diff options
| -rw-r--r-- | shar/python-0.9.1-01-21.shar | 656 | ||||
| -rw-r--r-- | shar/python-0.9.1-03-21.shar | 4038 | ||||
| -rw-r--r-- | shar/python-0.9.1-04-21.shar | 3802 | ||||
| -rw-r--r-- | shar/python-0.9.1-05-21.shar | 3484 | ||||
| -rw-r--r-- | shar/python-0.9.1-06-21.shar | 2234 | ||||
| -rw-r--r-- | shar/python-0.9.1-07-21.shar | 3864 | ||||
| -rw-r--r-- | shar/python-0.9.1-08-21.shar | 2256 | ||||
| -rw-r--r-- | shar/python-0.9.1-09-21.shar | 2988 | ||||
| -rw-r--r-- | shar/python-0.9.1-10-21.shar | 3570 | ||||
| -rw-r--r-- | shar/python-0.9.1-11-21.shar | 2776 | ||||
| -rw-r--r-- | shar/python-0.9.1-12-21.shar | 3756 | ||||
| -rw-r--r-- | shar/python-0.9.1-13-21.shar | 3500 | ||||
| -rw-r--r-- | shar/python-0.9.1-14-21.shar | 3612 | ||||
| -rw-r--r-- | shar/python-0.9.1-15-21.shar | 2740 | ||||
| -rw-r--r-- | shar/python-0.9.1-16-21.shar | 2608 | ||||
| -rw-r--r-- | shar/python-0.9.1-17-21.shar | 2520 | ||||
| -rw-r--r-- | shar/python-0.9.1-18-21.shar | 1992 | ||||
| -rw-r--r-- | shar/python-0.9.1-19-21.shar | 1156 | ||||
| -rw-r--r-- | shar/python-0.9.1-20-21.shar | 1338 | ||||
| -rw-r--r-- | shar/python-0.9.1-21-21.shar | 1356 |
20 files changed, 27123 insertions, 27123 deletions
diff --git a/shar/python-0.9.1-01-21.shar b/shar/python-0.9.1-01-21.shar index 75c124e..7b00e8a 100644 --- a/shar/python-0.9.1-01-21.shar +++ b/shar/python-0.9.1-01-21.shar @@ -35,43 +35,43 @@ XThis is version 0.9 (the first beta release), patchlevel 1. X XPython can be used instead of shell, Awk or Perl scripts, to write Xprototypes of real applications, or as an extension language of large -Xsystems, you name it. There are built-in modules that interface to +Xsystems, you name it. There are built-in modules that interface to Xthe operating system and to various window systems: X11, the Mac Xwindow system (you need STDWIN for these two), and Silicon Graphics' -XGL library. It runs on most modern versions of UNIX, on the Mac, and -XI wouldn't be surprised if it ran on MS-DOS unchanged. I developed it +XGL library. It runs on most modern versions of UNIX, on the Mac, and +XI wouldn't be surprised if it ran on MS-DOS unchanged. I developed it Xmostly on an SGI IRIS workstation (using IRIX 3.1 and 3.2) and on the XMac, but have tested it also on SunOS (4.1) and BSD 4.3 (tahoe). X XBuilding and installing Python is easy (but do read the Makefile). XA UNIX style manual page and extensive documentation (in LaTeX format) -Xare provided. (In the beta release, the documentation is still under +Xare provided. (In the beta release, the documentation is still under Xdevelopment.) X XPlease try it out and send me your comments (on anything -- the Xlanguage design, implementation, portability, installation, Xdocumentation) and the modules you wrote for it, to make the first -Xreal release better. If you needed to hack the source to get it to +Xreal release better. If you needed to hack the source to get it to Xcompile and run on a particular machine, send me the fixes -- I'll try -Xto incorporate them into the next patch. If you can't get it to work +Xto incorporate them into the next patch. If you can't get it to work Xat all, send me a *detailed* description of the problem and I may look Xinto it. X XIf you want to profit of the X11 or Mac window interface, you'll need -XSTDWIN. This is a portable window system interface by the same -Xauthor. The versions of STDWIN floating around on some archives are -Xnot sufficiently up-to-date for use with Python. I will distribute +XSTDWIN. This is a portable window system interface by the same +Xauthor. The versions of STDWIN floating around on some archives are +Xnot sufficiently up-to-date for use with Python. I will distribute Xthe latest and greatest STDWIN version at about the same time as Python. X XI am the author of Python: X -X Guido van Rossum -X CWI, dept. CST -X Kruislaan 413 -X 1098 SJ Amsterdam -X The Netherlands +X Guido van Rossum +X CWI, dept. CST +X Kruislaan 413 +X 1098 SJ Amsterdam +X The Netherlands X -X E-mail: [email protected] +X E-mail: [email protected] X XThe Python source is copyrighted, but you can freely use and copy it Xas long as you don't change or remove the copyright: @@ -80,7 +80,7 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X XPermission to use, copy, modify, and distribute this software and its Xdocumentation for any purpose and without fee is hereby granted, @@ -159,7 +159,7 @@ X.nf XGuido van Rossum XCWI, dept. CST XKruislaan 413 -X1098 SJ Amsterdam +X1098 SJ Amsterdam XThe Netherlands X.PP XE-mail: [email protected] @@ -194,7 +194,7 @@ echo 'x - demo/sgi/gl_panel/nurbs/nurbs.py' sed 's/^X//' > 'demo/sgi/gl_panel/nurbs/nurbs.py' << 'EOF' X#! /ufs/guido/bin/sgi/python X -X# Fancy NURBS demo. Require Z buffer and Panel Library. +X# Fancy NURBS demo. Require Z buffer and Panel Library. X Xfrom gl import * Xfrom GL import * @@ -205,187 +205,187 @@ X X# X# flags = trim_f, invis_f, cpvis_f, tpvis_f, axvis_f, freeze_f X# -XTRIM = 0 -XVIS = 1 -XCPVIS = 2 -XTPVIS = 3 -XAXVIS = 4 -XFREEZE = 5 +XTRIM = 0 +XVIS = 1 +XCPVIS = 2 +XTPVIS = 3 +XAXVIS = 4 +XFREEZE = 5 Xflags = [0, 1, 0, 0, 0, 0] X Xdef draw_axis () : -X cpack (0x0) -X zero = (0.0, 0.0, 0.0) -X # -X one = (1.0, 0.0, 0.0) -X smallline (zero, one) -X cmov (1.0, 0.0, 0.0) -X charstr ('x') -X # -X one = (0.0, 1.0, 0.0) -X smallline (zero, one) -X cmov (0.0, 1.0, 0.0) -X charstr ('y') -X # -X one = (0.0, 0.0, 1.0) -X smallline (zero, one) -X cmov (0.0, 0.0, 1.0) -X charstr ('z') +X cpack (0x0) +X zero = (0.0, 0.0, 0.0) +X # +X one = (1.0, 0.0, 0.0) +X smallline (zero, one) +X cmov (1.0, 0.0, 0.0) +X charstr ('x') +X # +X one = (0.0, 1.0, 0.0) +X smallline (zero, one) +X cmov (0.0, 1.0, 0.0) +X charstr ('y') +X # +X one = (0.0, 0.0, 1.0) +X smallline (zero, one) +X cmov (0.0, 0.0, 1.0) +X charstr ('z') X XDELTA = 0.1 X Xdef cross (p) : -X p0 = [p[0], p[1], p[2]] -X p1 = [p[0], p[1], p[2]] -X for i in range (0, 3) : -X p0[i] = p0[i] + DELTA -X p1[i] = p1[i] - DELTA -X smallline (p0, p1) -X p0[i] = p0[i] - DELTA -X p1[i] = p1[i] + DELTA +X p0 = [p[0], p[1], p[2]] +X p1 = [p[0], p[1], p[2]] +X for i in range (0, 3) : +X p0[i] = p0[i] + DELTA +X p1[i] = p1[i] - DELTA +X smallline (p0, p1) +X p0[i] = p0[i] - DELTA +X p1[i] = p1[i] + DELTA X Xdef smallline (p0, p1) : -X bgnline () -X v3f (p0) -X v3f (p1) -X endline () +X bgnline () +X v3f (p0) +X v3f (p1) +X endline () X Xdef draw_pts (pnts, color) : -X linewidth (2) -X cpack (color) -X for i in pnts : -X cross (i) +X linewidth (2) +X cpack (color) +X for i in pnts : +X cross (i) X Xdef init_windows(): -X foreground() -X wid = winopen('nurbs') -X wintitle('NURBS Surface') -X doublebuffer() -X RGBmode() -X gconfig() -X lsetdepth(0x000, 0x7fffff) -X zbuffer( TRUE ) +X foreground() +X wid = winopen('nurbs') +X wintitle('NURBS Surface') +X doublebuffer() +X RGBmode() +X gconfig() +X lsetdepth(0x000, 0x7fffff) +X zbuffer( TRUE ) X Xdef init_view(): -X mmode(MPROJECTION) -X ortho( -5., 5., -5., 5., -5., 5. ) -X # -X mmode(MVIEWING) -X loadmatrix(idmat) -X # -X lmbind(MATERIAL, 1) +X mmode(MPROJECTION) +X ortho( -5., 5., -5., 5., -5., 5. ) +X # +X mmode(MVIEWING) +X loadmatrix(idmat) +X # +X lmbind(MATERIAL, 1) X Xdef set_scene(flags): -X # -X lmbind(MATERIAL, 0) -X RGBcolor(150,150,150) -X lmbind(MATERIAL, 1) -X clear() -X zclear() -X # -X if not flags[FREEZE] : -X rotate( 100, 'y' ) -X rotate( 100, 'z' ) +X # +X lmbind(MATERIAL, 0) +X RGBcolor(150,150,150) +X lmbind(MATERIAL, 1) +X clear() +X zclear() +X # +X if not flags[FREEZE] : +X rotate( 100, 'y' ) +X rotate( 100, 'z' ) X Xdef draw_trim_surface(flags): -X pnts = ctlpoints -X if flags[VIS] : -X bgnsurface() -X nurbssurface(surfknots,surfknots,pnts,ORDER,ORDER,N_XYZ) -X if flags[TRIM]: -X bgntrim() -X nurbscurve(trimknots,trimpoints,ORDER-1,N_STW) -X endtrim() -X endsurface() -X # -X if flags[CPVIS] : -X for i in pnts : -X draw_pts (i, RED) -X # -X if flags[TPVIS] : -X tpts = trimpoints -X draw_pts (tpts, YELLOW) -X # -X if flags[AXVIS] : -X draw_axis () -X # -X swapbuffers() +X pnts = ctlpoints +X if flags[VIS] : +X bgnsurface() +X nurbssurface(surfknots,surfknots,pnts,ORDER,ORDER,N_XYZ) +X if flags[TRIM]: +X bgntrim() +X nurbscurve(trimknots,trimpoints,ORDER-1,N_STW) +X endtrim() +X endsurface() +X # +X if flags[CPVIS] : +X for i in pnts : +X draw_pts (i, RED) +X # +X if flags[TPVIS] : +X tpts = trimpoints +X draw_pts (tpts, YELLOW) +X # +X if flags[AXVIS] : +X draw_axis () +X # +X swapbuffers() X Xdef make_lights(): -X lmdef(DEFLMODEL,1,[]) -X lmdef(DEFLIGHT,1,[]) -X # -X # define material #1 -X # -X a = [] -X a = a + [EMISSION, 0.0, 0.0, 0.0] -X a = a + [AMBIENT, 0.1, 0.1, 0.1] -X a = a + [DIFFUSE, 0.6, 0.3, 0.3] -X a = a + [SPECULAR, 0.0, 0.6, 0.0] -X a = a + [SHININESS, 2.0] -X a = a + [LMNULL] -X lmdef(DEFMATERIAL, 1, a) -X # -X # turn on lighting -X # -X lmbind(LIGHT0, 1) -X lmbind(LMODEL, 1) +X lmdef(DEFLMODEL,1,[]) +X lmdef(DEFLIGHT,1,[]) +X # +X # define material #1 +X # +X a = [] +X a = a + [EMISSION, 0.0, 0.0, 0.0] +X a = a + [AMBIENT, 0.1, 0.1, 0.1] +X a = a + [DIFFUSE, 0.6, 0.3, 0.3] +X a = a + [SPECULAR, 0.0, 0.6, 0.0] +X a = a + [SHININESS, 2.0] +X a = a + [LMNULL] +X lmdef(DEFMATERIAL, 1, a) +X # +X # turn on lighting +X # +X lmbind(LIGHT0, 1) +X lmbind(LMODEL, 1) X Xdef main(): -X init_windows() -X make_lights() -X init_view() -X # -X panel.needredraw() -X panels = panel.defpanellist('nurbs.s') -X p = panels[0] -X # -X def cbtrim (a) : -X flags[TRIM:TRIM+1] = [int (a.val)] -X p.trim.upfunc = cbtrim -X # -X def cbquit (a) : -X import sys -X sys.exit (1) -X p.quit.upfunc = cbquit -X # -X def cbmotion (a) : -X flags[FREEZE:FREEZE+1] = [int (a.val)] -X p.motion.upfunc = cbmotion -X # -X def cbxyzaxis (a) : -X flags[AXVIS:AXVIS+1] = [int (a.val)] -X p.xyzaxis.upfunc = cbxyzaxis -X # -X def cbtrimpnts (a) : -X flags[TPVIS:TPVIS+1] = [int (a.val)] -X p.trimpnts.upfunc = cbtrimpnts -X # -X def cbcntlpnts (a) : -X flags[CPVIS:CPVIS+1] = [int (a.val)] -X p.cntlpnts.upfunc = cbcntlpnts -X # -X def cbnurb (a) : -X flags[VIS:VIS+1] = [int (a.val)] -X p.nurb.upfunc = cbnurb -X # -X set_scene(flags) -X setnurbsproperty( N_ERRORCHECKING, 1.0 ) -X setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) -X draw_trim_surface(flags) -X # -X while 1: -X act = panel.dopanel() -X # -X wid = panel.userredraw () -X if wid : -X winset (wid) -X reshapeviewport() -X set_scene(flags) -X draw_trim_surface(flags) -X # -X set_scene(flags) -X draw_trim_surface(flags) +X init_windows() +X make_lights() +X init_view() +X # +X panel.needredraw() +X panels = panel.defpanellist('nurbs.s') +X p = panels[0] +X # +X def cbtrim (a) : +X flags[TRIM:TRIM+1] = [int (a.val)] +X p.trim.upfunc = cbtrim +X # +X def cbquit (a) : +X import sys +X sys.exit (1) +X p.quit.upfunc = cbquit +X # +X def cbmotion (a) : +X flags[FREEZE:FREEZE+1] = [int (a.val)] +X p.motion.upfunc = cbmotion +X # +X def cbxyzaxis (a) : +X flags[AXVIS:AXVIS+1] = [int (a.val)] +X p.xyzaxis.upfunc = cbxyzaxis +X # +X def cbtrimpnts (a) : +X flags[TPVIS:TPVIS+1] = [int (a.val)] +X p.trimpnts.upfunc = cbtrimpnts +X # +X def cbcntlpnts (a) : +X flags[CPVIS:CPVIS+1] = [int (a.val)] +X p.cntlpnts.upfunc = cbcntlpnts +X # +X def cbnurb (a) : +X flags[VIS:VIS+1] = [int (a.val)] +X p.nurb.upfunc = cbnurb +X # +X set_scene(flags) +X setnurbsproperty( N_ERRORCHECKING, 1.0 ) +X setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) +X draw_trim_surface(flags) +X # +X while 1: +X act = panel.dopanel() +X # +X wid = panel.userredraw () +X if wid : +X winset (wid) +X reshapeviewport() +X set_scene(flags) +X draw_trim_surface(flags) +X # +X set_scene(flags) +X draw_trim_surface(flags) X Xmain() EOF @@ -407,10 +407,10 @@ X (DRAFT) X} X X\author{ -X Guido van Rossum \\ -X Dept. CST, CWI, Kruislaan 413 \\ -X 1098 SJ Amsterdam, The Netherlands \\ -X E-mail: {\tt [email protected]} +X Guido van Rossum \\ +X Dept. CST, CWI, Kruislaan 413 \\ +X 1098 SJ Amsterdam, The Netherlands \\ +X E-mail: {\tt [email protected]} X} X X\begin{document} @@ -552,15 +552,15 @@ X{\tt /usr/local} Xare possible; check with your local \Python\ guru or system Xadministrator.% X\footnote{ -X At CWI, at the time of writing, the interpreter can be found in -X the following places: -X On the Amoeba Ultrix machines, use the standard path, -X {\tt /usr/local/python}. -X On the Sun file servers, use -X {\tt /ufs/guido/bin/}{\em arch}{\tt /python}, -X where {\em arch} can be {\tt sgi} or {\tt sun4}. -X On piring, use {\tt /userfs3/amoeba/bin/python}. -X (If you can't find a binary advertised here, get in touch with me.) +X At CWI, at the time of writing, the interpreter can be found in +X the following places: +X On the Amoeba Ultrix machines, use the standard path, +X {\tt /usr/local/python}. +X On the Sun file servers, use +X {\tt /ufs/guido/bin/}{\em arch}{\tt /python}, +X where {\em arch} can be {\tt sgi} or {\tt sun4}. +X On piring, use {\tt /userfs3/amoeba/bin/python}. +X (If you can't find a binary advertised here, get in touch with me.) X} X XThe interpreter operates somewhat like the \UNIX\ shell: when called with @@ -570,13 +570,13 @@ Xstandard input, it reads and executes a X{\em script} Xfrom that file.% X\footnote{ -X There is a difference between ``{\tt python file}'' and -X ``{\tt python $<$file}''. In the latter case {\tt input()} and -X {\tt raw\_input()} are satisfied from {\em file}, which has -X already been read until the end by the parser, so they will read -X EOF immediately. In the former case (which is usually what -X you want) they are satisfied from whatever file or device is -X connected to standard input of the \Python\ interpreter. +X There is a difference between ``{\tt python file}'' and +X ``{\tt python $<$file}''. In the latter case {\tt input()} and +X {\tt raw\_input()} are satisfied from {\em file}, which has +X already been read until the end by the parser, so they will read +X EOF immediately. In the former case (which is usually what +X you want) they are satisfied from whatever file or device is +X connected to standard input of the \Python\ interpreter. X} XIf available, the script name and additional arguments thereafter are Xpassed to the script in the variable @@ -630,10 +630,10 @@ X{\tt PYTHONPATH} Xis not set, an installation-dependent default path is used, usually X{\tt .:/usr/local/lib/python}.% X\footnote{ -X Modules are really searched in the list of directories given by -X the variable {\tt sys.path} which is initialized from -X {\tt PYTHONPATH} or from the installation-dependent default. -X See the section on Standard Modules later. +X Modules are really searched in the list of directories given by +X the variable {\tt sys.path} which is initialized from +X {\tt PYTHONPATH} or from the installation-dependent default. +X See the section on Standard Modules later. X} X XOn BSD'ish \UNIX\ systems, \Python\ scripts can be made directly executable, @@ -660,10 +660,10 @@ Xhowever, the basics are easily explained. X XIf supported,% X\footnote{ -X Perhaps the quickest check to see whether command line editing -X is supported is typing Control-P to the first \Python\ prompt -X you get. If it beeps, you have command line editing. -X If not, you can skip the rest of this section. +X Perhaps the quickest check to see whether command line editing +X is supported is typing Control-P to the first \Python\ prompt +X you get. If it beeps, you have command line editing. +X If not, you can skip the rest of this section. X} Xinput line editing is active whenever the interpreter prints a primary Xor secondary prompt. @@ -821,9 +821,9 @@ X'He' X>>> word[2:4] X'lp' X>>> # Slice indices have useful defaults: -X>>> word[:2] # Take first two characters +X>>> word[:2] # Take first two characters X'He' -X>>> word[2:] # Drop first two characters +X>>> word[2:] # Drop first two characters X'lpA' X>>> # A useful invariant: s[:i] + s[i:] = s X>>> word[:3] + word[3:] @@ -846,12 +846,12 @@ XSlice indices (but not simple subscripts) may be negative numbers, to Xstart counting from the right. XFor example: X\bcode\begin{verbatim} -X>>> word[-2:] # Take last two characters +X>>> word[-2:] # Take last two characters X'pA' -X>>> word[:-2] # Drop last two characters +X>>> word[:-2] # Drop last two characters X'Hel' X>>> # But -0 does not count from the right! -X>>> word[-0:] # (since -0 equals 0) +X>>> word[-0:] # (since -0 equals 0) X'HelpA' X>>> X\end{verbatim}\ecode @@ -868,8 +868,8 @@ X\bcode\begin{verbatim} X +---+---+---+---+---+ X | H | e | l | p | A | X +---+---+---+---+---+ -X 0 1 2 3 4 5 -X-5 -4 -3 -2 -1 +X 0 1 2 3 4 5 +X-5 -4 -3 -2 -1 X\end{verbatim}\ecode XThe first row of numbers gives the position of the indices 0...5 in the Xstring; the second row gives the corresponding negative indices. @@ -968,8 +968,8 @@ X>>> # Fibonacci series: X>>> # the sum of two elements defines the next X>>> a, b = 0, 1 X>>> while b < 100: -X... print b -X... a, b = b, a+b +X... print b +X... a, b = b, a+b X... X1 X1 @@ -1014,9 +1014,9 @@ X{\tt >=} Xand X{\tt <>}.% X\footnote{ -X The ambiguity of using {\tt =} -X for both assignment and equality is resolved by disallowing -X unparenthesized conditions at the right hand side of assignments. +X The ambiguity of using {\tt =} +X for both assignment and equality is resolved by disallowing +X unparenthesized conditions at the right hand side of assignments. X} X\item XThe @@ -1049,8 +1049,8 @@ XA trailing comma avoids the newline after the output: X\bcode\begin{verbatim} X>>> a, b = 0, 1 X>>> while b < 1000: -X... print b, -X... a, b = b, a+b +X... print b, +X... a, b = b, a+b X... X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 X>>> @@ -1071,14 +1071,14 @@ XPerhaps the most well-known statement type is the {\tt if} statement. XFor example: X\bcode\begin{verbatim} X>>> if x < 0: -X... x = 0 -X... print 'Negative changed to zero' +X... x = 0 +X... print 'Negative changed to zero' X... elif x = 0: -X... print 'Zero' +X... print 'Zero' X... elif x = 1: -X... print 'Single' +X... print 'Single' X... else: -X... print 'More' +X... print 'More' X... X\end{verbatim}\ecode XThere can be zero or more {\tt elif} parts, and the {\tt else} part is @@ -1101,7 +1101,7 @@ X\bcode\begin{verbatim} X>>> # Measure some strings: X>>> a = ['cat', 'window', 'defenestrate'] X>>> for x in a: -X... print x, len(x) +X... print x, len(x) X... Xcat 3 Xwindow 6 @@ -1139,7 +1139,7 @@ Xand {\tt len()} as follows: X\bcode\begin{verbatim} X>>> a = ['Mary', 'had', 'a', 'little', 'boy'] X>>> for i in range(len(a)): -X... print i, a[i] +X... print i, a[i] X... X0 Mary X1 had @@ -1161,12 +1161,12 @@ XThis is exemplified by the following loop, which searches for a list Xitem of value 0: X\bcode\begin{verbatim} X>>> for n in range(2, 10): -X... for x in range(2, n): -X... if n % x = 0: -X... print n, 'equals', x, '*', n/x -X... break -X... else: -X... print n, 'is a prime number' +X... for x in range(2, n): +X... if n % x = 0: +X... print n, 'equals', x, '*', n/x +X... break +X... else: +X... print n, 'is a prime number' X... X2 is a prime number X3 is a prime number @@ -1187,7 +1187,7 @@ Xprogram requires no action. XFor example: X\bcode\begin{verbatim} X>>> while 1: -X... pass # Busy-wait for keyboard interrupt +X... pass # Busy-wait for keyboard interrupt X... X\end{verbatim}\ecode X @@ -1200,11 +1200,11 @@ X XWe can create a function that writes the Fibonacci series to an Xarbitrary boundary: X\bcode\begin{verbatim} -X>>> def fib(n): # write Fibonacci series up to n -X... a, b = 0, 1 -X... while b <= n: -X... print b, -X... a, b = b, a+b +X>>> def fib(n): # write Fibonacci series up to n +X... a, b = 0, 1 +X... while b <= n: +X... print b, +X... a, b = b, a+b X... X>>> # Now call the function we just defined: X>>> fib(2000) @@ -1235,10 +1235,10 @@ Xthe local symbol table of the called function when it is called; Xthus, arguments are passed using X{\em call\ by\ value}.% X\footnote{ -X Actually, {\em call by object reference} would be a better -X description, since if a mutable object is passed, the caller -X will see any changes the callee makes to it (e.g., items -X inserted into a list). +X Actually, {\em call by object reference} would be a better +X description, since if a mutable object is passed, the caller +X will see any changes the callee makes to it (e.g., items +X inserted into a list). X} XWhen a function calls another function, a new local symbol table is Xcreated for that call. @@ -1278,15 +1278,15 @@ XIt is simple to write a function that returns a list of the numbers of Xthe Fibonacci series, instead of printing it: X\bcode\begin{verbatim} X>>> def fib2(n): # return Fibonacci series up to n -X... result = [] -X... a, b = 0, 1 -X... while b <= n: -X... result.append(b) # see below -X... a, b = b, a+b -X... return result +X... result = [] +X... a, b = 0, 1 +X... while b <= n: +X... result.append(b) # see below +X... a, b = b, a+b +X... return result X... -X>>> f100 = fib2(100) # call it -X>>> f100 # write the result +X>>> f100 = fib2(100) # call it +X>>> f100 # write the result X[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] X>>> X\end{verbatim}\ecode @@ -1326,8 +1326,8 @@ XIn this case it is equivalent to X{\tt ret = ret + [b]}, Xbut more efficient.% X\footnote{ -X There is a subtle semantic difference if the object -X is referenced from more than one place. +X There is a subtle semantic difference if the object +X is referenced from more than one place. X} X\end{itemize} XThe list object type has two more methods: @@ -1391,19 +1391,19 @@ Xin the current directory with the following contents: X\bcode\begin{verbatim} X# Fibonacci numbers module X -Xdef fib(n): # write Fibonacci series up to n -X a, b = 0, 1 -X while b <= n: -X print b, -X a, b = b, a+b +Xdef fib(n): # write Fibonacci series up to n +X a, b = 0, 1 +X while b <= n: +X print b, +X a, b = b, a+b X Xdef fib2(n): # return Fibonacci series up to n -X ret = [] -X a, b = 0, 1 -X while b <= n: -X ret.append(b) -X a, b = b, a+b -X return ret +X ret = [] +X a, b = 0, 1 +X while b <= n: +X ret.append(b) +X a, b = b, a+b +X return ret X\end{verbatim}\ecode XNow enter the \Python\ interpreter and import this module with the Xfollowing command: @@ -1441,9 +1441,9 @@ XThey are executed only the X{\em first} Xtime the module is imported somewhere.% X\footnote{ -X In fact function definitions are also `statements' that are -X `executed'; the execution enters the function name in the -X module's global symbol table. +X In fact function definitions are also `statements' that are +X `executed'; the execution enters the function name in the +X module's global symbol table. X} X XEach module has its own private symbol table, which is used as the @@ -1555,7 +1555,7 @@ X\bcode\begin{verbatim} X>>> while 1 print 'Hello world' XParsing error: file <stdin>, line 1: Xwhile 1 print 'Hello world' -X ^ +X ^ XUnhandled exception: run-time error: syntax error X>>> X\end{verbatim}\ecode @@ -1576,15 +1576,15 @@ X\bcode\small\begin{verbatim} X>>> 10 * (1/0) XUnhandled exception: run-time error: integer division by zero XStack backtrace (innermost last): -X File "<stdin>", line 1 +X File "<stdin>", line 1 X>>> 4 + foo*3 XUnhandled exception: undefined name: foo XStack backtrace (innermost last): -X File "<stdin>", line 1 +X File "<stdin>", line 1 X>>> '2' + 2 XUnhandled exception: type error: illegal argument type for built-in operation XStack backtrace (innermost last): -X File "<stdin>", line 1 +X File "<stdin>", line 1 X>>> X\end{verbatim}\ecode XErrors detected during execution are called @@ -1621,9 +1621,9 @@ X{\em Undefined\ name} Xerrors are more serious: these are usually caused by misspelled Xidentifiers.% X\footnote{ -X The parser does not check whether names used in a program are at -X all defined elsewhere in the program, so such checks are -X postponed until run-time. The same holds for type checking. +X The parser does not check whether names used in a program are at +X all defined elsewhere in the program, so such checks are +X postponed until run-time. The same holds for type checking. X} XThe detail is the offending identifier. X\item @@ -1642,11 +1642,11 @@ Xsome floating point numbers: X\bcode\begin{verbatim} X>>> numbers = [0.3333, 2.5, 0.0, 10.0] X>>> for x in numbers: -X... print x, -X... try: -X... print 1.0 / x -X... except RuntimeError: -X... print '*** has no inverse ***' +X... print x, +X... try: +X... print 1.0 / x +X... except RuntimeError: +X... print '*** has no inverse ***' X... X0.3333 3.00030003 X2.5 0.4 @@ -1686,7 +1686,7 @@ XAn except clause may name multiple exceptions as a parenthesized list, Xe.g.: X\bcode\begin{verbatim} X... except (RuntimeError, TypeError, NameError): -X... pass +X... pass X\end{verbatim}\ecode XThe last except clause may omit the exception name(s), to serve as a Xwildcard. @@ -1701,9 +1701,9 @@ Xspecify a variable after the exception name (or list) to receive the Xargument's value, as follows: X\bcode\begin{verbatim} X>>> try: -X... foo() +X... foo() X... except NameError, x: -X... print 'name', x, 'undefined' +X... print 'name', x, 'undefined' X... Xname foo undefined X>>> @@ -1717,21 +1717,21 @@ XThese are in fact string objects whose X{\em object\ identity} X(not their value!) identifies the exceptions.% X\footnote{ -X There should really be a separate exception type; it is pure -X laziness that exceptions are identified by strings, and this may -X be fixed in the future. +X There should really be a separate exception type; it is pure +X laziness that exceptions are identified by strings, and this may +X be fixed in the future. X} XThe string is printed as the second part of the message for unhandled Xexceptions. XTheir names and values are: X\bcode\begin{verbatim} -XEOFError 'end-of-file read' -XKeyboardInterrupt 'keyboard interrupt' -XMemoryError 'out of memory' * -XNameError 'undefined name' * -XRuntimeError 'run-time error' * -XSystemError 'system error' * -XTypeError 'type error' * +XEOFError 'end-of-file read' +XKeyboardInterrupt 'keyboard interrupt' +XMemoryError 'out of memory' * +XNameError 'undefined name' * +XRuntimeError 'run-time error' * +XSystemError 'system error' * +XTypeError 'type error' * X\end{verbatim}\ecode XThe meanings should be clear enough. XThose exceptions with a {\tt *} in the third column have an argument. @@ -1742,12 +1742,12 @@ Xthat are called (even indirectly) in the try clause. XFor example: X\bcode\begin{verbatim} X>>> def this_fails(): -X... x = 1/0 +X... x = 1/0 X... X>>> try: -X... this_fails() +X... this_fails() X... except RuntimeError, detail: -X... print 'Handling run-time error:', detail +X... print 'Handling run-time error:', detail X... XHandling run-time error: domain error or zero division X>>> @@ -1762,7 +1762,7 @@ X\bcode\begin{verbatim} X>>> raise NameError, 'Hi There!' XUnhandled exception: undefined name: Hi There! XStack backtrace (innermost last): -X File "<stdin>", line 1 +X File "<stdin>", line 1 X>>> X\end{verbatim}\ecode XThe first argument to {\tt raise} names the exception to be raised. @@ -1776,15 +1776,15 @@ XFor example: X\bcode\begin{verbatim} X>>> my_exc = 'nobody likes me!' X>>> try: -X... raise my_exc, 2*2 +X... raise my_exc, 2*2 X... except my_exc, val: -X... print 'My exception occured, value:', val +X... print 'My exception occured, value:', val X... XMy exception occured, value: 4 X>>> raise my_exc, 1 XUnhandled exception: nobody likes me!: 1 XStack backtrace (innermost last): -X File "<stdin>", line 7 +X File "<stdin>", line 7 X>>> X\end{verbatim}\ecode XMany standard modules use this to report errors that may occur in @@ -1797,14 +1797,14 @@ Xdefine clean-up actions that must be executed under all circumstances. XFor example: X\bcode\begin{verbatim} X>>> try: -X... raise KeyboardInterrupt +X... raise KeyboardInterrupt X... finally: -X... print 'Goodbye, world!' +X... print 'Goodbye, world!' X... XGoodbye, world! XUnhandled exception: keyboard interrupt XStack backtrace (innermost last): -X File "<stdin>", line 2 +X File "<stdin>", line 2 X>>> X\end{verbatim}\ecode XThe @@ -1854,11 +1854,11 @@ XAlso, like Modula-3 but unlike C++, the built-in operators with special Xsyntax (arithmetic operators, subscripting etc.) cannot be redefined for Xclass members.% X\footnote{ -X They can be redefined for new object types implemented in C in -X extensions to the interpreter, however. It would require only a -X naming convention and a relatively small change to the -X interpreter to allow operator overloading for classes, so -X perhaps someday... +X They can be redefined for new object types implemented in C in +X extensions to the interpreter, however. It would require only a +X naming convention and a relatively small change to the +X interpreter to allow operator overloading for classes, so +X perhaps someday... X} X X\subsubsection{A Simple Example} @@ -1869,22 +1869,22 @@ Xremove elements, a membership test, and a request for the size of the Xset. X\bcode\begin{verbatim} Xclass Set(): -X def new(self): -X self.elements = [] -X return self -X def add(self, e): -X if e not in self.elements: -X self.elements.append(e) -X def remove(self, e): -X if e in self.elements: -X for i in range(len(self.elements)): -X if self.elements[i] = e: -X del self.elements[i] -X break -X def is_element(self, e): -X return e in self.elements -X def size(self): -X return len(self.elements) +X def new(self): +X self.elements = [] +X return self +X def add(self, e): +X if e not in self.elements: +X self.elements.append(e) +X def remove(self, e): +X if e in self.elements: +X for i in range(len(self.elements)): +X if self.elements[i] = e: +X del self.elements[i] +X break +X def is_element(self, e): +X return e in self.elements +X def size(self): +X return len(self.elements) X\end{verbatim}\ecode XNote that the class definition looks like a big compound statement, Xwith all the function definitons indented repective to the @@ -1936,13 +1936,13 @@ X X\section{XXX P.M.} X X\begin{itemize} -X\item The {\tt del} statement. -X\item The {\tt dir()} function. -X\item Tuples. -X\item Dictionaries. -X\item Objects and types in general. -X\item Backquotes. -X\item And/Or/Not. +X\item The {\tt del} statement. +X\item The {\tt dir()} function. +X\item Tuples. +X\item Dictionaries. +X\item Objects and types in general. +X\item Backquotes. +X\item And/Or/Not. X\end{itemize} X X\end{document} diff --git a/shar/python-0.9.1-03-21.shar b/shar/python-0.9.1-03-21.shar index b2f6af5..af4bac1 100644 --- a/shar/python-0.9.1-03-21.shar +++ b/shar/python-0.9.1-03-21.shar @@ -12,12 +12,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -35,9 +35,9 @@ X X/* Compile an expression node to intermediate code */ X X/* XXX TO DO: -X XXX Compute maximum needed stack sizes while compiling -X XXX Generate simple jump for break/return outside 'try...finally' -X XXX Include function name in code (and module names?) +X XXX Compute maximum needed stack sizes while compiling +X XXX Generate simple jump for break/return outside 'try...finally' +X XXX Include function name in code (and module names?) X*/ X X#include "allobjects.h" @@ -54,102 +54,102 @@ X X#define OFF(x) offsetof(codeobject, x) X Xstatic struct memberlist code_memberlist[] = { -X {"co_code", T_OBJECT, OFF(co_code)}, -X {"co_consts", T_OBJECT, OFF(co_consts)}, -X {"co_names", T_OBJECT, OFF(co_names)}, -X {"co_filename", T_OBJECT, OFF(co_filename)}, -X {NULL} /* Sentinel */ +X {"co_code", T_OBJECT, OFF(co_code)}, +X {"co_consts", T_OBJECT, OFF(co_consts)}, +X {"co_names", T_OBJECT, OFF(co_names)}, +X {"co_filename", T_OBJECT, OFF(co_filename)}, +X {NULL} /* Sentinel */ X}; X Xstatic object * Xcode_getattr(co, name) -X codeobject *co; -X char *name; +X codeobject *co; +X char *name; X{ -X return getmember((char *)co, code_memberlist, name); +X return getmember((char *)co, code_memberlist, name); X} X Xstatic void Xcode_dealloc(co) -X codeobject *co; +X codeobject *co; X{ -X XDECREF(co->co_code); -X XDECREF(co->co_consts); -X XDECREF(co->co_names); -X XDECREF(co->co_filename); -X DEL(co); +X XDECREF(co->co_code); +X XDECREF(co->co_consts); +X XDECREF(co->co_names); +X XDECREF(co->co_filename); +X DEL(co); X} X Xtypeobject Codetype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "code", -X sizeof(codeobject), -X 0, -X code_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X code_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "code", +X sizeof(codeobject), +X 0, +X code_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X code_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X Xstatic codeobject *newcodeobject PROTO((object *, object *, object *, char *)); X Xstatic codeobject * Xnewcodeobject(code, consts, names, filename) -X object *code; -X object *consts; -X object *names; -X char *filename; +X object *code; +X object *consts; +X object *names; +X char *filename; X{ -X codeobject *co; -X int i; -X /* Check argument types */ -X if (code == NULL || !is_stringobject(code) || -X consts == NULL || !is_listobject(consts) || -X names == NULL || !is_listobject(names)) { -X err_badcall(); -X return NULL; -X } -X /* Make sure the list of names contains only strings */ -X for (i = getlistsize(names); --i >= 0; ) { -X object *v = getlistitem(names, i); -X if (v == NULL || !is_stringobject(v)) { -X err_badcall(); -X return NULL; -X } -X } -X co = NEWOBJ(codeobject, &Codetype); -X if (co != NULL) { -X INCREF(code); -X co->co_code = (stringobject *)code; -X INCREF(consts); -X co->co_consts = consts; -X INCREF(names); -X co->co_names = names; -X if ((co->co_filename = newstringobject(filename)) == NULL) { -X DECREF(co); -X co = NULL; -X } -X } -X return co; +X codeobject *co; +X int i; +X /* Check argument types */ +X if (code == NULL || !is_stringobject(code) || +X consts == NULL || !is_listobject(consts) || +X names == NULL || !is_listobject(names)) { +X err_badcall(); +X return NULL; +X } +X /* Make sure the list of names contains only strings */ +X for (i = getlistsize(names); --i >= 0; ) { +X object *v = getlistitem(names, i); +X if (v == NULL || !is_stringobject(v)) { +X err_badcall(); +X return NULL; +X } +X } +X co = NEWOBJ(codeobject, &Codetype); +X if (co != NULL) { +X INCREF(code); +X co->co_code = (stringobject *)code; +X INCREF(consts); +X co->co_consts = consts; +X INCREF(names); +X co->co_names = names; +X if ((co->co_filename = newstringobject(filename)) == NULL) { +X DECREF(co); +X co = NULL; +X } +X } +X return co; X} X X X/* Data structure used internally */ Xstruct compiling { -X object *c_code; /* string */ -X object *c_consts; /* list of objects */ -X object *c_names; /* list of strings (names) */ -X int c_nexti; /* index into c_code */ -X int c_errors; /* counts errors occurred */ -X int c_infunction; /* set when compiling a function */ -X int c_loops; /* counts nested loops */ -X char *c_filename; /* filename of current node */ +X object *c_code; /* string */ +X object *c_consts; /* list of objects */ +X object *c_names; /* list of strings (names) */ +X int c_nexti; /* index into c_code */ +X int c_errors; /* counts errors occurred */ +X int c_infunction; /* set when compiling a function */ +X int c_loops; /* counts nested loops */ +X char *c_filename; /* filename of current node */ X}; X X/* Prototypes */ @@ -169,709 +169,709 @@ Xstatic void com_addopname PROTO((struct compiling *, int, node *)); X Xstatic int Xcom_init(c, filename) -X struct compiling *c; -X char *filename; +X struct compiling *c; +X char *filename; X{ -X if ((c->c_code = newsizedstringobject((char *)NULL, 0)) == NULL) -X goto fail_3; -X if ((c->c_consts = newlistobject(0)) == NULL) -X goto fail_2; -X if ((c->c_names = newlistobject(0)) == NULL) -X goto fail_1; -X c->c_nexti = 0; -X c->c_errors = 0; -X c->c_infunction = 0; -X c->c_loops = 0; -X c->c_filename = filename; -X return 1; -X -X fail_1: -X DECREF(c->c_consts); -X fail_2: -X DECREF(c->c_code); -X fail_3: -X return 0; +X if ((c->c_code = newsizedstringobject((char *)NULL, 0)) == NULL) +X goto fail_3; +X if ((c->c_consts = newlistobject(0)) == NULL) +X goto fail_2; +X if ((c->c_names = newlistobject(0)) == NULL) +X goto fail_1; +X c->c_nexti = 0; +X c->c_errors = 0; +X c->c_infunction = 0; +X c->c_loops = 0; +X c->c_filename = filename; +X return 1; +X +X fail_1: +X DECREF(c->c_consts); +X fail_2: +X DECREF(c->c_code); +X fail_3: +X return 0; X} X Xstatic void Xcom_free(c) -X struct compiling *c; +X struct compiling *c; X{ -X XDECREF(c->c_code); -X XDECREF(c->c_consts); -X XDECREF(c->c_names); +X XDECREF(c->c_code); +X XDECREF(c->c_consts); +X XDECREF(c->c_names); X} X Xstatic void Xcom_done(c) -X struct compiling *c; +X struct compiling *c; X{ -X if (c->c_code != NULL) -X resizestring(&c->c_code, c->c_nexti); +X if (c->c_code != NULL) +X resizestring(&c->c_code, c->c_nexti); X} X Xstatic void Xcom_addbyte(c, byte) -X struct compiling *c; -X int byte; +X struct compiling *c; +X int byte; X{ -X int len; -X if (byte < 0 || byte > 255) { -X fprintf(stderr, "XXX compiling bad byte: %d\n", byte); -X abort(); -X err_setstr(SystemError, "com_addbyte: byte out of range"); -X c->c_errors++; -X } -X if (c->c_code == NULL) -X return; -X len = getstringsize(c->c_code); -X if (c->c_nexti >= len) { -X if (resizestring(&c->c_code, len+1000) != 0) { -X c->c_errors++; -X return; -X } -X } -X getstringvalue(c->c_code)[c->c_nexti++] = byte; +X int len; +X if (byte < 0 || byte > 255) { +X fprintf(stderr, "XXX compiling bad byte: %d\n", byte); +X abort(); +X err_setstr(SystemError, "com_addbyte: byte out of range"); +X c->c_errors++; +X } +X if (c->c_code == NULL) +X return; +X len = getstringsize(c->c_code); +X if (c->c_nexti >= len) { +X if (resizestring(&c->c_code, len+1000) != 0) { +X c->c_errors++; +X return; +X } +X } +X getstringvalue(c->c_code)[c->c_nexti++] = byte; X} X Xstatic void Xcom_addint(c, x) -X struct compiling *c; -X int x; +X struct compiling *c; +X int x; X{ -X com_addbyte(c, x & 0xff); -X com_addbyte(c, x >> 8); /* XXX x should be positive */ +X com_addbyte(c, x & 0xff); +X com_addbyte(c, x >> 8); /* XXX x should be positive */ X} X Xstatic void Xcom_addoparg(c, op, arg) -X struct compiling *c; -X int op; -X int arg; +X struct compiling *c; +X int op; +X int arg; X{ -X com_addbyte(c, op); -X com_addint(c, arg); +X com_addbyte(c, op); +X com_addint(c, arg); X} X Xstatic void Xcom_addfwref(c, op, p_anchor) -X struct compiling *c; -X int op; -X int *p_anchor; +X struct compiling *c; +X int op; +X int *p_anchor; X{ -X /* Compile a forward reference for backpatching */ -X int here; -X int anchor; -X com_addbyte(c, op); -X here = c->c_nexti; -X anchor = *p_anchor; -X *p_anchor = here; -X com_addint(c, anchor == 0 ? 0 : here - anchor); +X /* Compile a forward reference for backpatching */ +X int here; +X int anchor; +X com_addbyte(c, op); +X here = c->c_nexti; +X anchor = *p_anchor; +X *p_anchor = here; +X com_addint(c, anchor == 0 ? 0 : here - anchor); X} X Xstatic void Xcom_backpatch(c, anchor) -X struct compiling *c; -X int anchor; /* Must be nonzero */ +X struct compiling *c; +X int anchor; /* Must be nonzero */ X{ -X unsigned char *code = (unsigned char *) getstringvalue(c->c_code); -X int target = c->c_nexti; -X int lastanchor = 0; -X int dist; -X int prev; -X for (;;) { -X /* Make the JUMP instruction at anchor point to target */ -X prev = code[anchor] + (code[anchor+1] << 8); -X dist = target - (anchor+2); -X code[anchor] = dist & 0xff; -X code[anchor+1] = dist >> 8; -X if (!prev) -X break; -X lastanchor = anchor; -X anchor -= prev; -X } +X unsigned char *code = (unsigned char *) getstringvalue(c->c_code); +X int target = c->c_nexti; +X int lastanchor = 0; +X int dist; +X int prev; +X for (;;) { +X /* Make the JUMP instruction at anchor point to target */ +X prev = code[anchor] + (code[anchor+1] << 8); +X dist = target - (anchor+2); +X code[anchor] = dist & 0xff; +X code[anchor+1] = dist >> 8; +X if (!prev) +X break; +X lastanchor = anchor; +X anchor -= prev; +X } X} X X/* Handle constants and names uniformly */ X Xstatic int Xcom_add(c, list, v) -X struct compiling *c; -X object *list; -X object *v; +X struct compiling *c; +X object *list; +X object *v; X{ -X int n = getlistsize(list); -X int i; -X for (i = n; --i >= 0; ) { -X object *w = getlistitem(list, i); -X if (cmpobject(v, w) == 0) -X return i; -X } -X if (addlistitem(list, v) != 0) -X c->c_errors++; -X return n; +X int n = getlistsize(list); +X int i; +X for (i = n; --i >= 0; ) { +X object *w = getlistitem(list, i); +X if (cmpobject(v, w) == 0) +X return i; +X } +X if (addlistitem(list, v) != 0) +X c->c_errors++; +X return n; X} X Xstatic int Xcom_addconst(c, v) -X struct compiling *c; -X object *v; +X struct compiling *c; +X object *v; X{ -X return com_add(c, c->c_consts, v); +X return com_add(c, c->c_consts, v); X} X Xstatic int Xcom_addname(c, v) -X struct compiling *c; -X object *v; +X struct compiling *c; +X object *v; X{ -X return com_add(c, c->c_names, v); +X return com_add(c, c->c_names, v); X} X Xstatic void Xcom_addopname(c, op, n) -X struct compiling *c; -X int op; -X node *n; +X struct compiling *c; +X int op; +X node *n; X{ -X object *v; -X int i; -X char *name; -X if (TYPE(n) == STAR) -X name = "*"; -X else { -X REQ(n, NAME); -X name = STR(n); -X } -X if ((v = newstringobject(name)) == NULL) { -X c->c_errors++; -X i = 255; -X } -X else { -X i = com_addname(c, v); -X DECREF(v); -X } -X com_addoparg(c, op, i); +X object *v; +X int i; +X char *name; +X if (TYPE(n) == STAR) +X name = "*"; +X else { +X REQ(n, NAME); +X name = STR(n); +X } +X if ((v = newstringobject(name)) == NULL) { +X c->c_errors++; +X i = 255; +X } +X else { +X i = com_addname(c, v); +X DECREF(v); +X } +X com_addoparg(c, op, i); X} X Xstatic object * Xparsenumber(s) -X char *s; +X char *s; X{ -X extern long strtol(); -X extern double atof(); -X char *end = s; -X long x; -X x = strtol(s, &end, 0); -X if (*end == '\0') -X return newintobject(x); -X if (*end == '.' || *end == 'e' || *end == 'E') -X return newfloatobject(atof(s)); -X err_setstr(RuntimeError, "bad number syntax"); -X return NULL; +X extern long strtol(); +X extern double atof(); +X char *end = s; +X long x; +X x = strtol(s, &end, 0); +X if (*end == '\0') +X return newintobject(x); +X if (*end == '.' || *end == 'e' || *end == 'E') +X return newfloatobject(atof(s)); +X err_setstr(RuntimeError, "bad number syntax"); +X return NULL; X} X Xstatic object * Xparsestr(s) -X char *s; +X char *s; X{ -X object *v; -X int len; -X char *buf; -X char *p; -X int c; -X if (*s != '\'') { -X err_badcall(); -X return NULL; -X } -X s++; -X len = strlen(s); -X if (s[--len] != '\'') { -X err_badcall(); -X return NULL; -X } -X if (strchr(s, '\\') == NULL) -X return newsizedstringobject(s, len); -X v = newsizedstringobject((char *)NULL, len); -X p = buf = getstringvalue(v); -X while (*s != '\0' && *s != '\'') { -X if (*s != '\\') { -X *p++ = *s++; -X continue; -X } -X s++; -X switch (*s++) { -X /* XXX This assumes ASCII! */ -X case '\\': *p++ = '\\'; break; -X case '\'': *p++ = '\''; break; -X case 'b': *p++ = '\b'; break; -X case 'f': *p++ = '\014'; break; /* FF */ -X case 't': *p++ = '\t'; break; -X case 'n': *p++ = '\n'; break; -X case 'r': *p++ = '\r'; break; -X case 'v': *p++ = '\013'; break; /* VT */ -X case 'E': *p++ = '\033'; break; /* ESC, not C */ -X case 'a': *p++ = '\007'; break; /* BEL, not classic C */ -X case '0': case '1': case '2': case '3': -X case '4': case '5': case '6': case '7': -X c = s[-1] - '0'; -X if ('0' <= *s && *s <= '7') { -X c = (c<<3) + *s++ - '0'; -X if ('0' <= *s && *s <= '7') -X c = (c<<3) + *s++ - '0'; -X } -X *p++ = c; -X break; -X case 'x': -X if (isxdigit(*s)) { -X sscanf(s, "%x", &c); -X *p++ = c; -X do { -X s++; -X } while (isxdigit(*s)); -X break; -X } -X /* FALLTHROUGH */ -X default: *p++ = '\\'; *p++ = s[-1]; break; -X } -X } -X resizestring(&v, (int)(p - buf)); -X return v; +X object *v; +X int len; +X char *buf; +X char *p; +X int c; +X if (*s != '\'') { +X err_badcall(); +X return NULL; +X } +X s++; +X len = strlen(s); +X if (s[--len] != '\'') { +X err_badcall(); +X return NULL; +X } +X if (strchr(s, '\\') == NULL) +X return newsizedstringobject(s, len); +X v = newsizedstringobject((char *)NULL, len); +X p = buf = getstringvalue(v); +X while (*s != '\0' && *s != '\'') { +X if (*s != '\\') { +X *p++ = *s++; +X continue; +X } +X s++; +X switch (*s++) { +X /* XXX This assumes ASCII! */ +X case '\\': *p++ = '\\'; break; +X case '\'': *p++ = '\''; break; +X case 'b': *p++ = '\b'; break; +X case 'f': *p++ = '\014'; break; /* FF */ +X case 't': *p++ = '\t'; break; +X case 'n': *p++ = '\n'; break; +X case 'r': *p++ = '\r'; break; +X case 'v': *p++ = '\013'; break; /* VT */ +X case 'E': *p++ = '\033'; break; /* ESC, not C */ +X case 'a': *p++ = '\007'; break; /* BEL, not classic C */ +X case '0': case '1': case '2': case '3': +X case '4': case '5': case '6': case '7': +X c = s[-1] - '0'; +X if ('0' <= *s && *s <= '7') { +X c = (c<<3) + *s++ - '0'; +X if ('0' <= *s && *s <= '7') +X c = (c<<3) + *s++ - '0'; +X } +X *p++ = c; +X break; +X case 'x': +X if (isxdigit(*s)) { +X sscanf(s, "%x", &c); +X *p++ = c; +X do { +X s++; +X } while (isxdigit(*s)); +X break; +X } +X /* FALLTHROUGH */ +X default: *p++ = '\\'; *p++ = s[-1]; break; +X } +X } +X resizestring(&v, (int)(p - buf)); +X return v; X} X Xstatic void Xcom_list_constructor(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int len; -X int i; -X object *v, *w; -X if (TYPE(n) != testlist) -X REQ(n, exprlist); -X /* exprlist: expr (',' expr)* [',']; likewise for testlist */ -X len = (NCH(n) + 1) / 2; -X for (i = 0; i < NCH(n); i += 2) -X com_node(c, CHILD(n, i)); -X com_addoparg(c, BUILD_LIST, len); +X int len; +X int i; +X object *v, *w; +X if (TYPE(n) != testlist) +X REQ(n, exprlist); +X /* exprlist: expr (',' expr)* [',']; likewise for testlist */ +X len = (NCH(n) + 1) / 2; +X for (i = 0; i < NCH(n); i += 2) +X com_node(c, CHILD(n, i)); +X com_addoparg(c, BUILD_LIST, len); X} X Xstatic void Xcom_atom(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X node *ch; -X object *v; -X int i; -X REQ(n, atom); -X ch = CHILD(n, 0); -X switch (TYPE(ch)) { -X case LPAR: -X if (TYPE(CHILD(n, 1)) == RPAR) -X com_addoparg(c, BUILD_TUPLE, 0); -X else -X com_node(c, CHILD(n, 1)); -X break; -X case LSQB: -X if (TYPE(CHILD(n, 1)) == RSQB) -X com_addoparg(c, BUILD_LIST, 0); -X else -X com_list_constructor(c, CHILD(n, 1)); -X break; -X case LBRACE: -X com_addoparg(c, BUILD_MAP, 0); -X break; -X case BACKQUOTE: -X com_node(c, CHILD(n, 1)); -X com_addbyte(c, UNARY_CONVERT); -X break; -X case NUMBER: -X if ((v = parsenumber(STR(ch))) == NULL) { -X c->c_errors++; -X i = 255; -X } -X else { -X i = com_addconst(c, v); -X DECREF(v); -X } -X com_addoparg(c, LOAD_CONST, i); -X break; -X case STRING: -X if ((v = parsestr(STR(ch))) == NULL) { -X c->c_errors++; -X i = 255; -X } -X else { -X i = com_addconst(c, v); -X DECREF(v); -X } -X com_addoparg(c, LOAD_CONST, i); -X break; -X case NAME: -X com_addopname(c, LOAD_NAME, ch); -X break; -X default: -X fprintf(stderr, "node type %d\n", TYPE(ch)); -X err_setstr(SystemError, "com_atom: unexpected node type"); -X c->c_errors++; -X } +X node *ch; +X object *v; +X int i; +X REQ(n, atom); +X ch = CHILD(n, 0); +X switch (TYPE(ch)) { +X case LPAR: +X if (TYPE(CHILD(n, 1)) == RPAR) +X com_addoparg(c, BUILD_TUPLE, 0); +X else +X com_node(c, CHILD(n, 1)); +X break; +X case LSQB: +X if (TYPE(CHILD(n, 1)) == RSQB) +X com_addoparg(c, BUILD_LIST, 0); +X else +X com_list_constructor(c, CHILD(n, 1)); +X break; +X case LBRACE: +X com_addoparg(c, BUILD_MAP, 0); +X break; +X case BACKQUOTE: +X com_node(c, CHILD(n, 1)); +X com_addbyte(c, UNARY_CONVERT); +X break; +X case NUMBER: +X if ((v = parsenumber(STR(ch))) == NULL) { +X c->c_errors++; +X i = 255; +X } +X else { +X i = com_addconst(c, v); +X DECREF(v); +X } +X com_addoparg(c, LOAD_CONST, i); +X break; +X case STRING: +X if ((v = parsestr(STR(ch))) == NULL) { +X c->c_errors++; +X i = 255; +X } +X else { +X i = com_addconst(c, v); +X DECREF(v); +X } +X com_addoparg(c, LOAD_CONST, i); +X break; +X case NAME: +X com_addopname(c, LOAD_NAME, ch); +X break; +X default: +X fprintf(stderr, "node type %d\n", TYPE(ch)); +X err_setstr(SystemError, "com_atom: unexpected node type"); +X c->c_errors++; +X } X} X Xstatic void Xcom_slice(c, n, op) -X struct compiling *c; -X node *n; -X int op; +X struct compiling *c; +X node *n; +X int op; X{ -X if (NCH(n) == 1) { -X com_addbyte(c, op); -X } -X else if (NCH(n) == 2) { -X if (TYPE(CHILD(n, 0)) != COLON) { -X com_node(c, CHILD(n, 0)); -X com_addbyte(c, op+1); -X } -X else { -X com_node(c, CHILD(n, 1)); -X com_addbyte(c, op+2); -X } -X } -X else { -X com_node(c, CHILD(n, 0)); -X com_node(c, CHILD(n, 2)); -X com_addbyte(c, op+3); -X } +X if (NCH(n) == 1) { +X com_addbyte(c, op); +X } +X else if (NCH(n) == 2) { +X if (TYPE(CHILD(n, 0)) != COLON) { +X com_node(c, CHILD(n, 0)); +X com_addbyte(c, op+1); +X } +X else { +X com_node(c, CHILD(n, 1)); +X com_addbyte(c, op+2); +X } +X } +X else { +X com_node(c, CHILD(n, 0)); +X com_node(c, CHILD(n, 2)); +X com_addbyte(c, op+3); +X } X} X Xstatic void Xcom_apply_subscript(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, subscript); -X if (NCH(n) == 1 && TYPE(CHILD(n, 0)) != COLON) { -X /* It's a single subscript */ -X com_node(c, CHILD(n, 0)); -X com_addbyte(c, BINARY_SUBSCR); -X } -X else { -X /* It's a slice: [expr] ':' [expr] */ -X com_slice(c, n, SLICE); -X } +X REQ(n, subscript); +X if (NCH(n) == 1 && TYPE(CHILD(n, 0)) != COLON) { +X /* It's a single subscript */ +X com_node(c, CHILD(n, 0)); +X com_addbyte(c, BINARY_SUBSCR); +X } +X else { +X /* It's a slice: [expr] ':' [expr] */ +X com_slice(c, n, SLICE); +X } X} X Xstatic void Xcom_call_function(c, n) -X struct compiling *c; -X node *n; /* EITHER testlist OR ')' */ +X struct compiling *c; +X node *n; /* EITHER testlist OR ')' */ X{ -X if (TYPE(n) == RPAR) { -X com_addbyte(c, UNARY_CALL); -X } -X else { -X com_node(c, n); -X com_addbyte(c, BINARY_CALL); -X } +X if (TYPE(n) == RPAR) { +X com_addbyte(c, UNARY_CALL); +X } +X else { +X com_node(c, n); +X com_addbyte(c, BINARY_CALL); +X } X} X Xstatic void Xcom_select_member(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X com_addopname(c, LOAD_ATTR, n); +X com_addopname(c, LOAD_ATTR, n); X} X Xstatic void Xcom_apply_trailer(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, trailer); -X switch (TYPE(CHILD(n, 0))) { -X case LPAR: -X com_call_function(c, CHILD(n, 1)); -X break; -X case DOT: -X com_select_member(c, CHILD(n, 1)); -X break; -X case LSQB: -X com_apply_subscript(c, CHILD(n, 1)); -X break; -X default: -X err_setstr(SystemError, -X "com_apply_trailer: unknown trailer type"); -X c->c_errors++; -X } +X REQ(n, trailer); +X switch (TYPE(CHILD(n, 0))) { +X case LPAR: +X com_call_function(c, CHILD(n, 1)); +X break; +X case DOT: +X com_select_member(c, CHILD(n, 1)); +X break; +X case LSQB: +X com_apply_subscript(c, CHILD(n, 1)); +X break; +X default: +X err_setstr(SystemError, +X "com_apply_trailer: unknown trailer type"); +X c->c_errors++; +X } X} X Xstatic void Xcom_factor(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X REQ(n, factor); -X if (TYPE(CHILD(n, 0)) == PLUS) { -X com_factor(c, CHILD(n, 1)); -X com_addbyte(c, UNARY_POSITIVE); -X } -X else if (TYPE(CHILD(n, 0)) == MINUS) { -X com_factor(c, CHILD(n, 1)); -X com_addbyte(c, UNARY_NEGATIVE); -X } -X else { -X com_atom(c, CHILD(n, 0)); -X for (i = 1; i < NCH(n); i++) -X com_apply_trailer(c, CHILD(n, i)); -X } +X int i; +X REQ(n, factor); +X if (TYPE(CHILD(n, 0)) == PLUS) { +X com_factor(c, CHILD(n, 1)); +X com_addbyte(c, UNARY_POSITIVE); +X } +X else if (TYPE(CHILD(n, 0)) == MINUS) { +X com_factor(c, CHILD(n, 1)); +X com_addbyte(c, UNARY_NEGATIVE); +X } +X else { +X com_atom(c, CHILD(n, 0)); +X for (i = 1; i < NCH(n); i++) +X com_apply_trailer(c, CHILD(n, i)); +X } X} X Xstatic void Xcom_term(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X int op; -X REQ(n, term); -X com_factor(c, CHILD(n, 0)); -X for (i = 2; i < NCH(n); i += 2) { -X com_factor(c, CHILD(n, i)); -X switch (TYPE(CHILD(n, i-1))) { -X case STAR: -X op = BINARY_MULTIPLY; -X break; -X case SLASH: -X op = BINARY_DIVIDE; -X break; -X case PERCENT: -X op = BINARY_MODULO; -X break; -X default: -X err_setstr(SystemError, -X "com_term: term operator not *, / or %"); -X c->c_errors++; -X op = 255; -X } -X com_addbyte(c, op); -X } +X int i; +X int op; +X REQ(n, term); +X com_factor(c, CHILD(n, 0)); +X for (i = 2; i < NCH(n); i += 2) { +X com_factor(c, CHILD(n, i)); +X switch (TYPE(CHILD(n, i-1))) { +X case STAR: +X op = BINARY_MULTIPLY; +X break; +X case SLASH: +X op = BINARY_DIVIDE; +X break; +X case PERCENT: +X op = BINARY_MODULO; +X break; +X default: +X err_setstr(SystemError, +X "com_term: term operator not *, / or %"); +X c->c_errors++; +X op = 255; +X } +X com_addbyte(c, op); +X } X} X Xstatic void Xcom_expr(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X int op; -X REQ(n, expr); -X com_term(c, CHILD(n, 0)); -X for (i = 2; i < NCH(n); i += 2) { -X com_term(c, CHILD(n, i)); -X switch (TYPE(CHILD(n, i-1))) { -X case PLUS: -X op = BINARY_ADD; -X break; -X case MINUS: -X op = BINARY_SUBTRACT; -X break; -X default: -X err_setstr(SystemError, -X "com_expr: expr operator not + or -"); -X c->c_errors++; -X op = 255; -X } -X com_addbyte(c, op); -X } +X int i; +X int op; +X REQ(n, expr); +X com_term(c, CHILD(n, 0)); +X for (i = 2; i < NCH(n); i += 2) { +X com_term(c, CHILD(n, i)); +X switch (TYPE(CHILD(n, i-1))) { +X case PLUS: +X op = BINARY_ADD; +X break; +X case MINUS: +X op = BINARY_SUBTRACT; +X break; +X default: +X err_setstr(SystemError, +X "com_expr: expr operator not + or -"); +X c->c_errors++; +X op = 255; +X } +X com_addbyte(c, op); +X } X} X Xstatic enum cmp_op Xcmp_type(n) -X node *n; +X node *n; X{ -X REQ(n, comp_op); -X /* comp_op: '<' | '>' | '=' | '>' '=' | '<' '=' | '<' '>' -X | 'in' | 'not' 'in' | 'is' | 'is' not' */ -X if (NCH(n) == 1) { -X n = CHILD(n, 0); -X switch (TYPE(n)) { -X case LESS: return LT; -X case GREATER: return GT; -X case EQUAL: return EQ; -X case NAME: if (strcmp(STR(n), "in") == 0) return IN; -X if (strcmp(STR(n), "is") == 0) return IS; -X } -X } -X else if (NCH(n) == 2) { -X int t2 = TYPE(CHILD(n, 1)); -X switch (TYPE(CHILD(n, 0))) { -X case LESS: if (t2 == EQUAL) return LE; -X if (t2 == GREATER) return NE; -X break; -X case GREATER: if (t2 == EQUAL) return GE; -X break; -X case NAME: if (strcmp(STR(CHILD(n, 1)), "in") == 0) -X return NOT_IN; -X if (strcmp(STR(CHILD(n, 0)), "is") == 0) -X return IS_NOT; -X } -X } -X return BAD; +X REQ(n, comp_op); +X /* comp_op: '<' | '>' | '=' | '>' '=' | '<' '=' | '<' '>' +X | 'in' | 'not' 'in' | 'is' | 'is' not' */ +X if (NCH(n) == 1) { +X n = CHILD(n, 0); +X switch (TYPE(n)) { +X case LESS: return LT; +X case GREATER: return GT; +X case EQUAL: return EQ; +X case NAME: if (strcmp(STR(n), "in") == 0) return IN; +X if (strcmp(STR(n), "is") == 0) return IS; +X } +X } +X else if (NCH(n) == 2) { +X int t2 = TYPE(CHILD(n, 1)); +X switch (TYPE(CHILD(n, 0))) { +X case LESS: if (t2 == EQUAL) return LE; +X if (t2 == GREATER) return NE; +X break; +X case GREATER: if (t2 == EQUAL) return GE; +X break; +X case NAME: if (strcmp(STR(CHILD(n, 1)), "in") == 0) +X return NOT_IN; +X if (strcmp(STR(CHILD(n, 0)), "is") == 0) +X return IS_NOT; +X } +X } +X return BAD; X} X Xstatic void Xcom_comparison(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X enum cmp_op op; -X int anchor; -X REQ(n, comparison); /* comparison: expr (comp_op expr)* */ -X com_expr(c, CHILD(n, 0)); -X if (NCH(n) == 1) -X return; -X -X /**************************************************************** -X The following code is generated for all but the last -X comparison in a chain: -X -X label: on stack: opcode: jump to: -X -X a <code to load b> -X a, b DUP_TOP -X a, b, b ROT_THREE -X b, a, b COMPARE_OP -X b, 0-or-1 JUMP_IF_FALSE L1 -X b, 1 POP_TOP -X b -X -X We are now ready to repeat this sequence for the next -X comparison in the chain. -X -X For the last we generate: -X -X b <code to load c> -X b, c COMPARE_OP -X 0-or-1 -X -X If there were any jumps to L1 (i.e., there was more than one -X comparison), we generate: -X -X 0-or-1 JUMP_FORWARD L2 -X L1: b, 0 ROT_TWO -X 0, b POP_TOP -X 0 -X L2: -X ****************************************************************/ -X -X anchor = 0; -X -X for (i = 2; i < NCH(n); i += 2) { -X com_expr(c, CHILD(n, i)); -X if (i+2 < NCH(n)) { -X com_addbyte(c, DUP_TOP); -X com_addbyte(c, ROT_THREE); -X } -X op = cmp_type(CHILD(n, i-1)); -X if (op == BAD) { -X err_setstr(SystemError, -X "com_comparison: unknown comparison op"); -X c->c_errors++; -X } -X com_addoparg(c, COMPARE_OP, op); -X if (i+2 < NCH(n)) { -X com_addfwref(c, JUMP_IF_FALSE, &anchor); -X com_addbyte(c, POP_TOP); -X } -X } -X -X if (anchor) { -X int anchor2 = 0; -X com_addfwref(c, JUMP_FORWARD, &anchor2); -X com_backpatch(c, anchor); -X com_addbyte(c, ROT_TWO); -X com_addbyte(c, POP_TOP); -X com_backpatch(c, anchor2); -X } +X int i; +X enum cmp_op op; +X int anchor; +X REQ(n, comparison); /* comparison: expr (comp_op expr)* */ +X com_expr(c, CHILD(n, 0)); +X if (NCH(n) == 1) +X return; +X +X /**************************************************************** +X The following code is generated for all but the last +X comparison in a chain: +X +X label: on stack: opcode: jump to: +X +X a <code to load b> +X a, b DUP_TOP +X a, b, b ROT_THREE +X b, a, b COMPARE_OP +X b, 0-or-1 JUMP_IF_FALSE L1 +X b, 1 POP_TOP +X b +X +X We are now ready to repeat this sequence for the next +X comparison in the chain. +X +X For the last we generate: +X +X b <code to load c> +X b, c COMPARE_OP +X 0-or-1 +X +X If there were any jumps to L1 (i.e., there was more than one +X comparison), we generate: +X +X 0-or-1 JUMP_FORWARD L2 +X L1: b, 0 ROT_TWO +X 0, b POP_TOP +X 0 +X L2: +X ****************************************************************/ +X +X anchor = 0; +X +X for (i = 2; i < NCH(n); i += 2) { +X com_expr(c, CHILD(n, i)); +X if (i+2 < NCH(n)) { +X com_addbyte(c, DUP_TOP); +X com_addbyte(c, ROT_THREE); +X } +X op = cmp_type(CHILD(n, i-1)); +X if (op == BAD) { +X err_setstr(SystemError, +X "com_comparison: unknown comparison op"); +X c->c_errors++; +X } +X com_addoparg(c, COMPARE_OP, op); +X if (i+2 < NCH(n)) { +X com_addfwref(c, JUMP_IF_FALSE, &anchor); +X com_addbyte(c, POP_TOP); +X } +X } +X +X if (anchor) { +X int anchor2 = 0; +X com_addfwref(c, JUMP_FORWARD, &anchor2); +X com_backpatch(c, anchor); +X com_addbyte(c, ROT_TWO); +X com_addbyte(c, POP_TOP); +X com_backpatch(c, anchor2); +X } X} X Xstatic void Xcom_not_test(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, not_test); /* 'not' not_test | comparison */ -X if (NCH(n) == 1) { -X com_comparison(c, CHILD(n, 0)); -X } -X else { -X com_not_test(c, CHILD(n, 1)); -X com_addbyte(c, UNARY_NOT); -X } +X REQ(n, not_test); /* 'not' not_test | comparison */ +X if (NCH(n) == 1) { +X com_comparison(c, CHILD(n, 0)); +X } +X else { +X com_not_test(c, CHILD(n, 1)); +X com_addbyte(c, UNARY_NOT); +X } X} X Xstatic void Xcom_and_test(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X int anchor; -X REQ(n, and_test); /* not_test ('and' not_test)* */ -X anchor = 0; -X i = 0; -X for (;;) { -X com_not_test(c, CHILD(n, i)); -X if ((i += 2) >= NCH(n)) -X break; -X com_addfwref(c, JUMP_IF_FALSE, &anchor); -X com_addbyte(c, POP_TOP); -X } -X if (anchor) -X com_backpatch(c, anchor); +X int i; +X int anchor; +X REQ(n, and_test); /* not_test ('and' not_test)* */ +X anchor = 0; +X i = 0; +X for (;;) { +X com_not_test(c, CHILD(n, i)); +X if ((i += 2) >= NCH(n)) +X break; +X com_addfwref(c, JUMP_IF_FALSE, &anchor); +X com_addbyte(c, POP_TOP); +X } +X if (anchor) +X com_backpatch(c, anchor); X} X Xstatic void Xcom_test(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X int anchor; -X REQ(n, test); /* and_test ('and' and_test)* */ -X anchor = 0; -X i = 0; -X for (;;) { -X com_and_test(c, CHILD(n, i)); -X if ((i += 2) >= NCH(n)) -X break; -X com_addfwref(c, JUMP_IF_TRUE, &anchor); -X com_addbyte(c, POP_TOP); -X } -X if (anchor) -X com_backpatch(c, anchor); +X int i; +X int anchor; +X REQ(n, test); /* and_test ('and' and_test)* */ +X anchor = 0; +X i = 0; +X for (;;) { +X com_and_test(c, CHILD(n, i)); +X if ((i += 2) >= NCH(n)) +X break; +X com_addfwref(c, JUMP_IF_TRUE, &anchor); +X com_addbyte(c, POP_TOP); +X } +X if (anchor) +X com_backpatch(c, anchor); X} X Xstatic void Xcom_list(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X /* exprlist: expr (',' expr)* [',']; likewise for testlist */ -X if (NCH(n) == 1) { -X com_node(c, CHILD(n, 0)); -X } -X else { -X int i; -X int len; -X len = (NCH(n) + 1) / 2; -X for (i = 0; i < NCH(n); i += 2) -X com_node(c, CHILD(n, i)); -X com_addoparg(c, BUILD_TUPLE, len); -X } +X /* exprlist: expr (',' expr)* [',']; likewise for testlist */ +X if (NCH(n) == 1) { +X com_node(c, CHILD(n, 0)); +X } +X else { +X int i; +X int len; +X len = (NCH(n) + 1) / 2; +X for (i = 0; i < NCH(n); i += 2) +X com_node(c, CHILD(n, i)); +X com_addoparg(c, BUILD_TUPLE, len); +X } X} X X @@ -882,903 +882,903 @@ Xstatic void com_assign PROTO((struct compiling *, node *, int)); X Xstatic void Xcom_assign_attr(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n); +X com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n); X} X Xstatic void Xcom_assign_slice(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X com_slice(c, n, assigning ? STORE_SLICE : DELETE_SLICE); +X com_slice(c, n, assigning ? STORE_SLICE : DELETE_SLICE); X} X Xstatic void Xcom_assign_subscript(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X com_node(c, n); -X com_addbyte(c, assigning ? STORE_SUBSCR : DELETE_SUBSCR); +X com_node(c, n); +X com_addbyte(c, assigning ? STORE_SUBSCR : DELETE_SUBSCR); X} X Xstatic void Xcom_assign_trailer(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X char *name; -X REQ(n, trailer); -X switch (TYPE(CHILD(n, 0))) { -X case LPAR: /* '(' [exprlist] ')' */ -X err_setstr(TypeError, "can't assign to function call"); -X c->c_errors++; -X break; -X case DOT: /* '.' NAME */ -X com_assign_attr(c, CHILD(n, 1), assigning); -X break; -X case LSQB: /* '[' subscript ']' */ -X n = CHILD(n, 1); -X REQ(n, subscript); /* subscript: expr | [expr] ':' [expr] */ -X if (NCH(n) > 1 || TYPE(CHILD(n, 0)) == COLON) -X com_assign_slice(c, n, assigning); -X else -X com_assign_subscript(c, CHILD(n, 0), assigning); -X break; -X default: -X err_setstr(TypeError, "unknown trailer type"); -X c->c_errors++; -X } +X char *name; +X REQ(n, trailer); +X switch (TYPE(CHILD(n, 0))) { +X case LPAR: /* '(' [exprlist] ')' */ +X err_setstr(TypeError, "can't assign to function call"); +X c->c_errors++; +X break; +X case DOT: /* '.' NAME */ +X com_assign_attr(c, CHILD(n, 1), assigning); +X break; +X case LSQB: /* '[' subscript ']' */ +X n = CHILD(n, 1); +X REQ(n, subscript); /* subscript: expr | [expr] ':' [expr] */ +X if (NCH(n) > 1 || TYPE(CHILD(n, 0)) == COLON) +X com_assign_slice(c, n, assigning); +X else +X com_assign_subscript(c, CHILD(n, 0), assigning); +X break; +X default: +X err_setstr(TypeError, "unknown trailer type"); +X c->c_errors++; +X } X} X Xstatic void Xcom_assign_tuple(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X int i; -X if (TYPE(n) != testlist) -X REQ(n, exprlist); -X if (assigning) -X com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); -X for (i = 0; i < NCH(n); i += 2) -X com_assign(c, CHILD(n, i), assigning); +X int i; +X if (TYPE(n) != testlist) +X REQ(n, exprlist); +X if (assigning) +X com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); +X for (i = 0; i < NCH(n); i += 2) +X com_assign(c, CHILD(n, i), assigning); X} X Xstatic void Xcom_assign_list(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X int i; -X if (assigning) -X com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2); -X for (i = 0; i < NCH(n); i += 2) -X com_assign(c, CHILD(n, i), assigning); +X int i; +X if (assigning) +X com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2); +X for (i = 0; i < NCH(n); i += 2) +X com_assign(c, CHILD(n, i), assigning); X} X Xstatic void Xcom_assign_name(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X REQ(n, NAME); -X com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n); +X REQ(n, NAME); +X com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n); X} X Xstatic void Xcom_assign(c, n, assigning) -X struct compiling *c; -X node *n; -X int assigning; +X struct compiling *c; +X node *n; +X int assigning; X{ -X /* Loop to avoid trivial recursion */ -X for (;;) { -X switch (TYPE(n)) { -X -X case exprlist: -X case testlist: -X if (NCH(n) > 1) { -X com_assign_tuple(c, n, assigning); -X return; -X } -X n = CHILD(n, 0); -X break; -X -X case test: -X case and_test: -X case not_test: -X if (NCH(n) > 1) { -X err_setstr(TypeError, -X "can't assign to operator"); -X c->c_errors++; -X return; -X } -X n = CHILD(n, 0); -X break; -X -X case comparison: -X if (NCH(n) > 1) { -X err_setstr(TypeError, -X "can't assign to operator"); -X c->c_errors++; -X return; -X } -X n = CHILD(n, 0); -X break; -X -X case expr: -X if (NCH(n) > 1) { -X err_setstr(TypeError, -X "can't assign to operator"); -X c->c_errors++; -X return; -X } -X n = CHILD(n, 0); -X break; -X -X case term: -X if (NCH(n) > 1) { -X err_setstr(TypeError, -X "can't assign to operator"); -X c->c_errors++; -X return; -X } -X n = CHILD(n, 0); -X break; -X -X case factor: /* ('+'|'-') factor | atom trailer* */ -X if (TYPE(CHILD(n, 0)) != atom) { /* '+' | '-' */ -X err_setstr(TypeError, -X "can't assign to operator"); -X c->c_errors++; -X return; -X } -X if (NCH(n) > 1) { /* trailer present */ -X int i; -X com_node(c, CHILD(n, 0)); -X for (i = 1; i+1 < NCH(n); i++) { -X com_apply_trailer(c, CHILD(n, i)); -X } /* NB i is still alive */ -X com_assign_trailer(c, -X CHILD(n, i), assigning); -X return; -X } -X n = CHILD(n, 0); -X break; -X -X case atom: -X switch (TYPE(CHILD(n, 0))) { -X case LPAR: -X n = CHILD(n, 1); -X if (TYPE(n) == RPAR) { -X /* XXX Should allow () = () ??? */ -X err_setstr(TypeError, -X "can't assign to ()"); -X c->c_errors++; -X return; -X } -X break; -X case LSQB: -X n = CHILD(n, 1); -X if (TYPE(n) == RSQB) { -X err_setstr(TypeError, -X "can't assign to []"); -X c->c_errors++; -X return; -X } -X com_assign_list(c, n, assigning); -X return; -X case NAME: -X com_assign_name(c, CHILD(n, 0), assigning); -X return; -X default: -X err_setstr(TypeError, -X "can't assign to constant"); -X c->c_errors++; -X return; -X } -X break; -X -X default: -X fprintf(stderr, "node type %d\n", TYPE(n)); -X err_setstr(SystemError, "com_assign: bad node"); -X c->c_errors++; -X return; -X -X } -X } +X /* Loop to avoid trivial recursion */ +X for (;;) { +X switch (TYPE(n)) { +X +X case exprlist: +X case testlist: +X if (NCH(n) > 1) { +X com_assign_tuple(c, n, assigning); +X return; +X } +X n = CHILD(n, 0); +X break; +X +X case test: +X case and_test: +X case not_test: +X if (NCH(n) > 1) { +X err_setstr(TypeError, +X "can't assign to operator"); +X c->c_errors++; +X return; +X } +X n = CHILD(n, 0); +X break; +X +X case comparison: +X if (NCH(n) > 1) { +X err_setstr(TypeError, +X "can't assign to operator"); +X c->c_errors++; +X return; +X } +X n = CHILD(n, 0); +X break; +X +X case expr: +X if (NCH(n) > 1) { +X err_setstr(TypeError, +X "can't assign to operator"); +X c->c_errors++; +X return; +X } +X n = CHILD(n, 0); +X break; +X +X case term: +X if (NCH(n) > 1) { +X err_setstr(TypeError, +X "can't assign to operator"); +X c->c_errors++; +X return; +X } +X n = CHILD(n, 0); +X break; +X +X case factor: /* ('+'|'-') factor | atom trailer* */ +X if (TYPE(CHILD(n, 0)) != atom) { /* '+' | '-' */ +X err_setstr(TypeError, +X "can't assign to operator"); +X c->c_errors++; +X return; +X } +X if (NCH(n) > 1) { /* trailer present */ +X int i; +X com_node(c, CHILD(n, 0)); +X for (i = 1; i+1 < NCH(n); i++) { +X com_apply_trailer(c, CHILD(n, i)); +X } /* NB i is still alive */ +X com_assign_trailer(c, +X CHILD(n, i), assigning); +X return; +X } +X n = CHILD(n, 0); +X break; +X +X case atom: +X switch (TYPE(CHILD(n, 0))) { +X case LPAR: +X n = CHILD(n, 1); +X if (TYPE(n) == RPAR) { +X /* XXX Should allow () = () ??? */ +X err_setstr(TypeError, +X "can't assign to ()"); +X c->c_errors++; +X return; +X } +X break; +X case LSQB: +X n = CHILD(n, 1); +X if (TYPE(n) == RSQB) { +X err_setstr(TypeError, +X "can't assign to []"); +X c->c_errors++; +X return; +X } +X com_assign_list(c, n, assigning); +X return; +X case NAME: +X com_assign_name(c, CHILD(n, 0), assigning); +X return; +X default: +X err_setstr(TypeError, +X "can't assign to constant"); +X c->c_errors++; +X return; +X } +X break; +X +X default: +X fprintf(stderr, "node type %d\n", TYPE(n)); +X err_setstr(SystemError, "com_assign: bad node"); +X c->c_errors++; +X return; +X +X } +X } X} X Xstatic void Xcom_expr_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, expr_stmt); /* exprlist ('=' exprlist)* NEWLINE */ -X com_node(c, CHILD(n, NCH(n)-2)); -X if (NCH(n) == 2) { -X com_addbyte(c, PRINT_EXPR); -X } -X else { -X int i; -X for (i = 0; i < NCH(n)-3; i+=2) { -X if (i+2 < NCH(n)-3) -X com_addbyte(c, DUP_TOP); -X com_assign(c, CHILD(n, i), 1/*assign*/); -X } -X } +X REQ(n, expr_stmt); /* exprlist ('=' exprlist)* NEWLINE */ +X com_node(c, CHILD(n, NCH(n)-2)); +X if (NCH(n) == 2) { +X com_addbyte(c, PRINT_EXPR); +X } +X else { +X int i; +X for (i = 0; i < NCH(n)-3; i+=2) { +X if (i+2 < NCH(n)-3) +X com_addbyte(c, DUP_TOP); +X com_assign(c, CHILD(n, i), 1/*assign*/); +X } +X } X} X Xstatic void Xcom_print_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X REQ(n, print_stmt); /* 'print' (test ',')* [test] NEWLINE */ -X for (i = 1; i+1 < NCH(n); i += 2) { -X com_node(c, CHILD(n, i)); -X com_addbyte(c, PRINT_ITEM); -X } -X if (TYPE(CHILD(n, NCH(n)-2)) != COMMA) -X com_addbyte(c, PRINT_NEWLINE); -X /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */ +X int i; +X REQ(n, print_stmt); /* 'print' (test ',')* [test] NEWLINE */ +X for (i = 1; i+1 < NCH(n); i += 2) { +X com_node(c, CHILD(n, i)); +X com_addbyte(c, PRINT_ITEM); +X } +X if (TYPE(CHILD(n, NCH(n)-2)) != COMMA) +X com_addbyte(c, PRINT_NEWLINE); +X /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */ X} X Xstatic void Xcom_return_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, return_stmt); /* 'return' [testlist] NEWLINE */ -X if (!c->c_infunction) { -X err_setstr(TypeError, "'return' outside function"); -X c->c_errors++; -X } -X if (NCH(n) == 2) -X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); -X else -X com_node(c, CHILD(n, 1)); -X com_addbyte(c, RETURN_VALUE); +X REQ(n, return_stmt); /* 'return' [testlist] NEWLINE */ +X if (!c->c_infunction) { +X err_setstr(TypeError, "'return' outside function"); +X c->c_errors++; +X } +X if (NCH(n) == 2) +X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); +X else +X com_node(c, CHILD(n, 1)); +X com_addbyte(c, RETURN_VALUE); X} X Xstatic void Xcom_raise_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, raise_stmt); /* 'raise' expr [',' expr] NEWLINE */ -X com_node(c, CHILD(n, 1)); -X if (NCH(n) > 3) -X com_node(c, CHILD(n, 3)); -X else -X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); -X com_addbyte(c, RAISE_EXCEPTION); +X REQ(n, raise_stmt); /* 'raise' expr [',' expr] NEWLINE */ +X com_node(c, CHILD(n, 1)); +X if (NCH(n) > 3) +X com_node(c, CHILD(n, 3)); +X else +X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); +X com_addbyte(c, RAISE_EXCEPTION); X} X Xstatic void Xcom_import_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X REQ(n, import_stmt); -X /* 'import' NAME (',' NAME)* NEWLINE | -X 'from' NAME 'import' ('*' | NAME (',' NAME)*) NEWLINE */ -X if (STR(CHILD(n, 0))[0] == 'f') { -X /* 'from' NAME 'import' ... */ -X REQ(CHILD(n, 1), NAME); -X com_addopname(c, IMPORT_NAME, CHILD(n, 1)); -X for (i = 3; i < NCH(n); i += 2) -X com_addopname(c, IMPORT_FROM, CHILD(n, i)); -X com_addbyte(c, POP_TOP); -X } -X else { -X /* 'import' ... */ -X for (i = 1; i < NCH(n); i += 2) { -X com_addopname(c, IMPORT_NAME, CHILD(n, i)); -X com_addopname(c, STORE_NAME, CHILD(n, i)); -X } -X } +X int i; +X REQ(n, import_stmt); +X /* 'import' NAME (',' NAME)* NEWLINE | +X 'from' NAME 'import' ('*' | NAME (',' NAME)*) NEWLINE */ +X if (STR(CHILD(n, 0))[0] == 'f') { +X /* 'from' NAME 'import' ... */ +X REQ(CHILD(n, 1), NAME); +X com_addopname(c, IMPORT_NAME, CHILD(n, 1)); +X for (i = 3; i < NCH(n); i += 2) +X com_addopname(c, IMPORT_FROM, CHILD(n, i)); +X com_addbyte(c, POP_TOP); +X } +X else { +X /* 'import' ... */ +X for (i = 1; i < NCH(n); i += 2) { +X com_addopname(c, IMPORT_NAME, CHILD(n, i)); +X com_addopname(c, STORE_NAME, CHILD(n, i)); +X } +X } X} X Xstatic void Xcom_if_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X int anchor = 0; -X REQ(n, if_stmt); -X /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */ -X for (i = 0; i+3 < NCH(n); i+=4) { -X int a = 0; -X node *ch = CHILD(n, i+1); -X if (i > 0) -X com_addoparg(c, SET_LINENO, ch->n_lineno); -X com_node(c, CHILD(n, i+1)); -X com_addfwref(c, JUMP_IF_FALSE, &a); -X com_addbyte(c, POP_TOP); -X com_node(c, CHILD(n, i+3)); -X com_addfwref(c, JUMP_FORWARD, &anchor); -X com_backpatch(c, a); -X com_addbyte(c, POP_TOP); -X } -X if (i+2 < NCH(n)) -X com_node(c, CHILD(n, i+2)); -X com_backpatch(c, anchor); +X int i; +X int anchor = 0; +X REQ(n, if_stmt); +X /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */ +X for (i = 0; i+3 < NCH(n); i+=4) { +X int a = 0; +X node *ch = CHILD(n, i+1); +X if (i > 0) +X com_addoparg(c, SET_LINENO, ch->n_lineno); +X com_node(c, CHILD(n, i+1)); +X com_addfwref(c, JUMP_IF_FALSE, &a); +X com_addbyte(c, POP_TOP); +X com_node(c, CHILD(n, i+3)); +X com_addfwref(c, JUMP_FORWARD, &anchor); +X com_backpatch(c, a); +X com_addbyte(c, POP_TOP); +X } +X if (i+2 < NCH(n)) +X com_node(c, CHILD(n, i+2)); +X com_backpatch(c, anchor); X} X Xstatic void Xcom_while_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int break_anchor = 0; -X int anchor = 0; -X int begin; -X REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */ -X com_addfwref(c, SETUP_LOOP, &break_anchor); -X begin = c->c_nexti; -X com_addoparg(c, SET_LINENO, n->n_lineno); -X com_node(c, CHILD(n, 1)); -X com_addfwref(c, JUMP_IF_FALSE, &anchor); -X com_addbyte(c, POP_TOP); -X c->c_loops++; -X com_node(c, CHILD(n, 3)); -X c->c_loops--; -X com_addoparg(c, JUMP_ABSOLUTE, begin); -X com_backpatch(c, anchor); -X com_addbyte(c, POP_TOP); -X com_addbyte(c, POP_BLOCK); -X if (NCH(n) > 4) -X com_node(c, CHILD(n, 6)); -X com_backpatch(c, break_anchor); +X int break_anchor = 0; +X int anchor = 0; +X int begin; +X REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */ +X com_addfwref(c, SETUP_LOOP, &break_anchor); +X begin = c->c_nexti; +X com_addoparg(c, SET_LINENO, n->n_lineno); +X com_node(c, CHILD(n, 1)); +X com_addfwref(c, JUMP_IF_FALSE, &anchor); +X com_addbyte(c, POP_TOP); +X c->c_loops++; +X com_node(c, CHILD(n, 3)); +X c->c_loops--; +X com_addoparg(c, JUMP_ABSOLUTE, begin); +X com_backpatch(c, anchor); +X com_addbyte(c, POP_TOP); +X com_addbyte(c, POP_BLOCK); +X if (NCH(n) > 4) +X com_node(c, CHILD(n, 6)); +X com_backpatch(c, break_anchor); X} X Xstatic void Xcom_for_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X object *v; -X int break_anchor = 0; -X int anchor = 0; -X int begin; -X REQ(n, for_stmt); -X /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */ -X com_addfwref(c, SETUP_LOOP, &break_anchor); -X com_node(c, CHILD(n, 3)); -X v = newintobject(0L); -X if (v == NULL) -X c->c_errors++; -X com_addoparg(c, LOAD_CONST, com_addconst(c, v)); -X XDECREF(v); -X begin = c->c_nexti; -X com_addoparg(c, SET_LINENO, n->n_lineno); -X com_addfwref(c, FOR_LOOP, &anchor); -X com_assign(c, CHILD(n, 1), 1/*assigning*/); -X c->c_loops++; -X com_node(c, CHILD(n, 5)); -X c->c_loops--; -X com_addoparg(c, JUMP_ABSOLUTE, begin); -X com_backpatch(c, anchor); -X com_addbyte(c, POP_BLOCK); -X if (NCH(n) > 8) -X com_node(c, CHILD(n, 8)); -X com_backpatch(c, break_anchor); +X object *v; +X int break_anchor = 0; +X int anchor = 0; +X int begin; +X REQ(n, for_stmt); +X /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */ +X com_addfwref(c, SETUP_LOOP, &break_anchor); +X com_node(c, CHILD(n, 3)); +X v = newintobject(0L); +X if (v == NULL) +X c->c_errors++; +X com_addoparg(c, LOAD_CONST, com_addconst(c, v)); +X XDECREF(v); +X begin = c->c_nexti; +X com_addoparg(c, SET_LINENO, n->n_lineno); +X com_addfwref(c, FOR_LOOP, &anchor); +X com_assign(c, CHILD(n, 1), 1/*assigning*/); +X c->c_loops++; +X com_node(c, CHILD(n, 5)); +X c->c_loops--; +X com_addoparg(c, JUMP_ABSOLUTE, begin); +X com_backpatch(c, anchor); +X com_addbyte(c, POP_BLOCK); +X if (NCH(n) > 8) +X com_node(c, CHILD(n, 8)); +X com_backpatch(c, break_anchor); X} X X/* Although 'execpt' and 'finally' clauses can be combined -X syntactically, they are compiled separately. In fact, -X try: S -X except E1: S1 -X except E2: S2 -X ... -X finally: Sf -X is equivalent to -X try: -X try: S -X except E1: S1 -X except E2: S2 -X ... -X finally: Sf -X meaning that the 'finally' clause is entered even if things -X go wrong again in an exception handler. Note that this is -X not the case for exception handlers: at most one is entered. -X -X Code generated for "try: S finally: Sf" is as follows: -X -X SETUP_FINALLY L -X <code for S> -X POP_BLOCK -X LOAD_CONST <nil> -X L: <code for Sf> -X END_FINALLY -X -X The special instructions use the block stack. Each block -X stack entry contains the instruction that created it (here -X SETUP_FINALLY), the level of the value stack at the time the -X block stack entry was created, and a label (here L). -X -X SETUP_FINALLY: -X Pushes the current value stack level and the label -X onto the block stack. -X POP_BLOCK: -X Pops en entry from the block stack, and pops the value -X stack until its level is the same as indicated on the -X block stack. (The label is ignored.) -X END_FINALLY: -X Pops a variable number of entries from the *value* stack -X and re-raises the exception they specify. The number of -X entries popped depends on the (pseudo) exception type. -X -X The block stack is unwound when an exception is raised: -X when a SETUP_FINALLY entry is found, the exception is pushed -X onto the value stack (and the exception condition is cleared), -X and the interpreter jumps to the label gotten from the block -X stack. -X -X Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...": -X (The contents of the value stack is shown in [], with the top -X at the right; 'tb' is trace-back info, 'val' the exception's -X associated value, and 'exc' the exception.) -X -X Value stack Label Instruction Argument -X [] SETUP_EXCEPT L1 -X [] <code for S> -X [] POP_BLOCK -X [] JUMP_FORWARD L0 -X -X [tb, val, exc] L1: DUP ) -X [tb, val, exc, exc] <evaluate E1> ) -X [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 -X [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 ) -X [tb, val, exc, 1] POP ) -X [tb, val, exc] POP -X [tb, val] <assign to V1> (or POP if no V1) -X [tb] POP -X [] <code for S1> -X JUMP_FORWARD L0 -X -X [tb, val, exc, 0] L2: POP -X [tb, val, exc] DUP -X .............................etc....................... -X -X [tb, val, exc, 0] Ln+1: POP -X [tb, val, exc] END_FINALLY # re-raise exception -X -X [] L0: <next statement> -X -X Of course, parts are not generated if Vi or Ei is not present. +X syntactically, they are compiled separately. In fact, +X try: S +X except E1: S1 +X except E2: S2 +X ... +X finally: Sf +X is equivalent to +X try: +X try: S +X except E1: S1 +X except E2: S2 +X ... +X finally: Sf +X meaning that the 'finally' clause is entered even if things +X go wrong again in an exception handler. Note that this is +X not the case for exception handlers: at most one is entered. +X +X Code generated for "try: S finally: Sf" is as follows: +X +X SETUP_FINALLY L +X <code for S> +X POP_BLOCK +X LOAD_CONST <nil> +X L: <code for Sf> +X END_FINALLY +X +X The special instructions use the block stack. Each block +X stack entry contains the instruction that created it (here +X SETUP_FINALLY), the level of the value stack at the time the +X block stack entry was created, and a label (here L). +X +X SETUP_FINALLY: +X Pushes the current value stack level and the label +X onto the block stack. +X POP_BLOCK: +X Pops en entry from the block stack, and pops the value +X stack until its level is the same as indicated on the +X block stack. (The label is ignored.) +X END_FINALLY: +X Pops a variable number of entries from the *value* stack +X and re-raises the exception they specify. The number of +X entries popped depends on the (pseudo) exception type. +X +X The block stack is unwound when an exception is raised: +X when a SETUP_FINALLY entry is found, the exception is pushed +X onto the value stack (and the exception condition is cleared), +X and the interpreter jumps to the label gotten from the block +X stack. +X +X Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...": +X (The contents of the value stack is shown in [], with the top +X at the right; 'tb' is trace-back info, 'val' the exception's +X associated value, and 'exc' the exception.) +X +X Value stack Label Instruction Argument +X [] SETUP_EXCEPT L1 +X [] <code for S> +X [] POP_BLOCK +X [] JUMP_FORWARD L0 +X +X [tb, val, exc] L1: DUP ) +X [tb, val, exc, exc] <evaluate E1> ) +X [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 +X [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 ) +X [tb, val, exc, 1] POP ) +X [tb, val, exc] POP +X [tb, val] <assign to V1> (or POP if no V1) +X [tb] POP +X [] <code for S1> +X JUMP_FORWARD L0 +X +X [tb, val, exc, 0] L2: POP +X [tb, val, exc] DUP +X .............................etc....................... +X +X [tb, val, exc, 0] Ln+1: POP +X [tb, val, exc] END_FINALLY # re-raise exception +X +X [] L0: <next statement> +X +X Of course, parts are not generated if Vi or Ei is not present. X*/ X Xstatic void Xcom_try_stmt(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int finally_anchor = 0; -X int except_anchor = 0; -X REQ(n, try_stmt); -X /* 'try' ':' suite (except_clause ':' suite)* ['finally' ':' suite] */ -X -X if (NCH(n) > 3 && TYPE(CHILD(n, NCH(n)-3)) != except_clause) { -X /* Have a 'finally' clause */ -X com_addfwref(c, SETUP_FINALLY, &finally_anchor); -X } -X if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == except_clause) { -X /* Have an 'except' clause */ -X com_addfwref(c, SETUP_EXCEPT, &except_anchor); -X } -X com_node(c, CHILD(n, 2)); -X if (except_anchor) { -X int end_anchor = 0; -X int i; -X node *ch; -X com_addbyte(c, POP_BLOCK); -X com_addfwref(c, JUMP_FORWARD, &end_anchor); -X com_backpatch(c, except_anchor); -X for (i = 3; -X i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause; -X i += 3) { -X /* except_clause: 'except' [expr [',' expr]] */ -X if (except_anchor == 0) { -X err_setstr(TypeError, -X "default 'except:' must be last"); -X c->c_errors++; -X break; -X } -X except_anchor = 0; -X com_addoparg(c, SET_LINENO, ch->n_lineno); -X if (NCH(ch) > 1) { -X com_addbyte(c, DUP_TOP); -X com_node(c, CHILD(ch, 1)); -X com_addoparg(c, COMPARE_OP, EXC_MATCH); -X com_addfwref(c, JUMP_IF_FALSE, &except_anchor); -X com_addbyte(c, POP_TOP); -X } -X com_addbyte(c, POP_TOP); -X if (NCH(ch) > 3) -X com_assign(c, CHILD(ch, 3), 1/*assigning*/); -X else -X com_addbyte(c, POP_TOP); -X com_addbyte(c, POP_TOP); -X com_node(c, CHILD(n, i+2)); -X com_addfwref(c, JUMP_FORWARD, &end_anchor); -X if (except_anchor) { -X com_backpatch(c, except_anchor); -X com_addbyte(c, POP_TOP); -X } -X } -X com_addbyte(c, END_FINALLY); -X com_backpatch(c, end_anchor); -X } -X if (finally_anchor) { -X node *ch; -X com_addbyte(c, POP_BLOCK); -X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); -X com_backpatch(c, finally_anchor); -X ch = CHILD(n, NCH(n)-1); -X com_addoparg(c, SET_LINENO, ch->n_lineno); -X com_node(c, ch); -X com_addbyte(c, END_FINALLY); -X } +X int finally_anchor = 0; +X int except_anchor = 0; +X REQ(n, try_stmt); +X /* 'try' ':' suite (except_clause ':' suite)* ['finally' ':' suite] */ +X +X if (NCH(n) > 3 && TYPE(CHILD(n, NCH(n)-3)) != except_clause) { +X /* Have a 'finally' clause */ +X com_addfwref(c, SETUP_FINALLY, &finally_anchor); +X } +X if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == except_clause) { +X /* Have an 'except' clause */ +X com_addfwref(c, SETUP_EXCEPT, &except_anchor); +X } +X com_node(c, CHILD(n, 2)); +X if (except_anchor) { +X int end_anchor = 0; +X int i; +X node *ch; +X com_addbyte(c, POP_BLOCK); +X com_addfwref(c, JUMP_FORWARD, &end_anchor); +X com_backpatch(c, except_anchor); +X for (i = 3; +X i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause; +X i += 3) { +X /* except_clause: 'except' [expr [',' expr]] */ +X if (except_anchor == 0) { +X err_setstr(TypeError, +X "default 'except:' must be last"); +X c->c_errors++; +X break; +X } +X except_anchor = 0; +X com_addoparg(c, SET_LINENO, ch->n_lineno); +X if (NCH(ch) > 1) { +X com_addbyte(c, DUP_TOP); +X com_node(c, CHILD(ch, 1)); +X com_addoparg(c, COMPARE_OP, EXC_MATCH); +X com_addfwref(c, JUMP_IF_FALSE, &except_anchor); +X com_addbyte(c, POP_TOP); +X } +X com_addbyte(c, POP_TOP); +X if (NCH(ch) > 3) +X com_assign(c, CHILD(ch, 3), 1/*assigning*/); +X else +X com_addbyte(c, POP_TOP); +X com_addbyte(c, POP_TOP); +X com_node(c, CHILD(n, i+2)); +X com_addfwref(c, JUMP_FORWARD, &end_anchor); +X if (except_anchor) { +X com_backpatch(c, except_anchor); +X com_addbyte(c, POP_TOP); +X } +X } +X com_addbyte(c, END_FINALLY); +X com_backpatch(c, end_anchor); +X } +X if (finally_anchor) { +X node *ch; +X com_addbyte(c, POP_BLOCK); +X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); +X com_backpatch(c, finally_anchor); +X ch = CHILD(n, NCH(n)-1); +X com_addoparg(c, SET_LINENO, ch->n_lineno); +X com_node(c, ch); +X com_addbyte(c, END_FINALLY); +X } X} X Xstatic void Xcom_suite(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, suite); -X /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */ -X if (NCH(n) == 1) { -X com_node(c, CHILD(n, 0)); -X } -X else { -X int i; -X for (i = 0; i < NCH(n); i++) { -X node *ch = CHILD(n, i); -X if (TYPE(ch) == stmt) -X com_node(c, ch); -X } -X } +X REQ(n, suite); +X /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */ +X if (NCH(n) == 1) { +X com_node(c, CHILD(n, 0)); +X } +X else { +X int i; +X for (i = 0; i < NCH(n); i++) { +X node *ch = CHILD(n, i); +X if (TYPE(ch) == stmt) +X com_node(c, ch); +X } +X } X} X Xstatic void Xcom_funcdef(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X object *v; -X REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ -X v = (object *)compile(n, c->c_filename); -X if (v == NULL) -X c->c_errors++; -X else { -X int i = com_addconst(c, v); -X com_addoparg(c, LOAD_CONST, i); -X com_addbyte(c, BUILD_FUNCTION); -X com_addopname(c, STORE_NAME, CHILD(n, 1)); -X DECREF(v); -X } +X object *v; +X REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ +X v = (object *)compile(n, c->c_filename); +X if (v == NULL) +X c->c_errors++; +X else { +X int i = com_addconst(c, v); +X com_addoparg(c, LOAD_CONST, i); +X com_addbyte(c, BUILD_FUNCTION); +X com_addopname(c, STORE_NAME, CHILD(n, 1)); +X DECREF(v); +X } X} X Xstatic void Xcom_bases(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i, nbases; -X REQ(n, baselist); -X /* -X baselist: atom arguments (',' atom arguments)* -X arguments: '(' [testlist] ')' -X */ -X for (i = 0; i < NCH(n); i += 3) -X com_node(c, CHILD(n, i)); -X com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 3); +X int i, nbases; +X REQ(n, baselist); +X /* +X baselist: atom arguments (',' atom arguments)* +X arguments: '(' [testlist] ')' +X */ +X for (i = 0; i < NCH(n); i += 3) +X com_node(c, CHILD(n, i)); +X com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 3); X} X Xstatic void Xcom_classdef(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X object *v; -X REQ(n, classdef); -X /* -X classdef: 'class' NAME parameters ['=' baselist] ':' suite -X baselist: atom arguments (',' atom arguments)* -X arguments: '(' [testlist] ')' -X */ -X if (NCH(n) == 7) -X com_bases(c, CHILD(n, 4)); -X else -X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); -X v = (object *)compile(n, c->c_filename); -X if (v == NULL) -X c->c_errors++; -X else { -X int i = com_addconst(c, v); -X com_addoparg(c, LOAD_CONST, i); -X com_addbyte(c, BUILD_FUNCTION); -X com_addbyte(c, UNARY_CALL); -X com_addbyte(c, BUILD_CLASS); -X com_addopname(c, STORE_NAME, CHILD(n, 1)); -X DECREF(v); -X } +X object *v; +X REQ(n, classdef); +X /* +X classdef: 'class' NAME parameters ['=' baselist] ':' suite +X baselist: atom arguments (',' atom arguments)* +X arguments: '(' [testlist] ')' +X */ +X if (NCH(n) == 7) +X com_bases(c, CHILD(n, 4)); +X else +X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); +X v = (object *)compile(n, c->c_filename); +X if (v == NULL) +X c->c_errors++; +X else { +X int i = com_addconst(c, v); +X com_addoparg(c, LOAD_CONST, i); +X com_addbyte(c, BUILD_FUNCTION); +X com_addbyte(c, UNARY_CALL); +X com_addbyte(c, BUILD_CLASS); +X com_addopname(c, STORE_NAME, CHILD(n, 1)); +X DECREF(v); +X } X} X Xstatic void Xcom_node(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X switch (TYPE(n)) { -X -X /* Definition nodes */ -X -X case funcdef: -X com_funcdef(c, n); -X break; -X case classdef: -X com_classdef(c, n); -X break; -X -X /* Trivial parse tree nodes */ -X -X case stmt: -X case flow_stmt: -X com_node(c, CHILD(n, 0)); -X break; -X -X case simple_stmt: -X case compound_stmt: -X com_addoparg(c, SET_LINENO, n->n_lineno); -X com_node(c, CHILD(n, 0)); -X break; -X -X /* Statement nodes */ -X -X case expr_stmt: -X com_expr_stmt(c, n); -X break; -X case print_stmt: -X com_print_stmt(c, n); -X break; -X case del_stmt: /* 'del' exprlist NEWLINE */ -X com_assign(c, CHILD(n, 1), 0/*delete*/); -X break; -X case pass_stmt: -X break; -X case break_stmt: -X if (c->c_loops == 0) { -X err_setstr(TypeError, "'break' outside loop"); -X c->c_errors++; -X } -X com_addbyte(c, BREAK_LOOP); -X break; -X case return_stmt: -X com_return_stmt(c, n); -X break; -X case raise_stmt: -X com_raise_stmt(c, n); -X break; -X case import_stmt: -X com_import_stmt(c, n); -X break; -X case if_stmt: -X com_if_stmt(c, n); -X break; -X case while_stmt: -X com_while_stmt(c, n); -X break; -X case for_stmt: -X com_for_stmt(c, n); -X break; -X case try_stmt: -X com_try_stmt(c, n); -X break; -X case suite: -X com_suite(c, n); -X break; -X -X /* Expression nodes */ -X -X case testlist: -X com_list(c, n); -X break; -X case test: -X com_test(c, n); -X break; -X case and_test: -X com_and_test(c, n); -X break; -X case not_test: -X com_not_test(c, n); -X break; -X case comparison: -X com_comparison(c, n); -X break; -X case exprlist: -X com_list(c, n); -X break; -X case expr: -X com_expr(c, n); -X break; -X case term: -X com_term(c, n); -X break; -X case factor: -X com_factor(c, n); -X break; -X case atom: -X com_atom(c, n); -X break; -X -X default: -X fprintf(stderr, "node type %d\n", TYPE(n)); -X err_setstr(SystemError, "com_node: unexpected node type"); -X c->c_errors++; -X } +X switch (TYPE(n)) { +X +X /* Definition nodes */ +X +X case funcdef: +X com_funcdef(c, n); +X break; +X case classdef: +X com_classdef(c, n); +X break; +X +X /* Trivial parse tree nodes */ +X +X case stmt: +X case flow_stmt: +X com_node(c, CHILD(n, 0)); +X break; +X +X case simple_stmt: +X case compound_stmt: +X com_addoparg(c, SET_LINENO, n->n_lineno); +X com_node(c, CHILD(n, 0)); +X break; +X +X /* Statement nodes */ +X +X case expr_stmt: +X com_expr_stmt(c, n); +X break; +X case print_stmt: +X com_print_stmt(c, n); +X break; +X case del_stmt: /* 'del' exprlist NEWLINE */ +X com_assign(c, CHILD(n, 1), 0/*delete*/); +X break; +X case pass_stmt: +X break; +X case break_stmt: +X if (c->c_loops == 0) { +X err_setstr(TypeError, "'break' outside loop"); +X c->c_errors++; +X } +X com_addbyte(c, BREAK_LOOP); +X break; +X case return_stmt: +X com_return_stmt(c, n); +X break; +X case raise_stmt: +X com_raise_stmt(c, n); +X break; +X case import_stmt: +X com_import_stmt(c, n); +X break; +X case if_stmt: +X com_if_stmt(c, n); +X break; +X case while_stmt: +X com_while_stmt(c, n); +X break; +X case for_stmt: +X com_for_stmt(c, n); +X break; +X case try_stmt: +X com_try_stmt(c, n); +X break; +X case suite: +X com_suite(c, n); +X break; +X +X /* Expression nodes */ +X +X case testlist: +X com_list(c, n); +X break; +X case test: +X com_test(c, n); +X break; +X case and_test: +X com_and_test(c, n); +X break; +X case not_test: +X com_not_test(c, n); +X break; +X case comparison: +X com_comparison(c, n); +X break; +X case exprlist: +X com_list(c, n); +X break; +X case expr: +X com_expr(c, n); +X break; +X case term: +X com_term(c, n); +X break; +X case factor: +X com_factor(c, n); +X break; +X case atom: +X com_atom(c, n); +X break; +X +X default: +X fprintf(stderr, "node type %d\n", TYPE(n)); +X err_setstr(SystemError, "com_node: unexpected node type"); +X c->c_errors++; +X } X} X Xstatic void com_fplist PROTO((struct compiling *, node *)); X Xstatic void Xcom_fpdef(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */ -X if (TYPE(CHILD(n, 0)) == LPAR) -X com_fplist(c, CHILD(n, 1)); -X else -X com_addopname(c, STORE_NAME, CHILD(n, 0)); +X REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */ +X if (TYPE(CHILD(n, 0)) == LPAR) +X com_fplist(c, CHILD(n, 1)); +X else +X com_addopname(c, STORE_NAME, CHILD(n, 0)); X} X Xstatic void Xcom_fplist(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X REQ(n, fplist); /* fplist: fpdef (',' fpdef)* */ -X if (NCH(n) == 1) { -X com_fpdef(c, CHILD(n, 0)); -X } -X else { -X int i; -X com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); -X for (i = 0; i < NCH(n); i += 2) -X com_fpdef(c, CHILD(n, i)); -X } +X REQ(n, fplist); /* fplist: fpdef (',' fpdef)* */ +X if (NCH(n) == 1) { +X com_fpdef(c, CHILD(n, 0)); +X } +X else { +X int i; +X com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); +X for (i = 0; i < NCH(n); i += 2) +X com_fpdef(c, CHILD(n, i)); +X } X} X Xstatic void Xcom_file_input(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X int i; -X REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */ -X for (i = 0; i < NCH(n); i++) { -X node *ch = CHILD(n, i); -X if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE) -X com_node(c, ch); -X } +X int i; +X REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */ +X for (i = 0; i < NCH(n); i++) { +X node *ch = CHILD(n, i); +X if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE) +X com_node(c, ch); +X } X} X X/* Top-level compile-node interface */ X Xstatic void Xcompile_funcdef(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X node *ch; -X REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ -X ch = CHILD(n, 2); /* parameters: '(' [fplist] ')' */ -X ch = CHILD(ch, 1); /* ')' | fplist */ -X if (TYPE(ch) == RPAR) -X com_addbyte(c, REFUSE_ARGS); -X else { -X com_addbyte(c, REQUIRE_ARGS); -X com_fplist(c, ch); -X } -X c->c_infunction = 1; -X com_node(c, CHILD(n, 4)); -X c->c_infunction = 0; -X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); -X com_addbyte(c, RETURN_VALUE); +X node *ch; +X REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ +X ch = CHILD(n, 2); /* parameters: '(' [fplist] ')' */ +X ch = CHILD(ch, 1); /* ')' | fplist */ +X if (TYPE(ch) == RPAR) +X com_addbyte(c, REFUSE_ARGS); +X else { +X com_addbyte(c, REQUIRE_ARGS); +X com_fplist(c, ch); +X } +X c->c_infunction = 1; +X com_node(c, CHILD(n, 4)); +X c->c_infunction = 0; +X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); +X com_addbyte(c, RETURN_VALUE); X} X Xstatic void Xcompile_node(c, n) -X struct compiling *c; -X node *n; +X struct compiling *c; +X node *n; X{ -X com_addoparg(c, SET_LINENO, n->n_lineno); -X -X switch (TYPE(n)) { -X -X case single_input: /* One interactive command */ -X /* NEWLINE | simple_stmt | compound_stmt NEWLINE */ -X com_addbyte(c, REFUSE_ARGS); -X n = CHILD(n, 0); -X if (TYPE(n) != NEWLINE) -X com_node(c, n); -X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); -X com_addbyte(c, RETURN_VALUE); -X break; -X -X case file_input: /* A whole file, or built-in function exec() */ -X com_addbyte(c, REFUSE_ARGS); -X com_file_input(c, n); -X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); -X com_addbyte(c, RETURN_VALUE); -X break; -X -X case expr_input: /* Built-in function eval() */ -X com_addbyte(c, REFUSE_ARGS); -X com_node(c, CHILD(n, 0)); -X com_addbyte(c, RETURN_VALUE); -X break; -X -X case eval_input: /* Built-in function input() */ -X com_addbyte(c, REFUSE_ARGS); -X com_node(c, CHILD(n, 0)); -X com_addbyte(c, RETURN_VALUE); -X break; -X -X case funcdef: /* A function definition */ -X compile_funcdef(c, n); -X break; -X -X case classdef: /* A class definition */ -X /* 'class' NAME parameters ['=' baselist] ':' suite */ -X com_addbyte(c, REFUSE_ARGS); -X com_node(c, CHILD(n, NCH(n)-1)); -X com_addbyte(c, LOAD_LOCALS); -X com_addbyte(c, RETURN_VALUE); -X break; -X -X default: -X fprintf(stderr, "node type %d\n", TYPE(n)); -X err_setstr(SystemError, "compile_node: unexpected node type"); -X c->c_errors++; -X } +X com_addoparg(c, SET_LINENO, n->n_lineno); +X +X switch (TYPE(n)) { +X +X case single_input: /* One interactive command */ +X /* NEWLINE | simple_stmt | compound_stmt NEWLINE */ +X com_addbyte(c, REFUSE_ARGS); +X n = CHILD(n, 0); +X if (TYPE(n) != NEWLINE) +X com_node(c, n); +X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); +X com_addbyte(c, RETURN_VALUE); +X break; +X +X case file_input: /* A whole file, or built-in function exec() */ +X com_addbyte(c, REFUSE_ARGS); +X com_file_input(c, n); +X com_addoparg(c, LOAD_CONST, com_addconst(c, None)); +X com_addbyte(c, RETURN_VALUE); +X break; +X +X case expr_input: /* Built-in function eval() */ +X com_addbyte(c, REFUSE_ARGS); +X com_node(c, CHILD(n, 0)); +X com_addbyte(c, RETURN_VALUE); +X break; +X +X case eval_input: /* Built-in function input() */ +X com_addbyte(c, REFUSE_ARGS); +X com_node(c, CHILD(n, 0)); +X com_addbyte(c, RETURN_VALUE); +X break; +X +X case funcdef: /* A function definition */ +X compile_funcdef(c, n); +X break; +X +X case classdef: /* A class definition */ +X /* 'class' NAME parameters ['=' baselist] ':' suite */ +X com_addbyte(c, REFUSE_ARGS); +X com_node(c, CHILD(n, NCH(n)-1)); +X com_addbyte(c, LOAD_LOCALS); +X com_addbyte(c, RETURN_VALUE); +X break; +X +X default: +X fprintf(stderr, "node type %d\n", TYPE(n)); +X err_setstr(SystemError, "compile_node: unexpected node type"); +X c->c_errors++; +X } X} X Xcodeobject * Xcompile(n, filename) -X node *n; -X char *filename; +X node *n; +X char *filename; X{ -X struct compiling sc; -X codeobject *co; -X if (!com_init(&sc, filename)) -X return NULL; -X compile_node(&sc, n); -X com_done(&sc); -X if (sc.c_errors == 0) -X co = newcodeobject(sc.c_code, sc.c_consts, sc.c_names, filename); -X else -X co = NULL; -X com_free(&sc); -X return co; +X struct compiling sc; +X codeobject *co; +X if (!com_init(&sc, filename)) +X return NULL; +X compile_node(&sc, n); +X com_done(&sc); +X if (sc.c_errors == 0) +X co = newcodeobject(sc.c_code, sc.c_consts, sc.c_names, filename); +X else +X co = NULL; +X com_free(&sc); +X return co; X} EOF fi @@ -1791,12 +1791,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1814,1072 +1814,1072 @@ X X#include "pgenheaders.h" X#include "grammar.h" Xstatic arc arcs_0_0[3] = { -X {2, 1}, -X {3, 1}, -X {4, 2}, +X {2, 1}, +X {3, 1}, +X {4, 2}, X}; Xstatic arc arcs_0_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic arc arcs_0_2[1] = { -X {2, 1}, +X {2, 1}, X}; Xstatic state states_0[3] = { -X {3, arcs_0_0}, -X {1, arcs_0_1}, -X {1, arcs_0_2}, +X {3, arcs_0_0}, +X {1, arcs_0_1}, +X {1, arcs_0_2}, X}; Xstatic arc arcs_1_0[3] = { -X {2, 0}, -X {6, 0}, -X {7, 1}, +X {2, 0}, +X {6, 0}, +X {7, 1}, X}; Xstatic arc arcs_1_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic state states_1[2] = { -X {3, arcs_1_0}, -X {1, arcs_1_1}, +X {3, arcs_1_0}, +X {1, arcs_1_1}, X}; Xstatic arc arcs_2_0[1] = { -X {9, 1}, +X {9, 1}, X}; Xstatic arc arcs_2_1[1] = { -X {2, 2}, +X {2, 2}, X}; Xstatic arc arcs_2_2[1] = { -X {0, 2}, +X {0, 2}, X}; Xstatic state states_2[3] = { -X {1, arcs_2_0}, -X {1, arcs_2_1}, -X {1, arcs_2_2}, +X {1, arcs_2_0}, +X {1, arcs_2_1}, +X {1, arcs_2_2}, X}; Xstatic arc arcs_3_0[1] = { -X {9, 1}, +X {9, 1}, X}; Xstatic arc arcs_3_1[1] = { -X {7, 2}, +X {7, 2}, X}; Xstatic arc arcs_3_2[1] = { -X {0, 2}, +X {0, 2}, X}; Xstatic state states_3[3] = { -X {1, arcs_3_0}, -X {1, arcs_3_1}, -X {1, arcs_3_2}, +X {1, arcs_3_0}, +X {1, arcs_3_1}, +X {1, arcs_3_2}, X}; Xstatic arc arcs_4_0[1] = { -X {12, 1}, +X {12, 1}, X}; Xstatic arc arcs_4_1[1] = { -X {13, 2}, +X {13, 2}, X}; Xstatic arc arcs_4_2[1] = { -X {14, 3}, +X {14, 3}, X}; Xstatic arc arcs_4_3[1] = { -X {15, 4}, +X {15, 4}, X}; Xstatic arc arcs_4_4[1] = { -X {16, 5}, +X {16, 5}, X}; Xstatic arc arcs_4_5[1] = { -X {0, 5}, +X {0, 5}, X}; Xstatic state states_4[6] = { -X {1, arcs_4_0}, -X {1, arcs_4_1}, -X {1, arcs_4_2}, -X {1, arcs_4_3}, -X {1, arcs_4_4}, -X {1, arcs_4_5}, +X {1, arcs_4_0}, +X {1, arcs_4_1}, +X {1, arcs_4_2}, +X {1, arcs_4_3}, +X {1, arcs_4_4}, +X {1, arcs_4_5}, X}; Xstatic arc arcs_5_0[1] = { -X {17, 1}, +X {17, 1}, X}; Xstatic arc arcs_5_1[2] = { -X {18, 2}, -X {19, 3}, +X {18, 2}, +X {19, 3}, X}; Xstatic arc arcs_5_2[1] = { -X {19, 3}, +X {19, 3}, X}; Xstatic arc arcs_5_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic state states_5[4] = { -X {1, arcs_5_0}, -X {2, arcs_5_1}, -X {1, arcs_5_2}, -X {1, arcs_5_3}, +X {1, arcs_5_0}, +X {2, arcs_5_1}, +X {1, arcs_5_2}, +X {1, arcs_5_3}, X}; Xstatic arc arcs_6_0[1] = { -X {20, 1}, +X {20, 1}, X}; Xstatic arc arcs_6_1[2] = { -X {21, 0}, -X {0, 1}, +X {21, 0}, +X {0, 1}, X}; Xstatic state states_6[2] = { -X {1, arcs_6_0}, -X {2, arcs_6_1}, +X {1, arcs_6_0}, +X {2, arcs_6_1}, X}; Xstatic arc arcs_7_0[2] = { -X {13, 1}, -X {17, 2}, +X {13, 1}, +X {17, 2}, X}; Xstatic arc arcs_7_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic arc arcs_7_2[1] = { -X {18, 3}, +X {18, 3}, X}; Xstatic arc arcs_7_3[1] = { -X {19, 1}, +X {19, 1}, X}; Xstatic state states_7[4] = { -X {2, arcs_7_0}, -X {1, arcs_7_1}, -X {1, arcs_7_2}, -X {1, arcs_7_3}, +X {2, arcs_7_0}, +X {1, arcs_7_1}, +X {1, arcs_7_2}, +X {1, arcs_7_3}, X}; Xstatic arc arcs_8_0[2] = { -X {3, 1}, -X {4, 1}, +X {3, 1}, +X {4, 1}, X}; Xstatic arc arcs_8_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic state states_8[2] = { -X {2, arcs_8_0}, -X {1, arcs_8_1}, +X {2, arcs_8_0}, +X {1, arcs_8_1}, X}; Xstatic arc arcs_9_0[6] = { -X {22, 1}, -X {23, 1}, -X {24, 1}, -X {25, 1}, -X {26, 1}, -X {27, 1}, +X {22, 1}, +X {23, 1}, +X {24, 1}, +X {25, 1}, +X {26, 1}, +X {27, 1}, X}; Xstatic arc arcs_9_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic state states_9[2] = { -X {6, arcs_9_0}, -X {1, arcs_9_1}, +X {6, arcs_9_0}, +X {1, arcs_9_1}, X}; Xstatic arc arcs_10_0[1] = { -X {28, 1}, +X {28, 1}, X}; Xstatic arc arcs_10_1[2] = { -X {29, 0}, -X {2, 2}, +X {29, 0}, +X {2, 2}, X}; Xstatic arc arcs_10_2[1] = { -X {0, 2}, +X {0, 2}, X}; Xstatic state states_10[3] = { -X {1, arcs_10_0}, -X {2, arcs_10_1}, -X {1, arcs_10_2}, +X {1, arcs_10_0}, +X {2, arcs_10_1}, +X {1, arcs_10_2}, X}; Xstatic arc arcs_11_0[1] = { -X {30, 1}, +X {30, 1}, X}; Xstatic arc arcs_11_1[2] = { -X {31, 2}, -X {2, 3}, +X {31, 2}, +X {2, 3}, X}; Xstatic arc arcs_11_2[2] = { -X {21, 1}, -X {2, 3}, +X {21, 1}, +X {2, 3}, X}; Xstatic arc arcs_11_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic state states_11[4] = { -X {1, arcs_11_0}, -X {2, arcs_11_1}, -X {2, arcs_11_2}, -X {1, arcs_11_3}, +X {1, arcs_11_0}, +X {2, arcs_11_1}, +X {2, arcs_11_2}, +X {1, arcs_11_3}, X}; Xstatic arc arcs_12_0[1] = { -X {32, 1}, +X {32, 1}, X}; Xstatic arc arcs_12_1[1] = { -X {28, 2}, +X {28, 2}, X}; Xstatic arc arcs_12_2[1] = { -X {2, 3}, +X {2, 3}, X}; Xstatic arc arcs_12_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic state states_12[4] = { -X {1, arcs_12_0}, -X {1, arcs_12_1}, -X {1, arcs_12_2}, -X {1, arcs_12_3}, +X {1, arcs_12_0}, +X {1, arcs_12_1}, +X {1, arcs_12_2}, +X {1, arcs_12_3}, X}; Xstatic arc arcs_13_0[1] = { -X {33, 1}, +X {33, 1}, X}; Xstatic arc arcs_13_1[1] = { -X {2, 2}, +X {2, 2}, X}; Xstatic arc arcs_13_2[1] = { -X {0, 2}, +X {0, 2}, X}; Xstatic state states_13[3] = { -X {1, arcs_13_0}, -X {1, arcs_13_1}, -X {1, arcs_13_2}, +X {1, arcs_13_0}, +X {1, arcs_13_1}, +X {1, arcs_13_2}, X}; Xstatic arc arcs_14_0[3] = { -X {34, 1}, -X {35, 1}, -X {36, 1}, +X {34, 1}, +X {35, 1}, +X {36, 1}, X}; Xstatic arc arcs_14_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic state states_14[2] = { -X {3, arcs_14_0}, -X {1, arcs_14_1}, +X {3, arcs_14_0}, +X {1, arcs_14_1}, X}; Xstatic arc arcs_15_0[1] = { -X {37, 1}, +X {37, 1}, X}; Xstatic arc arcs_15_1[1] = { -X {2, 2}, +X {2, 2}, X}; Xstatic arc arcs_15_2[1] = { -X {0, 2}, +X {0, 2}, X}; Xstatic state states_15[3] = { -X {1, arcs_15_0}, -X {1, arcs_15_1}, -X {1, arcs_15_2}, +X {1, arcs_15_0}, +X {1, arcs_15_1}, +X {1, arcs_15_2}, X}; Xstatic arc arcs_16_0[1] = { -X {38, 1}, +X {38, 1}, X}; Xstatic arc arcs_16_1[2] = { -X {9, 2}, -X {2, 3}, +X {9, 2}, +X {2, 3}, X}; Xstatic arc arcs_16_2[1] = { -X {2, 3}, +X {2, 3}, X}; Xstatic arc arcs_16_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic state states_16[4] = { -X {1, arcs_16_0}, -X {2, arcs_16_1}, -X {1, arcs_16_2}, -X {1, arcs_16_3}, +X {1, arcs_16_0}, +X {2, arcs_16_1}, +X {1, arcs_16_2}, +X {1, arcs_16_3}, X}; Xstatic arc arcs_17_0[1] = { -X {39, 1}, +X {39, 1}, X}; Xstatic arc arcs_17_1[1] = { -X {40, 2}, +X {40, 2}, X}; Xstatic arc arcs_17_2[2] = { -X {21, 3}, -X {2, 4}, +X {21, 3}, +X {2, 4}, X}; Xstatic arc arcs_17_3[1] = { -X {40, 5}, +X {40, 5}, X}; Xstatic arc arcs_17_4[1] = { -X {0, 4}, +X {0, 4}, X}; Xstatic arc arcs_17_5[1] = { -X {2, 4}, +X {2, 4}, X}; Xstatic state states_17[6] = { -X {1, arcs_17_0}, -X {1, arcs_17_1}, -X {2, arcs_17_2}, -X {1, arcs_17_3}, -X {1, arcs_17_4}, -X {1, arcs_17_5}, +X {1, arcs_17_0}, +X {1, arcs_17_1}, +X {2, arcs_17_2}, +X {1, arcs_17_3}, +X {1, arcs_17_4}, +X {1, arcs_17_5}, X}; Xstatic arc arcs_18_0[2] = { -X {41, 1}, -X {42, 2}, +X {41, 1}, +X {42, 2}, X}; Xstatic arc arcs_18_1[1] = { -X {13, 3}, +X {13, 3}, X}; Xstatic arc arcs_18_2[1] = { -X {13, 4}, +X {13, 4}, X}; Xstatic arc arcs_18_3[2] = { -X {21, 1}, -X {2, 5}, +X {21, 1}, +X {2, 5}, X}; Xstatic arc arcs_18_4[1] = { -X {41, 6}, +X {41, 6}, X}; Xstatic arc arcs_18_5[1] = { -X {0, 5}, +X {0, 5}, X}; Xstatic arc arcs_18_6[2] = { -X {43, 7}, -X {13, 8}, +X {43, 7}, +X {13, 8}, X}; Xstatic arc arcs_18_7[1] = { -X {2, 5}, +X {2, 5}, X}; Xstatic arc arcs_18_8[2] = { -X {21, 9}, -X {2, 5}, +X {21, 9}, +X {2, 5}, X}; Xstatic arc arcs_18_9[1] = { -X {13, 8}, +X {13, 8}, X}; Xstatic state states_18[10] = { -X {2, arcs_18_0}, -X {1, arcs_18_1}, -X {1, arcs_18_2}, -X {2, arcs_18_3}, -X {1, arcs_18_4}, -X {1, arcs_18_5}, -X {2, arcs_18_6}, -X {1, arcs_18_7}, -X {2, arcs_18_8}, -X {1, arcs_18_9}, +X {2, arcs_18_0}, +X {1, arcs_18_1}, +X {1, arcs_18_2}, +X {2, arcs_18_3}, +X {1, arcs_18_4}, +X {1, arcs_18_5}, +X {2, arcs_18_6}, +X {1, arcs_18_7}, +X {2, arcs_18_8}, +X {1, arcs_18_9}, X}; Xstatic arc arcs_19_0[6] = { -X {44, 1}, -X {45, 1}, -X {46, 1}, -X {47, 1}, -X {11, 1}, -X {48, 1}, +X {44, 1}, +X {45, 1}, +X {46, 1}, +X {47, 1}, +X {11, 1}, +X {48, 1}, X}; Xstatic arc arcs_19_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic state states_19[2] = { -X {6, arcs_19_0}, -X {1, arcs_19_1}, +X {6, arcs_19_0}, +X {1, arcs_19_1}, X}; Xstatic arc arcs_20_0[1] = { -X {49, 1}, +X {49, 1}, X}; Xstatic arc arcs_20_1[1] = { -X {31, 2}, +X {31, 2}, X}; Xstatic arc arcs_20_2[1] = { -X {15, 3}, +X {15, 3}, X}; Xstatic arc arcs_20_3[1] = { -X {16, 4}, +X {16, 4}, X}; Xstatic arc arcs_20_4[3] = { -X {50, 1}, -X {51, 5}, -X {0, 4}, +X {50, 1}, +X {51, 5}, +X {0, 4}, X}; Xstatic arc arcs_20_5[1] = { -X {15, 6}, +X {15, 6}, X}; Xstatic arc arcs_20_6[1] = { -X {16, 7}, +X {16, 7}, X}; Xstatic arc arcs_20_7[1] = { -X {0, 7}, +X {0, 7}, X}; Xstatic state states_20[8] = { -X {1, arcs_20_0}, -X {1, arcs_20_1}, -X {1, arcs_20_2}, -X {1, arcs_20_3}, -X {3, arcs_20_4}, -X {1, arcs_20_5}, -X {1, arcs_20_6}, -X {1, arcs_20_7}, +X {1, arcs_20_0}, +X {1, arcs_20_1}, +X {1, arcs_20_2}, +X {1, arcs_20_3}, +X {3, arcs_20_4}, +X {1, arcs_20_5}, +X {1, arcs_20_6}, +X {1, arcs_20_7}, X}; Xstatic arc arcs_21_0[1] = { -X {52, 1}, +X {52, 1}, X}; Xstatic arc arcs_21_1[1] = { -X {31, 2}, +X {31, 2}, X}; Xstatic arc arcs_21_2[1] = { -X {15, 3}, +X {15, 3}, X}; Xstatic arc arcs_21_3[1] = { -X {16, 4}, +X {16, 4}, X}; Xstatic arc arcs_21_4[2] = { -X {51, 5}, -X {0, 4}, +X {51, 5}, +X {0, 4}, X}; Xstatic arc arcs_21_5[1] = { -X {15, 6}, +X {15, 6}, X}; Xstatic arc arcs_21_6[1] = { -X {16, 7}, +X {16, 7}, X}; Xstatic arc arcs_21_7[1] = { -X {0, 7}, +X {0, 7}, X}; Xstatic state states_21[8] = { -X {1, arcs_21_0}, -X {1, arcs_21_1}, -X {1, arcs_21_2}, -X {1, arcs_21_3}, -X {2, arcs_21_4}, -X {1, arcs_21_5}, -X {1, arcs_21_6}, -X {1, arcs_21_7}, +X {1, arcs_21_0}, +X {1, arcs_21_1}, +X {1, arcs_21_2}, +X {1, arcs_21_3}, +X {2, arcs_21_4}, +X {1, arcs_21_5}, +X {1, arcs_21_6}, +X {1, arcs_21_7}, X}; Xstatic arc arcs_22_0[1] = { -X {53, 1}, +X {53, 1}, X}; Xstatic arc arcs_22_1[1] = { -X {28, 2}, +X {28, 2}, X}; Xstatic arc arcs_22_2[1] = { -X {54, 3}, +X {54, 3}, X}; Xstatic arc arcs_22_3[1] = { -X {28, 4}, +X {28, 4}, X}; Xstatic arc arcs_22_4[1] = { -X {15, 5}, +X {15, 5}, X}; Xstatic arc arcs_22_5[1] = { -X {16, 6}, +X {16, 6}, X}; Xstatic arc arcs_22_6[2] = { -X {51, 7}, -X {0, 6}, +X {51, 7}, +X {0, 6}, X}; Xstatic arc arcs_22_7[1] = { -X {15, 8}, +X {15, 8}, X}; Xstatic arc arcs_22_8[1] = { -X {16, 9}, +X {16, 9}, X}; Xstatic arc arcs_22_9[1] = { -X {0, 9}, +X {0, 9}, X}; Xstatic state states_22[10] = { -X {1, arcs_22_0}, -X {1, arcs_22_1}, -X {1, arcs_22_2}, -X {1, arcs_22_3}, -X {1, arcs_22_4}, -X {1, arcs_22_5}, -X {2, arcs_22_6}, -X {1, arcs_22_7}, -X {1, arcs_22_8}, -X {1, arcs_22_9}, +X {1, arcs_22_0}, +X {1, arcs_22_1}, +X {1, arcs_22_2}, +X {1, arcs_22_3}, +X {1, arcs_22_4}, +X {1, arcs_22_5}, +X {2, arcs_22_6}, +X {1, arcs_22_7}, +X {1, arcs_22_8}, +X {1, arcs_22_9}, X}; Xstatic arc arcs_23_0[1] = { -X {55, 1}, +X {55, 1}, X}; Xstatic arc arcs_23_1[1] = { -X {15, 2}, +X {15, 2}, X}; Xstatic arc arcs_23_2[1] = { -X {16, 3}, +X {16, 3}, X}; Xstatic arc arcs_23_3[3] = { -X {56, 1}, -X {57, 4}, -X {0, 3}, +X {56, 1}, +X {57, 4}, +X {0, 3}, X}; Xstatic arc arcs_23_4[1] = { -X {15, 5}, +X {15, 5}, X}; Xstatic arc arcs_23_5[1] = { -X {16, 6}, +X {16, 6}, X}; Xstatic arc arcs_23_6[1] = { -X {0, 6}, +X {0, 6}, X}; Xstatic state states_23[7] = { -X {1, arcs_23_0}, -X {1, arcs_23_1}, -X {1, arcs_23_2}, -X {3, arcs_23_3}, -X {1, arcs_23_4}, -X {1, arcs_23_5}, -X {1, arcs_23_6}, +X {1, arcs_23_0}, +X {1, arcs_23_1}, +X {1, arcs_23_2}, +X {3, arcs_23_3}, +X {1, arcs_23_4}, +X {1, arcs_23_5}, +X {1, arcs_23_6}, X}; Xstatic arc arcs_24_0[1] = { -X {58, 1}, +X {58, 1}, X}; Xstatic arc arcs_24_1[2] = { -X {40, 2}, -X {0, 1}, +X {40, 2}, +X {0, 1}, X}; Xstatic arc arcs_24_2[2] = { -X {21, 3}, -X {0, 2}, +X {21, 3}, +X {0, 2}, X}; Xstatic arc arcs_24_3[1] = { -X {40, 4}, +X {40, 4}, X}; Xstatic arc arcs_24_4[1] = { -X {0, 4}, +X {0, 4}, X}; Xstatic state states_24[5] = { -X {1, arcs_24_0}, -X {2, arcs_24_1}, -X {2, arcs_24_2}, -X {1, arcs_24_3}, -X {1, arcs_24_4}, +X {1, arcs_24_0}, +X {2, arcs_24_1}, +X {2, arcs_24_2}, +X {1, arcs_24_3}, +X {1, arcs_24_4}, X}; Xstatic arc arcs_25_0[2] = { -X {3, 1}, -X {2, 2}, +X {3, 1}, +X {2, 2}, X}; Xstatic arc arcs_25_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic arc arcs_25_2[1] = { -X {59, 3}, +X {59, 3}, X}; Xstatic arc arcs_25_3[2] = { -X {2, 3}, -X {6, 4}, +X {2, 3}, +X {6, 4}, X}; Xstatic arc arcs_25_4[3] = { -X {6, 4}, -X {2, 4}, -X {60, 1}, +X {6, 4}, +X {2, 4}, +X {60, 1}, X}; Xstatic state states_25[5] = { -X {2, arcs_25_0}, -X {1, arcs_25_1}, -X {1, arcs_25_2}, -X {2, arcs_25_3}, -X {3, arcs_25_4}, +X {2, arcs_25_0}, +X {1, arcs_25_1}, +X {1, arcs_25_2}, +X {2, arcs_25_3}, +X {3, arcs_25_4}, X}; Xstatic arc arcs_26_0[1] = { -X {61, 1}, +X {61, 1}, X}; Xstatic arc arcs_26_1[2] = { -X {62, 0}, -X {0, 1}, +X {62, 0}, +X {0, 1}, X}; Xstatic state states_26[2] = { -X {1, arcs_26_0}, -X {2, arcs_26_1}, +X {1, arcs_26_0}, +X {2, arcs_26_1}, X}; Xstatic arc arcs_27_0[1] = { -X {63, 1}, +X {63, 1}, X}; Xstatic arc arcs_27_1[2] = { -X {64, 0}, -X {0, 1}, +X {64, 0}, +X {0, 1}, X}; Xstatic state states_27[2] = { -X {1, arcs_27_0}, -X {2, arcs_27_1}, +X {1, arcs_27_0}, +X {2, arcs_27_1}, X}; Xstatic arc arcs_28_0[2] = { -X {65, 1}, -X {66, 2}, +X {65, 1}, +X {66, 2}, X}; Xstatic arc arcs_28_1[1] = { -X {63, 2}, +X {63, 2}, X}; Xstatic arc arcs_28_2[1] = { -X {0, 2}, +X {0, 2}, X}; Xstatic state states_28[3] = { -X {2, arcs_28_0}, -X {1, arcs_28_1}, -X {1, arcs_28_2}, +X {2, arcs_28_0}, +X {1, arcs_28_1}, +X {1, arcs_28_2}, X}; Xstatic arc arcs_29_0[1] = { -X {40, 1}, +X {40, 1}, X}; Xstatic arc arcs_29_1[2] = { -X {67, 0}, -X {0, 1}, +X {67, 0}, +X {0, 1}, X}; Xstatic state states_29[2] = { -X {1, arcs_29_0}, -X {2, arcs_29_1}, +X {1, arcs_29_0}, +X {2, arcs_29_1}, X}; Xstatic arc arcs_30_0[6] = { -X {68, 1}, -X {69, 2}, -X {29, 3}, -X {54, 3}, -X {65, 4}, -X {70, 5}, +X {68, 1}, +X {69, 2}, +X {29, 3}, +X {54, 3}, +X {65, 4}, +X {70, 5}, X}; Xstatic arc arcs_30_1[3] = { -X {29, 3}, -X {69, 3}, -X {0, 1}, +X {29, 3}, +X {69, 3}, +X {0, 1}, X}; Xstatic arc arcs_30_2[2] = { -X {29, 3}, -X {0, 2}, +X {29, 3}, +X {0, 2}, X}; Xstatic arc arcs_30_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic arc arcs_30_4[1] = { -X {54, 3}, +X {54, 3}, X}; Xstatic arc arcs_30_5[2] = { -X {65, 3}, -X {0, 5}, +X {65, 3}, +X {0, 5}, X}; Xstatic state states_30[6] = { -X {6, arcs_30_0}, -X {3, arcs_30_1}, -X {2, arcs_30_2}, -X {1, arcs_30_3}, -X {1, arcs_30_4}, -X {2, arcs_30_5}, +X {6, arcs_30_0}, +X {3, arcs_30_1}, +X {2, arcs_30_2}, +X {1, arcs_30_3}, +X {1, arcs_30_4}, +X {2, arcs_30_5}, X}; Xstatic arc arcs_31_0[1] = { -X {71, 1}, +X {71, 1}, X}; Xstatic arc arcs_31_1[3] = { -X {72, 0}, -X {73, 0}, -X {0, 1}, +X {72, 0}, +X {73, 0}, +X {0, 1}, X}; Xstatic state states_31[2] = { -X {1, arcs_31_0}, -X {3, arcs_31_1}, +X {1, arcs_31_0}, +X {3, arcs_31_1}, X}; Xstatic arc arcs_32_0[1] = { -X {74, 1}, +X {74, 1}, X}; Xstatic arc arcs_32_1[4] = { -X {43, 0}, -X {75, 0}, -X {76, 0}, -X {0, 1}, +X {43, 0}, +X {75, 0}, +X {76, 0}, +X {0, 1}, X}; Xstatic state states_32[2] = { -X {1, arcs_32_0}, -X {4, arcs_32_1}, +X {1, arcs_32_0}, +X {4, arcs_32_1}, X}; Xstatic arc arcs_33_0[3] = { -X {72, 1}, -X {73, 1}, -X {77, 2}, +X {72, 1}, +X {73, 1}, +X {77, 2}, X}; Xstatic arc arcs_33_1[1] = { -X {74, 3}, +X {74, 3}, X}; Xstatic arc arcs_33_2[2] = { -X {78, 2}, -X {0, 2}, +X {78, 2}, +X {0, 2}, X}; Xstatic arc arcs_33_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic state states_33[4] = { -X {3, arcs_33_0}, -X {1, arcs_33_1}, -X {2, arcs_33_2}, -X {1, arcs_33_3}, +X {3, arcs_33_0}, +X {1, arcs_33_1}, +X {2, arcs_33_2}, +X {1, arcs_33_3}, X}; Xstatic arc arcs_34_0[7] = { -X {17, 1}, -X {79, 2}, -X {81, 3}, -X {83, 4}, -X {13, 5}, -X {84, 5}, -X {85, 5}, +X {17, 1}, +X {79, 2}, +X {81, 3}, +X {83, 4}, +X {13, 5}, +X {84, 5}, +X {85, 5}, X}; Xstatic arc arcs_34_1[2] = { -X {9, 6}, -X {19, 5}, +X {9, 6}, +X {19, 5}, X}; Xstatic arc arcs_34_2[2] = { -X {9, 7}, -X {80, 5}, +X {9, 7}, +X {80, 5}, X}; Xstatic arc arcs_34_3[1] = { -X {82, 5}, +X {82, 5}, X}; Xstatic arc arcs_34_4[1] = { -X {9, 8}, +X {9, 8}, X}; Xstatic arc arcs_34_5[1] = { -X {0, 5}, +X {0, 5}, X}; Xstatic arc arcs_34_6[1] = { -X {19, 5}, +X {19, 5}, X}; Xstatic arc arcs_34_7[1] = { -X {80, 5}, +X {80, 5}, X}; Xstatic arc arcs_34_8[1] = { -X {83, 5}, +X {83, 5}, X}; Xstatic state states_34[9] = { -X {7, arcs_34_0}, -X {2, arcs_34_1}, -X {2, arcs_34_2}, -X {1, arcs_34_3}, -X {1, arcs_34_4}, -X {1, arcs_34_5}, -X {1, arcs_34_6}, -X {1, arcs_34_7}, -X {1, arcs_34_8}, +X {7, arcs_34_0}, +X {2, arcs_34_1}, +X {2, arcs_34_2}, +X {1, arcs_34_3}, +X {1, arcs_34_4}, +X {1, arcs_34_5}, +X {1, arcs_34_6}, +X {1, arcs_34_7}, +X {1, arcs_34_8}, X}; Xstatic arc arcs_35_0[3] = { -X {17, 1}, -X {79, 2}, -X {87, 3}, +X {17, 1}, +X {79, 2}, +X {87, 3}, X}; Xstatic arc arcs_35_1[2] = { -X {9, 4}, -X {19, 5}, +X {9, 4}, +X {19, 5}, X}; Xstatic arc arcs_35_2[1] = { -X {86, 6}, +X {86, 6}, X}; Xstatic arc arcs_35_3[1] = { -X {13, 5}, +X {13, 5}, X}; Xstatic arc arcs_35_4[1] = { -X {19, 5}, +X {19, 5}, X}; Xstatic arc arcs_35_5[1] = { -X {0, 5}, +X {0, 5}, X}; Xstatic arc arcs_35_6[1] = { -X {80, 5}, +X {80, 5}, X}; Xstatic state states_35[7] = { -X {3, arcs_35_0}, -X {2, arcs_35_1}, -X {1, arcs_35_2}, -X {1, arcs_35_3}, -X {1, arcs_35_4}, -X {1, arcs_35_5}, -X {1, arcs_35_6}, +X {3, arcs_35_0}, +X {2, arcs_35_1}, +X {1, arcs_35_2}, +X {1, arcs_35_3}, +X {1, arcs_35_4}, +X {1, arcs_35_5}, +X {1, arcs_35_6}, X}; Xstatic arc arcs_36_0[2] = { -X {40, 1}, -X {15, 2}, +X {40, 1}, +X {15, 2}, X}; Xstatic arc arcs_36_1[2] = { -X {15, 2}, -X {0, 1}, +X {15, 2}, +X {0, 1}, X}; Xstatic arc arcs_36_2[2] = { -X {40, 3}, -X {0, 2}, +X {40, 3}, +X {0, 2}, X}; Xstatic arc arcs_36_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic state states_36[4] = { -X {2, arcs_36_0}, -X {2, arcs_36_1}, -X {2, arcs_36_2}, -X {1, arcs_36_3}, +X {2, arcs_36_0}, +X {2, arcs_36_1}, +X {2, arcs_36_2}, +X {1, arcs_36_3}, X}; Xstatic arc arcs_37_0[1] = { -X {40, 1}, +X {40, 1}, X}; Xstatic arc arcs_37_1[2] = { -X {21, 2}, -X {0, 1}, +X {21, 2}, +X {0, 1}, X}; Xstatic arc arcs_37_2[2] = { -X {40, 1}, -X {0, 2}, +X {40, 1}, +X {0, 2}, X}; Xstatic state states_37[3] = { -X {1, arcs_37_0}, -X {2, arcs_37_1}, -X {2, arcs_37_2}, +X {1, arcs_37_0}, +X {2, arcs_37_1}, +X {2, arcs_37_2}, X}; Xstatic arc arcs_38_0[1] = { -X {31, 1}, +X {31, 1}, X}; Xstatic arc arcs_38_1[2] = { -X {21, 2}, -X {0, 1}, +X {21, 2}, +X {0, 1}, X}; Xstatic arc arcs_38_2[2] = { -X {31, 1}, -X {0, 2}, +X {31, 1}, +X {0, 2}, X}; Xstatic state states_38[3] = { -X {1, arcs_38_0}, -X {2, arcs_38_1}, -X {2, arcs_38_2}, +X {1, arcs_38_0}, +X {2, arcs_38_1}, +X {2, arcs_38_2}, X}; Xstatic arc arcs_39_0[1] = { -X {88, 1}, +X {88, 1}, X}; Xstatic arc arcs_39_1[1] = { -X {13, 2}, +X {13, 2}, X}; Xstatic arc arcs_39_2[1] = { -X {14, 3}, +X {14, 3}, X}; Xstatic arc arcs_39_3[2] = { -X {29, 4}, -X {15, 5}, +X {29, 4}, +X {15, 5}, X}; Xstatic arc arcs_39_4[1] = { -X {89, 6}, +X {89, 6}, X}; Xstatic arc arcs_39_5[1] = { -X {16, 7}, +X {16, 7}, X}; Xstatic arc arcs_39_6[1] = { -X {15, 5}, +X {15, 5}, X}; Xstatic arc arcs_39_7[1] = { -X {0, 7}, +X {0, 7}, X}; Xstatic state states_39[8] = { -X {1, arcs_39_0}, -X {1, arcs_39_1}, -X {1, arcs_39_2}, -X {2, arcs_39_3}, -X {1, arcs_39_4}, -X {1, arcs_39_5}, -X {1, arcs_39_6}, -X {1, arcs_39_7}, +X {1, arcs_39_0}, +X {1, arcs_39_1}, +X {1, arcs_39_2}, +X {2, arcs_39_3}, +X {1, arcs_39_4}, +X {1, arcs_39_5}, +X {1, arcs_39_6}, +X {1, arcs_39_7}, X}; Xstatic arc arcs_40_0[1] = { -X {77, 1}, +X {77, 1}, X}; Xstatic arc arcs_40_1[1] = { -X {90, 2}, +X {90, 2}, X}; Xstatic arc arcs_40_2[2] = { -X {21, 0}, -X {0, 2}, +X {21, 0}, +X {0, 2}, X}; Xstatic state states_40[3] = { -X {1, arcs_40_0}, -X {1, arcs_40_1}, -X {2, arcs_40_2}, +X {1, arcs_40_0}, +X {1, arcs_40_1}, +X {2, arcs_40_2}, X}; Xstatic arc arcs_41_0[1] = { -X {17, 1}, +X {17, 1}, X}; Xstatic arc arcs_41_1[2] = { -X {9, 2}, -X {19, 3}, +X {9, 2}, +X {19, 3}, X}; Xstatic arc arcs_41_2[1] = { -X {19, 3}, +X {19, 3}, X}; Xstatic arc arcs_41_3[1] = { -X {0, 3}, +X {0, 3}, X}; Xstatic state states_41[4] = { -X {1, arcs_41_0}, -X {2, arcs_41_1}, -X {1, arcs_41_2}, -X {1, arcs_41_3}, +X {1, arcs_41_0}, +X {2, arcs_41_1}, +X {1, arcs_41_2}, +X {1, arcs_41_3}, X}; Xstatic dfa dfas[42] = { -X {256, "single_input", 0, 3, states_0, -X "\004\060\002\100\343\006\262\000\000\203\072\001"}, -X {257, "file_input", 0, 2, states_1, -X "\204\060\002\100\343\006\262\000\000\203\072\001"}, -X {258, "expr_input", 0, 3, states_2, -X "\000\040\002\000\000\000\000\000\002\203\072\000"}, -X {259, "eval_input", 0, 3, states_3, -X "\000\040\002\000\000\000\000\000\002\203\072\000"}, -X {260, "funcdef", 0, 6, states_4, -X "\000\020\000\000\000\000\000\000\000\000\000\000"}, -X {261, "parameters", 0, 4, states_5, -X "\000\000\002\000\000\000\000\000\000\000\000\000"}, -X {262, "fplist", 0, 2, states_6, -X "\000\040\002\000\000\000\000\000\000\000\000\000"}, -X {263, "fpdef", 0, 4, states_7, -X "\000\040\002\000\000\000\000\000\000\000\000\000"}, -X {264, "stmt", 0, 2, states_8, -X "\000\060\002\100\343\006\262\000\000\203\072\001"}, -X {265, "simple_stmt", 0, 2, states_9, -X "\000\040\002\100\343\006\000\000\000\203\072\000"}, -X {266, "expr_stmt", 0, 3, states_10, -X "\000\040\002\000\000\000\000\000\000\203\072\000"}, -X {267, "print_stmt", 0, 4, states_11, -X "\000\000\000\100\000\000\000\000\000\000\000\000"}, -X {268, "del_stmt", 0, 4, states_12, -X "\000\000\000\000\001\000\000\000\000\000\000\000"}, -X {269, "pass_stmt", 0, 3, states_13, -X "\000\000\000\000\002\000\000\000\000\000\000\000"}, -X {270, "flow_stmt", 0, 2, states_14, -X "\000\000\000\000\340\000\000\000\000\000\000\000"}, -X {271, "break_stmt", 0, 3, states_15, -X "\000\000\000\000\040\000\000\000\000\000\000\000"}, -X {272, "return_stmt", 0, 4, states_16, -X "\000\000\000\000\100\000\000\000\000\000\000\000"}, -X {273, "raise_stmt", 0, 6, states_17, -X "\000\000\000\000\200\000\000\000\000\000\000\000"}, -X {274, "import_stmt", 0, 10, states_18, -X "\000\000\000\000\000\006\000\000\000\000\000\000"}, -X {275, "compound_stmt", 0, 2, states_19, -X "\000\020\000\000\000\000\262\000\000\000\000\001"}, -X {276, "if_stmt", 0, 8, states_20, -X "\000\000\000\000\000\000\002\000\000\000\000\000"}, -X {277, "while_stmt", 0, 8, states_21, -X "\000\000\000\000\000\000\020\000\000\000\000\000"}, -X {278, "for_stmt", 0, 10, states_22, -X "\000\000\000\000\000\000\040\000\000\000\000\000"}, -X {279, "try_stmt", 0, 7, states_23, -X "\000\000\000\000\000\000\200\000\000\000\000\000"}, -X {280, "except_clause", 0, 5, states_24, -X "\000\000\000\000\000\000\000\004\000\000\000\000"}, -X {281, "suite", 0, 5, states_25, -X "\004\040\002\100\343\006\000\000\000\203\072\000"}, -X {282, "test", 0, 2, states_26, -X "\000\040\002\000\000\000\000\000\002\203\072\000"}, -X {283, "and_test", 0, 2, states_27, -X "\000\040\002\000\000\000\000\000\002\203\072\000"}, -X {284, "not_test", 0, 3, states_28, -X "\000\040\002\000\000\000\000\000\002\203\072\000"}, -X {285, "comparison", 0, 2, states_29, -X "\000\040\002\000\000\000\000\000\000\203\072\000"}, -X {286, "comp_op", 0, 6, states_30, -X "\000\000\000\040\000\000\100\000\162\000\000\000"}, -X {287, "expr", 0, 2, states_31, -X "\000\040\002\000\000\000\000\000\000\203\072\000"}, -X {288, "term", 0, 2, states_32, -X "\000\040\002\000\000\000\000\000\000\203\072\000"}, -X {289, "factor", 0, 4, states_33, -X "\000\040\002\000\000\000\000\000\000\203\072\000"}, -X {290, "atom", 0, 9, states_34, -X "\000\040\002\000\000\000\000\000\000\200\072\000"}, -X {291, "trailer", 0, 7, states_35, -X "\000\000\002\000\000\000\000\000\000\200\200\000"}, -X {292, "subscript", 0, 4, states_36, -X "\000\240\002\000\000\000\000\000\000\203\072\000"}, -X {293, "exprlist", 0, 3, states_37, -X "\000\040\002\000\000\000\000\000\000\203\072\000"}, -X {294, "testlist", 0, 3, states_38, -X "\000\040\002\000\000\000\000\000\002\203\072\000"}, -X {295, "classdef", 0, 8, states_39, -X "\000\000\000\000\000\000\000\000\000\000\000\001"}, -X {296, "baselist", 0, 3, states_40, -X "\000\040\002\000\000\000\000\000\000\200\072\000"}, -X {297, "arguments", 0, 4, states_41, -X "\000\000\002\000\000\000\000\000\000\000\000\000"}, +X {256, "single_input", 0, 3, states_0, +X "\004\060\002\100\343\006\262\000\000\203\072\001"}, +X {257, "file_input", 0, 2, states_1, +X "\204\060\002\100\343\006\262\000\000\203\072\001"}, +X {258, "expr_input", 0, 3, states_2, +X "\000\040\002\000\000\000\000\000\002\203\072\000"}, +X {259, "eval_input", 0, 3, states_3, +X "\000\040\002\000\000\000\000\000\002\203\072\000"}, +X {260, "funcdef", 0, 6, states_4, +X "\000\020\000\000\000\000\000\000\000\000\000\000"}, +X {261, "parameters", 0, 4, states_5, +X "\000\000\002\000\000\000\000\000\000\000\000\000"}, +X {262, "fplist", 0, 2, states_6, +X "\000\040\002\000\000\000\000\000\000\000\000\000"}, +X {263, "fpdef", 0, 4, states_7, +X "\000\040\002\000\000\000\000\000\000\000\000\000"}, +X {264, "stmt", 0, 2, states_8, +X "\000\060\002\100\343\006\262\000\000\203\072\001"}, +X {265, "simple_stmt", 0, 2, states_9, +X "\000\040\002\100\343\006\000\000\000\203\072\000"}, +X {266, "expr_stmt", 0, 3, states_10, +X "\000\040\002\000\000\000\000\000\000\203\072\000"}, +X {267, "print_stmt", 0, 4, states_11, +X "\000\000\000\100\000\000\000\000\000\000\000\000"}, +X {268, "del_stmt", 0, 4, states_12, +X "\000\000\000\000\001\000\000\000\000\000\000\000"}, +X {269, "pass_stmt", 0, 3, states_13, +X "\000\000\000\000\002\000\000\000\000\000\000\000"}, +X {270, "flow_stmt", 0, 2, states_14, +X "\000\000\000\000\340\000\000\000\000\000\000\000"}, +X {271, "break_stmt", 0, 3, states_15, +X "\000\000\000\000\040\000\000\000\000\000\000\000"}, +X {272, "return_stmt", 0, 4, states_16, +X "\000\000\000\000\100\000\000\000\000\000\000\000"}, +X {273, "raise_stmt", 0, 6, states_17, +X "\000\000\000\000\200\000\000\000\000\000\000\000"}, +X {274, "import_stmt", 0, 10, states_18, +X "\000\000\000\000\000\006\000\000\000\000\000\000"}, +X {275, "compound_stmt", 0, 2, states_19, +X "\000\020\000\000\000\000\262\000\000\000\000\001"}, +X {276, "if_stmt", 0, 8, states_20, +X "\000\000\000\000\000\000\002\000\000\000\000\000"}, +X {277, "while_stmt", 0, 8, states_21, +X "\000\000\000\000\000\000\020\000\000\000\000\000"}, +X {278, "for_stmt", 0, 10, states_22, +X "\000\000\000\000\000\000\040\000\000\000\000\000"}, +X {279, "try_stmt", 0, 7, states_23, +X "\000\000\000\000\000\000\200\000\000\000\000\000"}, +X {280, "except_clause", 0, 5, states_24, +X "\000\000\000\000\000\000\000\004\000\000\000\000"}, +X {281, "suite", 0, 5, states_25, +X "\004\040\002\100\343\006\000\000\000\203\072\000"}, +X {282, "test", 0, 2, states_26, +X "\000\040\002\000\000\000\000\000\002\203\072\000"}, +X {283, "and_test", 0, 2, states_27, +X "\000\040\002\000\000\000\000\000\002\203\072\000"}, +X {284, "not_test", 0, 3, states_28, +X "\000\040\002\000\000\000\000\000\002\203\072\000"}, +X {285, "comparison", 0, 2, states_29, +X "\000\040\002\000\000\000\000\000\000\203\072\000"}, +X {286, "comp_op", 0, 6, states_30, +X "\000\000\000\040\000\000\100\000\162\000\000\000"}, +X {287, "expr", 0, 2, states_31, +X "\000\040\002\000\000\000\000\000\000\203\072\000"}, +X {288, "term", 0, 2, states_32, +X "\000\040\002\000\000\000\000\000\000\203\072\000"}, +X {289, "factor", 0, 4, states_33, +X "\000\040\002\000\000\000\000\000\000\203\072\000"}, +X {290, "atom", 0, 9, states_34, +X "\000\040\002\000\000\000\000\000\000\200\072\000"}, +X {291, "trailer", 0, 7, states_35, +X "\000\000\002\000\000\000\000\000\000\200\200\000"}, +X {292, "subscript", 0, 4, states_36, +X "\000\240\002\000\000\000\000\000\000\203\072\000"}, +X {293, "exprlist", 0, 3, states_37, +X "\000\040\002\000\000\000\000\000\000\203\072\000"}, +X {294, "testlist", 0, 3, states_38, +X "\000\040\002\000\000\000\000\000\002\203\072\000"}, +X {295, "classdef", 0, 8, states_39, +X "\000\000\000\000\000\000\000\000\000\000\000\001"}, +X {296, "baselist", 0, 3, states_40, +X "\000\040\002\000\000\000\000\000\000\200\072\000"}, +X {297, "arguments", 0, 4, states_41, +X "\000\000\002\000\000\000\000\000\000\000\000\000"}, X}; Xstatic label labels[91] = { -X {0, "EMPTY"}, -X {256, 0}, -X {4, 0}, -X {265, 0}, -X {275, 0}, -X {257, 0}, -X {264, 0}, -X {0, 0}, -X {258, 0}, -X {294, 0}, -X {259, 0}, -X {260, 0}, -X {1, "def"}, -X {1, 0}, -X {261, 0}, -X {11, 0}, -X {281, 0}, -X {7, 0}, -X {262, 0}, -X {8, 0}, -X {263, 0}, -X {12, 0}, -X {266, 0}, -X {267, 0}, -X {269, 0}, -X {268, 0}, -X {270, 0}, -X {274, 0}, -X {293, 0}, -X {22, 0}, -X {1, "print"}, -X {282, 0}, -X {1, "del"}, -X {1, "pass"}, -X {271, 0}, -X {272, 0}, -X {273, 0}, -X {1, "break"}, -X {1, "return"}, -X {1, "raise"}, -X {287, 0}, -X {1, "import"}, -X {1, "from"}, -X {16, 0}, -X {276, 0}, -X {277, 0}, -X {278, 0}, -X {279, 0}, -X {295, 0}, -X {1, "if"}, -X {1, "elif"}, -X {1, "else"}, -X {1, "while"}, -X {1, "for"}, -X {1, "in"}, -X {1, "try"}, -X {280, 0}, -X {1, "finally"}, -X {1, "except"}, -X {5, 0}, -X {6, 0}, -X {283, 0}, -X {1, "or"}, -X {284, 0}, -X {1, "and"}, -X {1, "not"}, -X {285, 0}, -X {286, 0}, -X {20, 0}, -X {21, 0}, -X {1, "is"}, -X {288, 0}, -X {14, 0}, -X {15, 0}, -X {289, 0}, -X {17, 0}, -X {24, 0}, -X {290, 0}, -X {291, 0}, -X {9, 0}, -X {10, 0}, -X {26, 0}, -X {27, 0}, -X {25, 0}, -X {2, 0}, -X {3, 0}, -X {292, 0}, -X {23, 0}, -X {1, "class"}, -X {296, 0}, -X {297, 0}, +X {0, "EMPTY"}, +X {256, 0}, +X {4, 0}, +X {265, 0}, +X {275, 0}, +X {257, 0}, +X {264, 0}, +X {0, 0}, +X {258, 0}, +X {294, 0}, +X {259, 0}, +X {260, 0}, +X {1, "def"}, +X {1, 0}, +X {261, 0}, +X {11, 0}, +X {281, 0}, +X {7, 0}, +X {262, 0}, +X {8, 0}, +X {263, 0}, +X {12, 0}, +X {266, 0}, +X {267, 0}, +X {269, 0}, +X {268, 0}, +X {270, 0}, +X {274, 0}, +X {293, 0}, +X {22, 0}, +X {1, "print"}, +X {282, 0}, +X {1, "del"}, +X {1, "pass"}, +X {271, 0}, +X {272, 0}, +X {273, 0}, +X {1, "break"}, +X {1, "return"}, +X {1, "raise"}, +X {287, 0}, +X {1, "import"}, +X {1, "from"}, +X {16, 0}, +X {276, 0}, +X {277, 0}, +X {278, 0}, +X {279, 0}, +X {295, 0}, +X {1, "if"}, +X {1, "elif"}, +X {1, "else"}, +X {1, "while"}, +X {1, "for"}, +X {1, "in"}, +X {1, "try"}, +X {280, 0}, +X {1, "finally"}, +X {1, "except"}, +X {5, 0}, +X {6, 0}, +X {283, 0}, +X {1, "or"}, +X {284, 0}, +X {1, "and"}, +X {1, "not"}, +X {285, 0}, +X {286, 0}, +X {20, 0}, +X {21, 0}, +X {1, "is"}, +X {288, 0}, +X {14, 0}, +X {15, 0}, +X {289, 0}, +X {17, 0}, +X {24, 0}, +X {290, 0}, +X {291, 0}, +X {9, 0}, +X {10, 0}, +X {26, 0}, +X {27, 0}, +X {25, 0}, +X {2, 0}, +X {3, 0}, +X {292, 0}, +X {23, 0}, +X {1, "class"}, +X {296, 0}, +X {297, 0}, X}; Xgrammar gram = { -X 42, -X dfas, -X {91, labels}, -X 256 +X 42, +X dfas, +X {91, labels}, +X 256 X}; EOF fi @@ -2892,12 +2892,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2922,13 +2922,13 @@ XNEWOBJ(type, typeobj) allocates memory for a new object of the given Xtype; here 'type' must be the C structure type used to represent the Xobject and 'typeobj' the address of the corresponding type object. XReference count and type pointer are filled in; the rest of the bytes of -Xthe object are *undefined*! The resulting expression type is 'type *'. +Xthe object are *undefined*! The resulting expression type is 'type *'. XThe size of the object is actually determined by the tp_basicsize field Xof the type object. X XNEWVAROBJ(type, typeobj, n) is similar but allocates a variable-size -Xobject with n extra items. The size is computer as tp_basicsize plus -Xn * tp_itemsize. This fills in the ob_size field as well. +Xobject with n extra items. The size is computer as tp_basicsize plus +Xn * tp_itemsize. This fills in the ob_size field as well. X*/ X Xextern object *newobject PROTO((typeobject *)); @@ -2941,4 +2941,4 @@ Xextern int StopPrint; /* Set when printing is interrupted */ EOF fi echo 'Part 03 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-04-21.shar b/shar/python-0.9.1-04-21.shar index 5f1cbee..b1a5d00 100644 --- a/shar/python-0.9.1-04-21.shar +++ b/shar/python-0.9.1-04-21.shar @@ -57,20 +57,20 @@ X X<returntype> can be: void, short, long (XXX maybe others?) X X<type> can be: char, string, short, float, long, or double -X string indicates a null terminated string; -X if <type> is char and <arg> begins with a *, the * is stripped -X and <type> is changed into string +X string indicates a null terminated string; +X if <type> is char and <arg> begins with a *, the * is stripped +X and <type> is changed into string X X<arg> has the form <mode> or <mode>[<subscript>] -X where <mode> can be -X s: arg is sent -X r: arg is received (arg is a pointer) -X and <subscript> can be (N and I are numbers): -X N -X argI -X retval -X N*argI -X N*retval +X where <mode> can be +X s: arg is sent +X r: arg is received (arg is a pointer) +X and <subscript> can be (N and I are numbers): +X N +X argI +X retval +X N*argI +X N*retval X*/ X X#include <gl.h> @@ -93,7 +93,7 @@ Xvarray -- an array of v.. calls. XThe argument is an array (maybe list or tuple) of points. XEach point must be a tuple or list of coordinates (x, y, z). XThe points may be 2- or 3-dimensional but must all have the -Xsame dimension. Float and int values may be mixed however. +Xsame dimension. Float and int values may be mixed however. XThe points are always converted to 3D double precision points Xby assuming z=0.0 if necessary (as indicated in the man page), Xand for each point v3d() is called. @@ -103,67 +103,67 @@ X% varray X Xstatic object * Xgl_varray(self, args) -X object *self; -X object *args; -X{ -X object *v, *w; -X int i, n, width; -X double vec[3]; -X object * (*getitem) FPROTO((object *, int)); -X -X if (!getiobjectarg(args, 1, 0, &v)) -X return NULL; -X -X if (is_listobject(v)) { -X n = getlistsize(v); -X getitem = getlistitem; -X } -X else if (is_tupleobject(v)) { -X n = gettuplesize(v); -X getitem = gettupleitem; -X } -X else { -X err_badarg(); -X return NULL; -X } -X -X if (n == 0) { -X INCREF(None); -X return None; -X } -X if (n > 0) -X w = (*getitem)(v, 0); -X -X width = 0; -X if (w == NULL) { -X } -X else if (is_listobject(w)) { -X width = getlistsize(w); -X } -X else if (is_tupleobject(w)) { -X width = gettuplesize(w); -X } -X -X switch (width) { -X case 2: -X vec[2] = 0.0; -X /* Fall through */ -X case 3: -X break; -X default: -X err_badarg(); -X return NULL; -X } -X -X for (i = 0; i < n; i++) { -X w = (*getitem)(v, i); -X if (!getidoublearray(w, 1, 0, width, vec)) -X return NULL; -X v3d(vec); -X } -X -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X object *v, *w; +X int i, n, width; +X double vec[3]; +X object * (*getitem) FPROTO((object *, int)); +X +X if (!getiobjectarg(args, 1, 0, &v)) +X return NULL; +X +X if (is_listobject(v)) { +X n = getlistsize(v); +X getitem = getlistitem; +X } +X else if (is_tupleobject(v)) { +X n = gettuplesize(v); +X getitem = gettupleitem; +X } +X else { +X err_badarg(); +X return NULL; +X } +X +X if (n == 0) { +X INCREF(None); +X return None; +X } +X if (n > 0) +X w = (*getitem)(v, 0); +X +X width = 0; +X if (w == NULL) { +X } +X else if (is_listobject(w)) { +X width = getlistsize(w); +X } +X else if (is_tupleobject(w)) { +X width = gettuplesize(w); +X } +X +X switch (width) { +X case 2: +X vec[2] = 0.0; +X /* Fall through */ +X case 3: +X break; +X default: +X err_badarg(); +X return NULL; +X } +X +X for (i = 0; i < n; i++) { +X w = (*getitem)(v, i); +X if (!getidoublearray(w, 1, 0, width, vec)) +X return NULL; +X v3d(vec); +X } +X +X INCREF(None); +X return None; X} X X/* @@ -171,7 +171,7 @@ Xvnarray, nvarray -- an array of n3f and v3f calls. XThe argument is an array (list or tuple) of pairs of points and normals. XEach pair is a tuple (NOT a list) of a point and a normal for that point. XEach point or normal must be a tuple (NOT a list) of coordinates (x, y, z). -XThree coordinates must be given. Float and int values may be mixed. +XThree coordinates must be given. Float and int values may be mixed. XFor each pair, n3f() is called for the normal, and then v3f() is called Xfor the vector. X @@ -185,267 +185,267 @@ X% nvarray X Xstatic object * Xgl_nvarray(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return gen_nvarray(args, 0); +X return gen_nvarray(args, 0); X} X X% vnarray X Xstatic object * Xgl_vnarray(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return gen_nvarray(args, 1); +X return gen_nvarray(args, 1); X} X X/* Generic, internal version of {nv,nv}array: inorm indicates the -X argument order, 0: normal first, 1: vector first. */ +X argument order, 0: normal first, 1: vector first. */ X Xstatic object * Xgen_nvarray(args, inorm) -X object *args; -X int inorm; -X{ -X object *v, *w, *wnorm, *wvec; -X int i, n; -X float norm[3], vec[3]; -X object * (*getitem) FPROTO((object *, int)); -X -X if (!getiobjectarg(args, 1, 0, &v)) -X return NULL; -X -X if (is_listobject(v)) { -X n = getlistsize(v); -X getitem = getlistitem; -X } -X else if (is_tupleobject(v)) { -X n = gettuplesize(v); -X getitem = gettupleitem; -X } -X else { -X err_badarg(); -X return NULL; -X } -X -X for (i = 0; i < n; i++) { -X w = (*getitem)(v, i); -X if (!is_tupleobject(w) || gettuplesize(w) != 2) { -X err_badarg(); -X return NULL; -X } -X wnorm = gettupleitem(w, inorm); -X wvec = gettupleitem(w, 1 - inorm); -X if (!getifloatarray(wnorm, 1, 0, 3, norm) || -X !getifloatarray(wvec, 1, 0, 3, vec)) -X return NULL; -X n3f(norm); -X v3f(vec); -X } -X -X INCREF(None); -X return None; +X object *args; +X int inorm; +X{ +X object *v, *w, *wnorm, *wvec; +X int i, n; +X float norm[3], vec[3]; +X object * (*getitem) FPROTO((object *, int)); +X +X if (!getiobjectarg(args, 1, 0, &v)) +X return NULL; +X +X if (is_listobject(v)) { +X n = getlistsize(v); +X getitem = getlistitem; +X } +X else if (is_tupleobject(v)) { +X n = gettuplesize(v); +X getitem = gettupleitem; +X } +X else { +X err_badarg(); +X return NULL; +X } +X +X for (i = 0; i < n; i++) { +X w = (*getitem)(v, i); +X if (!is_tupleobject(w) || gettuplesize(w) != 2) { +X err_badarg(); +X return NULL; +X } +X wnorm = gettupleitem(w, inorm); +X wvec = gettupleitem(w, 1 - inorm); +X if (!getifloatarray(wnorm, 1, 0, 3, norm) || +X !getifloatarray(wvec, 1, 0, 3, vec)) +X return NULL; +X n3f(norm); +X v3f(vec); +X } +X +X INCREF(None); +X return None; X} X X/* nurbssurface(s_knots[], t_knots[], ctl[][], s_order, t_order, type). -X The dimensions of ctl[] are computed as follows: -X [len(s_knots) - s_order], [len(t_knots) - t_order] +X The dimensions of ctl[] are computed as follows: +X [len(s_knots) - s_order], [len(t_knots) - t_order] X*/ X X% nurbssurface X Xstatic object * Xgl_nurbssurface(self, args) -X object *self; -X object *args; -X{ -X long arg1 ; -X double * arg2 ; -X long arg3 ; -X double * arg4 ; -X double *arg5 ; -X long arg6 ; -X long arg7 ; -X long arg8 ; -X long ncoords; -X long s_byte_stride, t_byte_stride; -X long s_nctl, t_nctl; -X long s, t; -X object *v, *w, *pt; -X double *pnext; -X if (!getilongarraysize(args, 6, 0, &arg1)) -X return NULL; -X if ((arg2 = NEW(double, arg1 )) == NULL) { -X return err_nomem(); -X } -X if (!getidoublearray(args, 6, 0, arg1 , arg2)) -X return NULL; -X if (!getilongarraysize(args, 6, 1, &arg3)) -X return NULL; -X if ((arg4 = NEW(double, arg3 )) == NULL) { -X return err_nomem(); -X } -X if (!getidoublearray(args, 6, 1, arg3 , arg4)) -X return NULL; -X if (!getilongarg(args, 6, 3, &arg6)) -X return NULL; -X if (!getilongarg(args, 6, 4, &arg7)) -X return NULL; -X if (!getilongarg(args, 6, 5, &arg8)) -X return NULL; -X if (arg8 == N_XYZ) -X ncoords = 3; -X else if (arg8 == N_XYZW) -X ncoords = 4; -X else { -X err_badarg(); -X return NULL; -X } -X s_nctl = arg1 - arg6; -X t_nctl = arg3 - arg7; -X if (!getiobjectarg(args, 6, 2, &v)) -X return NULL; -X if (!is_listobject(v) || getlistsize(v) != s_nctl) { -X err_badarg(); -X return NULL; -X } -X if ((arg5 = NEW(double, s_nctl*t_nctl*ncoords )) == NULL) { -X return err_nomem(); -X } -X pnext = arg5; -X for (s = 0; s < s_nctl; s++) { -X w = getlistitem(v, s); -X if (w == NULL || !is_listobject(w) || -X getlistsize(w) != t_nctl) { -X err_badarg(); -X return NULL; -X } -X for (t = 0; t < t_nctl; t++) { -X pt = getlistitem(w, t); -X if (!getidoublearray(pt, 1, 0, ncoords, pnext)) -X return NULL; -X pnext += ncoords; -X } -X } -X s_byte_stride = sizeof(double) * ncoords; -X t_byte_stride = s_byte_stride * s_nctl; -X nurbssurface( arg1 , arg2 , arg3 , arg4 , -X s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 ); -X DEL(arg2); -X DEL(arg4); -X DEL(arg5); -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X long arg1 ; +X double * arg2 ; +X long arg3 ; +X double * arg4 ; +X double *arg5 ; +X long arg6 ; +X long arg7 ; +X long arg8 ; +X long ncoords; +X long s_byte_stride, t_byte_stride; +X long s_nctl, t_nctl; +X long s, t; +X object *v, *w, *pt; +X double *pnext; +X if (!getilongarraysize(args, 6, 0, &arg1)) +X return NULL; +X if ((arg2 = NEW(double, arg1 )) == NULL) { +X return err_nomem(); +X } +X if (!getidoublearray(args, 6, 0, arg1 , arg2)) +X return NULL; +X if (!getilongarraysize(args, 6, 1, &arg3)) +X return NULL; +X if ((arg4 = NEW(double, arg3 )) == NULL) { +X return err_nomem(); +X } +X if (!getidoublearray(args, 6, 1, arg3 , arg4)) +X return NULL; +X if (!getilongarg(args, 6, 3, &arg6)) +X return NULL; +X if (!getilongarg(args, 6, 4, &arg7)) +X return NULL; +X if (!getilongarg(args, 6, 5, &arg8)) +X return NULL; +X if (arg8 == N_XYZ) +X ncoords = 3; +X else if (arg8 == N_XYZW) +X ncoords = 4; +X else { +X err_badarg(); +X return NULL; +X } +X s_nctl = arg1 - arg6; +X t_nctl = arg3 - arg7; +X if (!getiobjectarg(args, 6, 2, &v)) +X return NULL; +X if (!is_listobject(v) || getlistsize(v) != s_nctl) { +X err_badarg(); +X return NULL; +X } +X if ((arg5 = NEW(double, s_nctl*t_nctl*ncoords )) == NULL) { +X return err_nomem(); +X } +X pnext = arg5; +X for (s = 0; s < s_nctl; s++) { +X w = getlistitem(v, s); +X if (w == NULL || !is_listobject(w) || +X getlistsize(w) != t_nctl) { +X err_badarg(); +X return NULL; +X } +X for (t = 0; t < t_nctl; t++) { +X pt = getlistitem(w, t); +X if (!getidoublearray(pt, 1, 0, ncoords, pnext)) +X return NULL; +X pnext += ncoords; +X } +X } +X s_byte_stride = sizeof(double) * ncoords; +X t_byte_stride = s_byte_stride * s_nctl; +X nurbssurface( arg1 , arg2 , arg3 , arg4 , +X s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 ); +X DEL(arg2); +X DEL(arg4); +X DEL(arg5); +X INCREF(None); +X return None; X} X X/* nurbscurve(knots, ctlpoints, order, type). -X The length of ctlpoints is len(knots)-order. */ +X The length of ctlpoints is len(knots)-order. */ X X%nurbscurve X Xstatic object * Xgl_nurbscurve(self, args) -X object *self; -X object *args; -X{ -X long arg1 ; -X double * arg2 ; -X long arg3 ; -X double * arg4 ; -X long arg5 ; -X long arg6 ; -X int ncoords, npoints; -X int i; -X object *v; -X double *pnext; -X if (!getilongarraysize(args, 4, 0, &arg1)) -X return NULL; -X if ((arg2 = NEW(double, arg1 )) == NULL) { -X return err_nomem(); -X } -X if (!getidoublearray(args, 4, 0, arg1 , arg2)) -X return NULL; -X if (!getilongarg(args, 4, 2, &arg5)) -X return NULL; -X if (!getilongarg(args, 4, 3, &arg6)) -X return NULL; -X if (arg6 == N_ST) -X ncoords = 2; -X else if (arg6 == N_STW) -X ncoords = 3; -X else { -X err_badarg(); -X return NULL; -X } -X npoints = arg1 - arg5; -X if (!getiobjectarg(args, 4, 1, &v)) -X return NULL; -X if (!is_listobject(v) || getlistsize(v) != npoints) { -X err_badarg(); -X return NULL; -X } -X if ((arg4 = NEW(double, npoints*ncoords )) == NULL) { -X return err_nomem(); -X } -X pnext = arg4; -X for (i = 0; i < npoints; i++) { -X if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) -X return NULL; -X pnext += ncoords; -X } -X arg3 = (sizeof(double)) * ncoords; -X nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 ); -X DEL(arg2); -X DEL(arg4); -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X long arg1 ; +X double * arg2 ; +X long arg3 ; +X double * arg4 ; +X long arg5 ; +X long arg6 ; +X int ncoords, npoints; +X int i; +X object *v; +X double *pnext; +X if (!getilongarraysize(args, 4, 0, &arg1)) +X return NULL; +X if ((arg2 = NEW(double, arg1 )) == NULL) { +X return err_nomem(); +X } +X if (!getidoublearray(args, 4, 0, arg1 , arg2)) +X return NULL; +X if (!getilongarg(args, 4, 2, &arg5)) +X return NULL; +X if (!getilongarg(args, 4, 3, &arg6)) +X return NULL; +X if (arg6 == N_ST) +X ncoords = 2; +X else if (arg6 == N_STW) +X ncoords = 3; +X else { +X err_badarg(); +X return NULL; +X } +X npoints = arg1 - arg5; +X if (!getiobjectarg(args, 4, 1, &v)) +X return NULL; +X if (!is_listobject(v) || getlistsize(v) != npoints) { +X err_badarg(); +X return NULL; +X } +X if ((arg4 = NEW(double, npoints*ncoords )) == NULL) { +X return err_nomem(); +X } +X pnext = arg4; +X for (i = 0; i < npoints; i++) { +X if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) +X return NULL; +X pnext += ncoords; +X } +X arg3 = (sizeof(double)) * ncoords; +X nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 ); +X DEL(arg2); +X DEL(arg4); +X INCREF(None); +X return None; X} X X/* pwlcurve(points, type). -X Points is a list of points. Type must be N_ST. */ +X Points is a list of points. Type must be N_ST. */ X X%pwlcurve X Xstatic object * Xgl_pwlcurve(self, args) -X object *self; -X object *args; -X{ -X object *v; -X long type; -X double *data, *pnext; -X long npoints, ncoords; -X int i; -X if (!getiobjectarg(args, 2, 0, &v)) -X return NULL; -X if (!getilongarg(args, 2, 1, &type)) -X return NULL; -X if (!is_listobject(v)) { -X err_badarg(); -X return NULL; -X } -X npoints = getlistsize(v); -X if (type == N_ST) -X ncoords = 2; -X else { -X err_badarg(); -X return NULL; -X } -X if ((data = NEW(double, npoints*ncoords)) == NULL) { -X return err_nomem(); -X } -X pnext = data; -X for (i = 0; i < npoints; i++) { -X if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) -X return NULL; -X pnext += ncoords; -X } -X pwlcurve(npoints, data, sizeof(double)*ncoords, type); -X DEL(data); -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X object *v; +X long type; +X double *data, *pnext; +X long npoints, ncoords; +X int i; +X if (!getiobjectarg(args, 2, 0, &v)) +X return NULL; +X if (!getilongarg(args, 2, 1, &type)) +X return NULL; +X if (!is_listobject(v)) { +X err_badarg(); +X return NULL; +X } +X npoints = getlistsize(v); +X if (type == N_ST) +X ncoords = 2; +X else { +X err_badarg(); +X return NULL; +X } +X if ((data = NEW(double, npoints*ncoords)) == NULL) { +X return err_nomem(); +X } +X pnext = data; +X for (i = 0; i < npoints; i++) { +X if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) +X return NULL; +X pnext += ncoords; +X } +X pwlcurve(npoints, data, sizeof(double)*ncoords, type); +X DEL(data); +X INCREF(None); +X return None; X} X X @@ -456,63 +456,63 @@ Xstatic long pickbuffersize; X Xstatic object * Xpick_select(args, func) -X object *args; -X void (*func)(); +X object *args; +X void (*func)(); X{ -X if (!getilongarg(args, 1, 0, &pickbuffersize)) -X return NULL; -X if (pickbuffer != NULL) { -X err_setstr(RuntimeError, -X "pick/gselect: already picking/selecting"); -X return NULL; -X } -X if ((pickbuffer = NEW(short, pickbuffersize)) == NULL) { -X return err_nomem(); -X } -X (*func)(pickbuffer, pickbuffersize); -X INCREF(None); -X return None; +X if (!getilongarg(args, 1, 0, &pickbuffersize)) +X return NULL; +X if (pickbuffer != NULL) { +X err_setstr(RuntimeError, +X "pick/gselect: already picking/selecting"); +X return NULL; +X } +X if ((pickbuffer = NEW(short, pickbuffersize)) == NULL) { +X return err_nomem(); +X } +X (*func)(pickbuffer, pickbuffersize); +X INCREF(None); +X return None; X} X Xstatic object * Xendpick_select(args, func) -X object *args; -X long (*func)(); -X{ -X object *v, *w; -X int i, nhits, n; -X if (!getnoarg(args)) -X return NULL; -X if (pickbuffer == NULL) { -X err_setstr(RuntimeError, -X "endpick/endselect: not in pick/select mode"); -X return NULL; -X } -X nhits = (*func)(pickbuffer); -X if (nhits < 0) { -X nhits = -nhits; /* How to report buffer overflow otherwise? */ -X } -X /* Scan the buffer to see how many integers */ -X n = 0; -X for (; nhits > 0; nhits--) { -X n += 1 + pickbuffer[n]; -X } -X v = newlistobject(n); -X if (v == NULL) -X return NULL; -X /* XXX Could do it nicer and interpret the data structure here, -X returning a list of lists. But this can be done in Python... */ -X for (i = 0; i < n; i++) { -X w = newintobject((long)pickbuffer[i]); -X if (w == NULL) { -X DECREF(v); -X return NULL; -X } -X setlistitem(v, i, w); -X } -X DEL(pickbuffer); -X pickbuffer = NULL; -X return v; +X object *args; +X long (*func)(); +X{ +X object *v, *w; +X int i, nhits, n; +X if (!getnoarg(args)) +X return NULL; +X if (pickbuffer == NULL) { +X err_setstr(RuntimeError, +X "endpick/endselect: not in pick/select mode"); +X return NULL; +X } +X nhits = (*func)(pickbuffer); +X if (nhits < 0) { +X nhits = -nhits; /* How to report buffer overflow otherwise? */ +X } +X /* Scan the buffer to see how many integers */ +X n = 0; +X for (; nhits > 0; nhits--) { +X n += 1 + pickbuffer[n]; +X } +X v = newlistobject(n); +X if (v == NULL) +X return NULL; +X /* XXX Could do it nicer and interpret the data structure here, +X returning a list of lists. But this can be done in Python... */ +X for (i = 0; i < n; i++) { +X w = newintobject((long)pickbuffer[i]); +X if (w == NULL) { +X DECREF(v); +X return NULL; +X } +X setlistitem(v, i, w); +X } +X DEL(pickbuffer); +X pickbuffer = NULL; +X return v; X} X Xextern void pick(), gselect(); @@ -520,370 +520,370 @@ Xextern long endpick(), endselect(); X X%pick Xstatic object *gl_pick(self, args) object *self, *args; { -X return pick_select(args, pick); +X return pick_select(args, pick); X} X X%endpick Xstatic object *gl_endpick(self, args) object *self, *args; { -X return endpick_select(args, endpick); +X return endpick_select(args, endpick); X} X X%gselect Xstatic object *gl_gselect(self, args) object *self, *args; { -X return pick_select(args, gselect); +X return pick_select(args, gselect); X} X X%endselect Xstatic object *gl_endselect(self, args) object *self, *args; { -X return endpick_select(args, endselect); +X return endpick_select(args, endselect); X} X X -X/* XXX The generator botches this one. Here's a quick hack to fix it. */ +X/* XXX The generator botches this one. Here's a quick hack to fix it. */ X X% getmatrix float r[16] X Xstatic object * Xgl_getmatrix(self, args) -X object *self; -X object *args; -X{ -X float arg1 [ 16 ] ; -X object *v, *w; -X int i; -X getmatrix( arg1 ); -X v = newlistobject(16); -X if (v == NULL) { -X return err_nomem(); -X } -X for (i = 0; i < 16; i++) { -X w = mknewfloatobject(arg1[i]); -X if (w == NULL) { -X DECREF(v); -X return NULL; -X } -X setlistitem(v, i, w); -X } -X return v; +X object *self; +X object *args; +X{ +X float arg1 [ 16 ] ; +X object *v, *w; +X int i; +X getmatrix( arg1 ); +X v = newlistobject(16); +X if (v == NULL) { +X return err_nomem(); +X } +X for (i = 0; i < 16; i++) { +X w = mknewfloatobject(arg1[i]); +X if (w == NULL) { +X DECREF(v); +X return NULL; +X } +X setlistitem(v, i, w); +X } +X return v; X} X X/* End of manually written stubs */ X X%% X -Xlong getshade -Xvoid devport short s long s -Xvoid rdr2i long s long s -Xvoid rectfs short s short s short s short s -Xvoid rects short s short s short s short s -Xvoid rmv2i long s long s -Xvoid noport -Xvoid popviewport -Xvoid clear -Xvoid clearhitcode -Xvoid closeobj -Xvoid cursoff -Xvoid curson -Xvoid doublebuffer -Xvoid finish -Xvoid gconfig -Xvoid ginit -Xvoid greset -Xvoid multimap -Xvoid onemap -Xvoid popattributes -Xvoid popmatrix -Xvoid pushattributes -Xvoid pushmatrix -Xvoid pushviewport -Xvoid qreset -Xvoid RGBmode -Xvoid singlebuffer -Xvoid swapbuffers -Xvoid gsync -Xvoid tpon -Xvoid tpoff -Xvoid clkon -Xvoid clkoff -Xvoid ringbell -X#void callfunc -Xvoid gbegin -Xvoid textinit -Xvoid initnames -Xvoid pclos -Xvoid popname -Xvoid spclos -Xvoid zclear -Xvoid screenspace -Xvoid reshapeviewport -Xvoid winpush -Xvoid winpop -Xvoid foreground -Xvoid endfullscrn -Xvoid endpupmode -Xvoid fullscrn -Xvoid pupmode -Xvoid winconstraints -Xvoid pagecolor short s -Xvoid textcolor short s -Xvoid color short s -Xvoid curveit short s -Xvoid font short s -Xvoid linewidth short s -Xvoid setlinestyle short s -Xvoid setmap short s -Xvoid swapinterval short s -Xvoid writemask short s -Xvoid textwritemask short s -Xvoid qdevice short s -Xvoid unqdevice short s -Xvoid curvebasis short s -Xvoid curveprecision short s -Xvoid loadname short s -Xvoid passthrough short s -Xvoid pushname short s -Xvoid setmonitor short s -Xvoid setshade short s -Xvoid setpattern short s -Xvoid pagewritemask short s +Xlong getshade +Xvoid devport short s long s +Xvoid rdr2i long s long s +Xvoid rectfs short s short s short s short s +Xvoid rects short s short s short s short s +Xvoid rmv2i long s long s +Xvoid noport +Xvoid popviewport +Xvoid clear +Xvoid clearhitcode +Xvoid closeobj +Xvoid cursoff +Xvoid curson +Xvoid doublebuffer +Xvoid finish +Xvoid gconfig +Xvoid ginit +Xvoid greset +Xvoid multimap +Xvoid onemap +Xvoid popattributes +Xvoid popmatrix +Xvoid pushattributes +Xvoid pushmatrix +Xvoid pushviewport +Xvoid qreset +Xvoid RGBmode +Xvoid singlebuffer +Xvoid swapbuffers +Xvoid gsync +Xvoid tpon +Xvoid tpoff +Xvoid clkon +Xvoid clkoff +Xvoid ringbell +X#void callfunc +Xvoid gbegin +Xvoid textinit +Xvoid initnames +Xvoid pclos +Xvoid popname +Xvoid spclos +Xvoid zclear +Xvoid screenspace +Xvoid reshapeviewport +Xvoid winpush +Xvoid winpop +Xvoid foreground +Xvoid endfullscrn +Xvoid endpupmode +Xvoid fullscrn +Xvoid pupmode +Xvoid winconstraints +Xvoid pagecolor short s +Xvoid textcolor short s +Xvoid color short s +Xvoid curveit short s +Xvoid font short s +Xvoid linewidth short s +Xvoid setlinestyle short s +Xvoid setmap short s +Xvoid swapinterval short s +Xvoid writemask short s +Xvoid textwritemask short s +Xvoid qdevice short s +Xvoid unqdevice short s +Xvoid curvebasis short s +Xvoid curveprecision short s +Xvoid loadname short s +Xvoid passthrough short s +Xvoid pushname short s +Xvoid setmonitor short s +Xvoid setshade short s +Xvoid setpattern short s +Xvoid pagewritemask short s X# -Xvoid callobj long s -Xvoid delobj long s -Xvoid editobj long s -Xvoid makeobj long s -Xvoid maketag long s -Xvoid chunksize long s -Xvoid compactify long s -Xvoid deltag long s -Xvoid lsrepeat long s -Xvoid objinsert long s -Xvoid objreplace long s -Xvoid winclose long s -Xvoid blanktime long s -Xvoid freepup long s +Xvoid callobj long s +Xvoid delobj long s +Xvoid editobj long s +Xvoid makeobj long s +Xvoid maketag long s +Xvoid chunksize long s +Xvoid compactify long s +Xvoid deltag long s +Xvoid lsrepeat long s +Xvoid objinsert long s +Xvoid objreplace long s +Xvoid winclose long s +Xvoid blanktime long s +Xvoid freepup long s X# This is not in the library!? -X###void pupcolor long s +X###void pupcolor long s X# -Xvoid backbuffer long s -Xvoid frontbuffer long s -Xvoid lsbackup long s -Xvoid resetls long s -Xvoid lampon long s -Xvoid lampoff long s -Xvoid setbell long s -Xvoid blankscreen long s -Xvoid depthcue long s -Xvoid zbuffer long s -Xvoid backface long s +Xvoid backbuffer long s +Xvoid frontbuffer long s +Xvoid lsbackup long s +Xvoid resetls long s +Xvoid lampon long s +Xvoid lampoff long s +Xvoid setbell long s +Xvoid blankscreen long s +Xvoid depthcue long s +Xvoid zbuffer long s +Xvoid backface long s X# -Xvoid cmov2i long s long s -Xvoid draw2i long s long s -Xvoid move2i long s long s -Xvoid pnt2i long s long s -Xvoid patchbasis long s long s -Xvoid patchprecision long s long s -Xvoid pdr2i long s long s -Xvoid pmv2i long s long s -Xvoid rpdr2i long s long s -Xvoid rpmv2i long s long s -Xvoid xfpt2i long s long s -Xvoid objdelete long s long s -Xvoid patchcurves long s long s -Xvoid minsize long s long s -Xvoid maxsize long s long s -Xvoid keepaspect long s long s -Xvoid prefsize long s long s -Xvoid stepunit long s long s -Xvoid fudge long s long s -Xvoid winmove long s long s +Xvoid cmov2i long s long s +Xvoid draw2i long s long s +Xvoid move2i long s long s +Xvoid pnt2i long s long s +Xvoid patchbasis long s long s +Xvoid patchprecision long s long s +Xvoid pdr2i long s long s +Xvoid pmv2i long s long s +Xvoid rpdr2i long s long s +Xvoid rpmv2i long s long s +Xvoid xfpt2i long s long s +Xvoid objdelete long s long s +Xvoid patchcurves long s long s +Xvoid minsize long s long s +Xvoid maxsize long s long s +Xvoid keepaspect long s long s +Xvoid prefsize long s long s +Xvoid stepunit long s long s +Xvoid fudge long s long s +Xvoid winmove long s long s X# -Xvoid attachcursor short s short s -Xvoid deflinestyle short s short s -Xvoid noise short s short s -Xvoid picksize short s short s -Xvoid qenter short s short s -Xvoid setdepth short s short s -Xvoid cmov2s short s short s -Xvoid draw2s short s short s -Xvoid move2s short s short s -Xvoid pdr2s short s short s -Xvoid pmv2s short s short s -Xvoid pnt2s short s short s -Xvoid rdr2s short s short s -Xvoid rmv2s short s short s -Xvoid rpdr2s short s short s -Xvoid rpmv2s short s short s -Xvoid xfpt2s short s short s +Xvoid attachcursor short s short s +Xvoid deflinestyle short s short s +Xvoid noise short s short s +Xvoid picksize short s short s +Xvoid qenter short s short s +Xvoid setdepth short s short s +Xvoid cmov2s short s short s +Xvoid draw2s short s short s +Xvoid move2s short s short s +Xvoid pdr2s short s short s +Xvoid pmv2s short s short s +Xvoid pnt2s short s short s +Xvoid rdr2s short s short s +Xvoid rmv2s short s short s +Xvoid rpdr2s short s short s +Xvoid rpmv2s short s short s +Xvoid xfpt2s short s short s X# -Xvoid cmov2 float s float s -Xvoid draw2 float s float s -Xvoid move2 float s float s -Xvoid pnt2 float s float s -Xvoid pdr2 float s float s -Xvoid pmv2 float s float s -Xvoid rdr2 float s float s -Xvoid rmv2 float s float s -Xvoid rpdr2 float s float s -Xvoid rpmv2 float s float s -Xvoid xfpt2 float s float s +Xvoid cmov2 float s float s +Xvoid draw2 float s float s +Xvoid move2 float s float s +Xvoid pnt2 float s float s +Xvoid pdr2 float s float s +Xvoid pmv2 float s float s +Xvoid rdr2 float s float s +Xvoid rmv2 float s float s +Xvoid rpdr2 float s float s +Xvoid rpmv2 float s float s +Xvoid xfpt2 float s float s X# -Xvoid loadmatrix float s[16] -Xvoid multmatrix float s[16] -Xvoid crv float s[16] -Xvoid rcrv float s[16] +Xvoid loadmatrix float s[16] +Xvoid multmatrix float s[16] +Xvoid crv float s[16] +Xvoid rcrv float s[16] X# -X# Methods that have strings. +X# Methods that have strings. X# -Xvoid addtopup long s char *s long s -Xvoid charstr char *s -Xvoid getport char *s -Xlong strwidth char *s -Xlong winopen char *s -Xvoid wintitle char *s +Xvoid addtopup long s char *s long s +Xvoid charstr char *s +Xvoid getport char *s +Xlong strwidth char *s +Xlong winopen char *s +Xvoid wintitle char *s X# -X# Methods that have 1 long (# of elements) and an array +X# Methods that have 1 long (# of elements) and an array X# -Xvoid polf long s float s[3*arg1] -Xvoid polf2 long s float s[2*arg1] -Xvoid poly long s float s[3*arg1] -Xvoid poly2 long s float s[2*arg1] -Xvoid crvn long s float s[3*arg1] -Xvoid rcrvn long s float s[4*arg1] +Xvoid polf long s float s[3*arg1] +Xvoid polf2 long s float s[2*arg1] +Xvoid poly long s float s[3*arg1] +Xvoid poly2 long s float s[2*arg1] +Xvoid crvn long s float s[3*arg1] +Xvoid rcrvn long s float s[4*arg1] X# -Xvoid polf2i long s long s[2*arg1] -Xvoid polfi long s long s[3*arg1] -Xvoid poly2i long s long s[2*arg1] -Xvoid polyi long s long s[3*arg1] +Xvoid polf2i long s long s[2*arg1] +Xvoid polfi long s long s[3*arg1] +Xvoid poly2i long s long s[2*arg1] +Xvoid polyi long s long s[3*arg1] X# -Xvoid polf2s long s short s[2*arg1] -Xvoid polfs long s short s[3*arg1] -Xvoid polys long s short s[3*arg1] -Xvoid poly2s long s short s[2*arg1] +Xvoid polf2s long s short s[2*arg1] +Xvoid polfs long s short s[3*arg1] +Xvoid polys long s short s[3*arg1] +Xvoid poly2s long s short s[2*arg1] X# -Xvoid defcursor short s short s[16] -Xvoid writepixels short s short s[arg1] -Xvoid defbasis long s float s[16] -Xvoid gewrite short s short s[arg1] +Xvoid defcursor short s short s[16] +Xvoid writepixels short s short s[arg1] +Xvoid defbasis long s float s[16] +Xvoid gewrite short s short s[arg1] X# -Xvoid rotate short s char s +Xvoid rotate short s char s X# This is not in the library!? -X###void setbutton short s char s -Xvoid rot float s char s +X###void setbutton short s char s +Xvoid rot float s char s X# -Xvoid circfi long s long s long s -Xvoid circi long s long s long s -Xvoid cmovi long s long s long s -Xvoid drawi long s long s long s -Xvoid movei long s long s long s -Xvoid pnti long s long s long s -Xvoid newtag long s long s long s -Xvoid pdri long s long s long s -Xvoid pmvi long s long s long s -Xvoid rdri long s long s long s -Xvoid rmvi long s long s long s -Xvoid rpdri long s long s long s -Xvoid rpmvi long s long s long s -Xvoid xfpti long s long s long s +Xvoid circfi long s long s long s +Xvoid circi long s long s long s +Xvoid cmovi long s long s long s +Xvoid drawi long s long s long s +Xvoid movei long s long s long s +Xvoid pnti long s long s long s +Xvoid newtag long s long s long s +Xvoid pdri long s long s long s +Xvoid pmvi long s long s long s +Xvoid rdri long s long s long s +Xvoid rmvi long s long s long s +Xvoid rpdri long s long s long s +Xvoid rpmvi long s long s long s +Xvoid xfpti long s long s long s X# -Xvoid circ float s float s float s -Xvoid circf float s float s float s -Xvoid cmov float s float s float s -Xvoid draw float s float s float s -Xvoid move float s float s float s -Xvoid pnt float s float s float s -Xvoid scale float s float s float s -Xvoid translate float s float s float s -Xvoid pdr float s float s float s -Xvoid pmv float s float s float s -Xvoid rdr float s float s float s -Xvoid rmv float s float s float s -Xvoid rpdr float s float s float s -Xvoid rpmv float s float s float s -Xvoid xfpt float s float s float s +Xvoid circ float s float s float s +Xvoid circf float s float s float s +Xvoid cmov float s float s float s +Xvoid draw float s float s float s +Xvoid move float s float s float s +Xvoid pnt float s float s float s +Xvoid scale float s float s float s +Xvoid translate float s float s float s +Xvoid pdr float s float s float s +Xvoid pmv float s float s float s +Xvoid rdr float s float s float s +Xvoid rmv float s float s float s +Xvoid rpdr float s float s float s +Xvoid rpmv float s float s float s +Xvoid xfpt float s float s float s X# -Xvoid RGBcolor short s short s short s -Xvoid RGBwritemask short s short s short s -Xvoid setcursor short s short s short s -Xvoid tie short s short s short s -Xvoid circfs short s short s short s -Xvoid circs short s short s short s -Xvoid cmovs short s short s short s -Xvoid draws short s short s short s -Xvoid moves short s short s short s -Xvoid pdrs short s short s short s -Xvoid pmvs short s short s short s -Xvoid pnts short s short s short s -Xvoid rdrs short s short s short s -Xvoid rmvs short s short s short s -Xvoid rpdrs short s short s short s -Xvoid rpmvs short s short s short s -Xvoid xfpts short s short s short s -Xvoid curorigin short s short s short s -Xvoid cyclemap short s short s short s +Xvoid RGBcolor short s short s short s +Xvoid RGBwritemask short s short s short s +Xvoid setcursor short s short s short s +Xvoid tie short s short s short s +Xvoid circfs short s short s short s +Xvoid circs short s short s short s +Xvoid cmovs short s short s short s +Xvoid draws short s short s short s +Xvoid moves short s short s short s +Xvoid pdrs short s short s short s +Xvoid pmvs short s short s short s +Xvoid pnts short s short s short s +Xvoid rdrs short s short s short s +Xvoid rmvs short s short s short s +Xvoid rpdrs short s short s short s +Xvoid rpmvs short s short s short s +Xvoid xfpts short s short s short s +Xvoid curorigin short s short s short s +Xvoid cyclemap short s short s short s X# -Xvoid patch float s[16] float s[16] float s[16] -Xvoid splf long s float s[3*arg1] short s[arg1] -Xvoid splf2 long s float s[2*arg1] short s[arg1] -Xvoid splfi long s long s[3*arg1] short s[arg1] -Xvoid splf2i long s long s[2*arg1] short s[arg1] -Xvoid splfs long s short s[3*arg1] short s[arg1] -Xvoid splf2s long s short s[2*arg1] short s[arg1] -Xvoid defpattern short s short s short s[arg2*arg2/16] +Xvoid patch float s[16] float s[16] float s[16] +Xvoid splf long s float s[3*arg1] short s[arg1] +Xvoid splf2 long s float s[2*arg1] short s[arg1] +Xvoid splfi long s long s[3*arg1] short s[arg1] +Xvoid splf2i long s long s[2*arg1] short s[arg1] +Xvoid splfs long s short s[3*arg1] short s[arg1] +Xvoid splf2s long s short s[2*arg1] short s[arg1] +Xvoid defpattern short s short s short s[arg2*arg2/16] X# -Xvoid rpatch float s[16] float s[16] float s[16] float s[16] +Xvoid rpatch float s[16] float s[16] float s[16] float s[16] X# X# routines that send 4 floats X# -Xvoid ortho2 float s float s float s float s -Xvoid rect float s float s float s float s -Xvoid rectf float s float s float s float s -Xvoid xfpt4 float s float s float s float s +Xvoid ortho2 float s float s float s float s +Xvoid rect float s float s float s float s +Xvoid rectf float s float s float s float s +Xvoid xfpt4 float s float s float s float s X# -Xvoid textport short s short s short s short s -Xvoid mapcolor short s short s short s short s -Xvoid scrmask short s short s short s short s -Xvoid setvaluator short s short s short s short s -Xvoid viewport short s short s short s short s -Xvoid shaderange short s short s short s short s -Xvoid xfpt4s short s short s short s short s -Xvoid rectfi long s long s long s long s -Xvoid recti long s long s long s long s -Xvoid xfpt4i long s long s long s long s -Xvoid prefposition long s long s long s long s +Xvoid textport short s short s short s short s +Xvoid mapcolor short s short s short s short s +Xvoid scrmask short s short s short s short s +Xvoid setvaluator short s short s short s short s +Xvoid viewport short s short s short s short s +Xvoid shaderange short s short s short s short s +Xvoid xfpt4s short s short s short s short s +Xvoid rectfi long s long s long s long s +Xvoid recti long s long s long s long s +Xvoid xfpt4i long s long s long s long s +Xvoid prefposition long s long s long s long s X# -Xvoid arc float s float s float s short s short s -Xvoid arcf float s float s float s short s short s -Xvoid arcfi long s long s long s short s short s -Xvoid arci long s long s long s short s short s +Xvoid arc float s float s float s short s short s +Xvoid arcf float s float s float s short s short s +Xvoid arcfi long s long s long s short s short s +Xvoid arci long s long s long s short s short s X# -Xvoid bbox2 short s short s float s float s float s float s -Xvoid bbox2i short s short s long s long s long s long s -Xvoid bbox2s short s short s short s short s short s short s -Xvoid blink short s short s short s short s short s -Xvoid ortho float s float s float s float s float s float s -Xvoid window float s float s float s float s float s float s -Xvoid lookat float s float s float s float s float s float s short s +Xvoid bbox2 short s short s float s float s float s float s +Xvoid bbox2i short s short s long s long s long s long s +Xvoid bbox2s short s short s short s short s short s short s +Xvoid blink short s short s short s short s short s +Xvoid ortho float s float s float s float s float s float s +Xvoid window float s float s float s float s float s float s +Xvoid lookat float s float s float s float s float s float s short s X# -Xvoid perspective short s float s float s float s -Xvoid polarview float s short s short s short s +Xvoid perspective short s float s float s float s +Xvoid polarview float s short s short s short s X# XXX getichararray not supported -X#void writeRGB short s char s[arg1] char s[arg1] char s[arg1] +X#void writeRGB short s char s[arg1] char s[arg1] char s[arg1] X# -Xvoid arcfs short s short s short s short s short s -Xvoid arcs short s short s short s short s short s -Xvoid rectcopy short s short s short s short s short s short s -Xvoid RGBcursor short s short s short s short s short s short s short s +Xvoid arcfs short s short s short s short s short s +Xvoid arcs short s short s short s short s short s +Xvoid rectcopy short s short s short s short s short s short s +Xvoid RGBcursor short s short s short s short s short s short s short s X# -Xlong getbutton short s +Xlong getbutton short s Xlong getcmmode Xlong getlsbackup Xlong getresetls Xlong getdcm Xlong getzbuffer Xlong ismex -Xlong isobj long s -Xlong isqueued short s -Xlong istag long s +Xlong isobj long s +Xlong isqueued short s +Xlong istag long s X# Xlong genobj Xlong gentag @@ -908,60 +908,60 @@ Xlong winattach Xlong getothermonitor Xlong newpup X# -Xlong getvaluator short s -Xvoid winset long s -Xlong dopup long s -Xvoid getdepth short r short r -Xvoid getcpos short r short r -Xvoid getsize long r long r -Xvoid getorigin long r long r -Xvoid getviewport short r short r short r short r -Xvoid gettp short r short r short r short r -Xvoid getgpos float r float r float r float r -Xvoid winposition long s long s long s long s -Xvoid gRGBcolor short r short r short r -Xvoid gRGBmask short r short r short r -Xvoid getscrmask short r short r short r short r -Xvoid gRGBcursor short r short r short r short r short r short r short r short r long * -Xvoid getmcolor short s short r short r short r -Xvoid mapw long s short s short s float r float r float r float r float r float r -Xvoid mapw2 long s short s short s float r float r -Xvoid defrasterfont short s short s short s Fontchar s[arg3] short s short s[4*arg5] -Xlong qread short r -Xvoid getcursor short r short r short r long r +Xlong getvaluator short s +Xvoid winset long s +Xlong dopup long s +Xvoid getdepth short r short r +Xvoid getcpos short r short r +Xvoid getsize long r long r +Xvoid getorigin long r long r +Xvoid getviewport short r short r short r short r +Xvoid gettp short r short r short r short r +Xvoid getgpos float r float r float r float r +Xvoid winposition long s long s long s long s +Xvoid gRGBcolor short r short r short r +Xvoid gRGBmask short r short r short r +Xvoid getscrmask short r short r short r short r +Xvoid gRGBcursor short r short r short r short r short r short r short r short r long * +Xvoid getmcolor short s short r short r short r +Xvoid mapw long s short s short s float r float r float r float r float r float r +Xvoid mapw2 long s short s short s float r float r +Xvoid defrasterfont short s short s short s Fontchar s[arg3] short s short s[4*arg5] +Xlong qread short r +Xvoid getcursor short r short r short r long r X# -X# For these we receive arrays of stuff +X# For these we receive arrays of stuff X# -Xvoid getdev long s short s[arg1] short r[arg1] +Xvoid getdev long s short s[arg1] short r[arg1] X#XXX not generated correctly yet -X#void getmatrix float r[16] -Xlong readpixels short s short r[retval] -Xlong readRGB short s char r[retval] char r[retval] char r[retval] -Xlong blkqread short s short r[arg1] +X#void getmatrix float r[16] +Xlong readpixels short s short r[retval] +Xlong readRGB short s char r[retval] char r[retval] char r[retval] +Xlong blkqread short s short r[arg1] X# -X# New 4D routines +X# New 4D routines X# Xvoid cmode -Xvoid concave long s -Xvoid curstype long s -Xvoid drawmode long s -Xvoid gammaramp short s[256] short s[256] short s[256] +Xvoid concave long s +Xvoid curstype long s +Xvoid drawmode long s +Xvoid gammaramp short s[256] short s[256] short s[256] Xlong getbackface Xlong getdescender Xlong getdrawmode Xlong getmmode Xlong getsm -Xlong getvideo long s +Xlong getvideo long s Xvoid imakebackground -Xvoid lmbind short s short s -Xvoid lmdef long s long s long s float s[arg3] -Xvoid mmode long s -Xvoid normal float s[3] -Xvoid overlay long s -Xvoid RGBrange short s short s short s short s short s short s short s short s -Xvoid setvideo long s long s -Xvoid shademodel long s -Xvoid underlay long s +Xvoid lmbind short s short s +Xvoid lmdef long s long s long s float s[arg3] +Xvoid mmode long s +Xvoid normal float s[3] +Xvoid overlay long s +Xvoid RGBrange short s short s short s short s short s short s short s short s +Xvoid setvideo long s long s +Xvoid shademodel long s +Xvoid underlay long s X# X# New Personal Iris/GT Routines X# @@ -979,72 +979,72 @@ Xvoid endpolygon Xvoid endsurface Xvoid endtmesh Xvoid endtrim -Xvoid blendfunction long s long s -Xvoid c3f float s[3] -Xvoid c3i long s[3] -Xvoid c3s short s[3] -Xvoid c4f float s[4] -Xvoid c4i long s[4] -Xvoid c4s short s[4] -Xvoid colorf float s -Xvoid cpack long s -Xvoid czclear long s long s -Xvoid dglclose long s -Xlong dglopen char *s long s -Xlong getgdesc long s -Xvoid getnurbsproperty long s float r -Xvoid glcompat long s long s -Xvoid iconsize long s long s -Xvoid icontitle char *s -Xvoid lRGBrange short s short s short s short s short s short s long s long s -Xvoid linesmooth long s -Xvoid lmcolor long s -Xvoid logicop long s -Xlong lrectread short s short s short s short s long r[retval] -Xvoid lrectwrite short s short s short s short s long s[(arg2-arg1+1)*(arg4-arg3+1)] -Xlong rectread short s short s short s short s short r[retval] -Xvoid rectwrite short s short s short s short s short s[(arg2-arg1+1)*(arg4-arg3+1)] -Xvoid lsetdepth long s long s -Xvoid lshaderange short s short s long s long s -Xvoid n3f float s[3] +Xvoid blendfunction long s long s +Xvoid c3f float s[3] +Xvoid c3i long s[3] +Xvoid c3s short s[3] +Xvoid c4f float s[4] +Xvoid c4i long s[4] +Xvoid c4s short s[4] +Xvoid colorf float s +Xvoid cpack long s +Xvoid czclear long s long s +Xvoid dglclose long s +Xlong dglopen char *s long s +Xlong getgdesc long s +Xvoid getnurbsproperty long s float r +Xvoid glcompat long s long s +Xvoid iconsize long s long s +Xvoid icontitle char *s +Xvoid lRGBrange short s short s short s short s short s short s long s long s +Xvoid linesmooth long s +Xvoid lmcolor long s +Xvoid logicop long s +Xlong lrectread short s short s short s short s long r[retval] +Xvoid lrectwrite short s short s short s short s long s[(arg2-arg1+1)*(arg4-arg3+1)] +Xlong rectread short s short s short s short s short r[retval] +Xvoid rectwrite short s short s short s short s short s[(arg2-arg1+1)*(arg4-arg3+1)] +Xvoid lsetdepth long s long s +Xvoid lshaderange short s short s long s long s +Xvoid n3f float s[3] Xvoid noborder -Xvoid pntsmooth long s -Xvoid readsource long s -Xvoid rectzoom float s float s -Xvoid sbox float s float s float s float s -Xvoid sboxi long s long s long s long s -Xvoid sboxs short s short s short s short s -Xvoid sboxf float s float s float s float s -Xvoid sboxfi long s long s long s long s -Xvoid sboxfs short s short s short s short s -Xvoid setnurbsproperty long s float s -Xvoid setpup long s long s long s -Xvoid smoothline long s -Xvoid subpixel long s +Xvoid pntsmooth long s +Xvoid readsource long s +Xvoid rectzoom float s float s +Xvoid sbox float s float s float s float s +Xvoid sboxi long s long s long s long s +Xvoid sboxs short s short s short s short s +Xvoid sboxf float s float s float s float s +Xvoid sboxfi long s long s long s long s +Xvoid sboxfs short s short s short s short s +Xvoid setnurbsproperty long s float s +Xvoid setpup long s long s long s +Xvoid smoothline long s +Xvoid subpixel long s Xvoid swaptmesh -Xlong swinopen long s -Xvoid v2f float s[2] -Xvoid v2i long s[2] -Xvoid v2s short s[2] -Xvoid v3f float s[3] -Xvoid v3i long s[3] -Xvoid v3s short s[3] -Xvoid v4f float s[4] -Xvoid v4i long s[4] -Xvoid v4s short s[4] -Xvoid videocmd long s -Xlong windepth long s -Xvoid wmpack long s -Xvoid zdraw long s -Xvoid zfunction long s -Xvoid zsource long s -Xvoid zwritemask long s +Xlong swinopen long s +Xvoid v2f float s[2] +Xvoid v2i long s[2] +Xvoid v2s short s[2] +Xvoid v3f float s[3] +Xvoid v3i long s[3] +Xvoid v3s short s[3] +Xvoid v4f float s[4] +Xvoid v4i long s[4] +Xvoid v4s short s[4] +Xvoid videocmd long s +Xlong windepth long s +Xvoid wmpack long s +Xvoid zdraw long s +Xvoid zfunction long s +Xvoid zsource long s +Xvoid zwritemask long s X# -X# uses doubles +X# uses doubles X# -Xvoid v2d double s[2] -Xvoid v3d double s[3] -Xvoid v4d double s[4] +Xvoid v2d double s[2] +Xvoid v3d double s[3] +Xvoid v4d double s[4] EOF fi if test -s 'src/stdwinmodule.c' @@ -1056,12 +1056,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1079,41 +1079,41 @@ X X/* Stdwin module */ X X/* Stdwin itself is a module, not a separate object type. -X Object types defined here: -X wp: a window -X dp: a drawing structure (only one can exist at a time) -X mp: a menu -X tp: a textedit block +X Object types defined here: +X wp: a window +X dp: a drawing structure (only one can exist at a time) +X mp: a menu +X tp: a textedit block X*/ X X/* Rules for translating C stdwin function calls into Python stwin: -X - All names drop their initial letter 'w' -X - Functions with a window as first parameter are methods of window objects -X - There is no equivalent for wclose(); just delete the window object -X (all references to it!) (XXX maybe this is a bad idea) -X - w.begindrawing() returns a drawing object -X - There is no equivalent for wenddrawing(win); just delete the drawing -X object (all references to it!) (XXX maybe this is a bad idea) -X - Functions that may only be used inside wbegindrawing / wendddrawing -X are methods of the drawing object; this includes the text measurement -X functions (which however have doubles as module functions). -X - Methods of the drawing object drop an initial 'draw' from their name -X if they have it, e.g., wdrawline() --> d.line() -X - The obvious type conversions: int --> intobject; string --> stringobject -X - A text parameter followed by a length parameter is only a text (string) -X parameter in Python -X - A point or other pair of horizontal and vertical coordinates is always -X a pair of integers in Python -X - Two points forming a rectangle or endpoints of a line segment are a -X pair of points in Python -X - The arguments to d.elarc() are three points. -X - The functions wgetclip() and wsetclip() are translated into -X stdwin.getcutbuffer() and stdwin.setcutbuffer(); 'clip' is really -X a bad word for what these functions do (clipping has a different -X meaning in the drawing world), while cutbuffer is standard X jargon. -X XXX This must change again in the light of changes to stdwin! -X - For textedit, similar rules hold, but they are less strict. -X XXX more? +X - All names drop their initial letter 'w' +X - Functions with a window as first parameter are methods of window objects +X - There is no equivalent for wclose(); just delete the window object +X (all references to it!) (XXX maybe this is a bad idea) +X - w.begindrawing() returns a drawing object +X - There is no equivalent for wenddrawing(win); just delete the drawing +X object (all references to it!) (XXX maybe this is a bad idea) +X - Functions that may only be used inside wbegindrawing / wendddrawing +X are methods of the drawing object; this includes the text measurement +X functions (which however have doubles as module functions). +X - Methods of the drawing object drop an initial 'draw' from their name +X if they have it, e.g., wdrawline() --> d.line() +X - The obvious type conversions: int --> intobject; string --> stringobject +X - A text parameter followed by a length parameter is only a text (string) +X parameter in Python +X - A point or other pair of horizontal and vertical coordinates is always +X a pair of integers in Python +X - Two points forming a rectangle or endpoints of a line segment are a +X pair of points in Python +X - The arguments to d.elarc() are three points. +X - The functions wgetclip() and wsetclip() are translated into +X stdwin.getcutbuffer() and stdwin.setcutbuffer(); 'clip' is really +X a bad word for what these functions do (clipping has a different +X meaning in the drawing world), while cutbuffer is standard X jargon. +X XXX This must change again in the light of changes to stdwin! +X - For textedit, similar rules hold, but they are less strict. +X XXX more? X*/ X X#include "allobjects.h" @@ -1125,24 +1125,24 @@ X X/* Window and menu object types declared here because of forward references */ X Xtypedef struct { -X OB_HEAD -X object *w_title; -X WINDOW *w_win; -X object *w_attr; /* Attributes dictionary */ +X OB_HEAD +X object *w_title; +X WINDOW *w_win; +X object *w_attr; /* Attributes dictionary */ X} windowobject; X -Xextern typeobject Windowtype; /* Really static, forward */ +Xextern typeobject Windowtype; /* Really static, forward */ X X#define is_windowobject(wp) ((wp)->ob_type == &Windowtype) X Xtypedef struct { -X OB_HEAD -X MENU *m_menu; -X int m_id; -X object *m_attr; /* Attributes dictionary */ +X OB_HEAD +X MENU *m_menu; +X int m_id; +X object *m_attr; /* Attributes dictionary */ X} menuobject; X -Xextern typeobject Menutype; /* Really static, forward */ +Xextern typeobject Menutype; /* Really static, forward */ X X#define is_menuobject(mp) ((mp)->ob_type == &Menutype) X @@ -1151,77 +1151,77 @@ X/* Strongly stdwin-specific argument handlers */ X Xstatic int Xgetmousedetail(v, ep) -X object *v; -X EVENT *ep; +X object *v; +X EVENT *ep; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 4) -X return err_badarg(); -X return getintintarg(gettupleitem(v, 0), -X &ep->u.where.h, &ep->u.where.v) && -X getintarg(gettupleitem(v, 1), &ep->u.where.clicks) && -X getintarg(gettupleitem(v, 2), &ep->u.where.button) && -X getintarg(gettupleitem(v, 3), &ep->u.where.mask); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 4) +X return err_badarg(); +X return getintintarg(gettupleitem(v, 0), +X &ep->u.where.h, &ep->u.where.v) && +X getintarg(gettupleitem(v, 1), &ep->u.where.clicks) && +X getintarg(gettupleitem(v, 2), &ep->u.where.button) && +X getintarg(gettupleitem(v, 3), &ep->u.where.mask); X} X Xstatic int Xgetmenudetail(v, ep) -X object *v; -X EVENT *ep; +X object *v; +X EVENT *ep; X{ -X object *mp; -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) -X return err_badarg(); -X mp = gettupleitem(v, 0); -X if (mp == NULL || !is_menuobject(mp)) -X return err_badarg(); -X ep->u.m.id = ((menuobject *)mp) -> m_id; -X return getintarg(gettupleitem(v, 1), &ep->u.m.item); +X object *mp; +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) +X return err_badarg(); +X mp = gettupleitem(v, 0); +X if (mp == NULL || !is_menuobject(mp)) +X return err_badarg(); +X ep->u.m.id = ((menuobject *)mp) -> m_id; +X return getintarg(gettupleitem(v, 1), &ep->u.m.item); X} X Xstatic int Xgeteventarg(v, ep) -X object *v; -X EVENT *ep; -X{ -X object *wp, *detail; -X int a[4]; -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) -X return err_badarg(); -X if (!getintarg(gettupleitem(v, 0), &ep->type)) -X return 0; -X wp = gettupleitem(v, 1); -X if (wp == None) -X ep->window = NULL; -X else if (wp == NULL || !is_windowobject(wp)) -X return err_badarg(); -X else -X ep->window = ((windowobject *)wp) -> w_win; -X detail = gettupleitem(v, 2); -X switch (ep->type) { -X case WE_CHAR: -X if (!is_stringobject(detail) || getstringsize(detail) != 1) -X return err_badarg(); -X ep->u.character = getstringvalue(detail)[0]; -X return 1; -X case WE_COMMAND: -X return getintarg(detail, &ep->u.command); -X case WE_DRAW: -X if (!getrectarg(detail, a)) -X return 0; -X ep->u.area.left = a[0]; -X ep->u.area.top = a[1]; -X ep->u.area.right = a[2]; -X ep->u.area.bottom = a[3]; -X return 1; -X case WE_MOUSE_DOWN: -X case WE_MOUSE_UP: -X case WE_MOUSE_MOVE: -X return getmousedetail(detail, ep); -X case WE_MENU: -X return getmenudetail(detail, ep); -X default: -X return 1; -X } +X object *v; +X EVENT *ep; +X{ +X object *wp, *detail; +X int a[4]; +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) +X return err_badarg(); +X if (!getintarg(gettupleitem(v, 0), &ep->type)) +X return 0; +X wp = gettupleitem(v, 1); +X if (wp == None) +X ep->window = NULL; +X else if (wp == NULL || !is_windowobject(wp)) +X return err_badarg(); +X else +X ep->window = ((windowobject *)wp) -> w_win; +X detail = gettupleitem(v, 2); +X switch (ep->type) { +X case WE_CHAR: +X if (!is_stringobject(detail) || getstringsize(detail) != 1) +X return err_badarg(); +X ep->u.character = getstringvalue(detail)[0]; +X return 1; +X case WE_COMMAND: +X return getintarg(detail, &ep->u.command); +X case WE_DRAW: +X if (!getrectarg(detail, a)) +X return 0; +X ep->u.area.left = a[0]; +X ep->u.area.top = a[1]; +X ep->u.area.right = a[2]; +X ep->u.area.bottom = a[3]; +X return 1; +X case WE_MOUSE_DOWN: +X case WE_MOUSE_UP: +X case WE_MOUSE_MOVE: +X return getmousedetail(detail, ep); +X case WE_MENU: +X return getmenudetail(detail, ep); +X default: +X return 1; +X } X} X X @@ -1229,87 +1229,87 @@ X/* Return construction tools */ X Xstatic object * Xmakepoint(a, b) -X int a, b; +X int a, b; X{ -X object *v; -X object *w; -X if ((v = newtupleobject(2)) == NULL) -X return NULL; -X if ((w = newintobject((long)a)) == NULL || -X settupleitem(v, 0, w) != 0 || -X (w = newintobject((long)b)) == NULL || -X settupleitem(v, 1, w) != 0) { -X DECREF(v); -X return NULL; -X } -X return v; +X object *v; +X object *w; +X if ((v = newtupleobject(2)) == NULL) +X return NULL; +X if ((w = newintobject((long)a)) == NULL || +X settupleitem(v, 0, w) != 0 || +X (w = newintobject((long)b)) == NULL || +X settupleitem(v, 1, w) != 0) { +X DECREF(v); +X return NULL; +X } +X return v; X} X Xstatic object * Xmakerect(a, b, c, d) -X int a, b, c, d; +X int a, b, c, d; X{ -X object *v; -X object *w; -X if ((v = newtupleobject(2)) == NULL) -X return NULL; -X if ((w = makepoint(a, b)) == NULL || -X settupleitem(v, 0, w) != 0 || -X (w = makepoint(c, d)) == NULL || -X settupleitem(v, 1, w) != 0) { -X DECREF(v); -X return NULL; -X } -X return v; +X object *v; +X object *w; +X if ((v = newtupleobject(2)) == NULL) +X return NULL; +X if ((w = makepoint(a, b)) == NULL || +X settupleitem(v, 0, w) != 0 || +X (w = makepoint(c, d)) == NULL || +X settupleitem(v, 1, w) != 0) { +X DECREF(v); +X return NULL; +X } +X return v; X} X Xstatic object * Xmakemouse(hor, ver, clicks, button, mask) -X int hor, ver, clicks, button, mask; -X{ -X object *v; -X object *w; -X if ((v = newtupleobject(4)) == NULL) -X return NULL; -X if ((w = makepoint(hor, ver)) == NULL || -X settupleitem(v, 0, w) != 0 || -X (w = newintobject((long)clicks)) == NULL || -X settupleitem(v, 1, w) != 0 || -X (w = newintobject((long)button)) == NULL || -X settupleitem(v, 2, w) != 0 || -X (w = newintobject((long)mask)) == NULL || -X settupleitem(v, 3, w) != 0) { -X DECREF(v); -X return NULL; -X } -X return v; +X int hor, ver, clicks, button, mask; +X{ +X object *v; +X object *w; +X if ((v = newtupleobject(4)) == NULL) +X return NULL; +X if ((w = makepoint(hor, ver)) == NULL || +X settupleitem(v, 0, w) != 0 || +X (w = newintobject((long)clicks)) == NULL || +X settupleitem(v, 1, w) != 0 || +X (w = newintobject((long)button)) == NULL || +X settupleitem(v, 2, w) != 0 || +X (w = newintobject((long)mask)) == NULL || +X settupleitem(v, 3, w) != 0) { +X DECREF(v); +X return NULL; +X } +X return v; X} X Xstatic object * Xmakemenu(mp, item) -X object *mp; -X int item; +X object *mp; +X int item; X{ -X object *v; -X object *w; -X if ((v = newtupleobject(2)) == NULL) -X return NULL; -X INCREF(mp); -X if (settupleitem(v, 0, mp) != 0 || -X (w = newintobject((long)item)) == NULL || -X settupleitem(v, 1, w) != 0) { -X DECREF(v); -X return NULL; -X } -X return v; +X object *v; +X object *w; +X if ((v = newtupleobject(2)) == NULL) +X return NULL; +X INCREF(mp); +X if (settupleitem(v, 0, mp) != 0 || +X (w = newintobject((long)item)) == NULL || +X settupleitem(v, 1, w) != 0) { +X DECREF(v); +X return NULL; +X } +X return v; X} X X X/* Drawing objects */ X Xtypedef struct { -X OB_HEAD -X windowobject *d_ref; +X OB_HEAD +X windowobject *d_ref; X} drawingobject; X Xstatic drawingobject *Drawing; /* Set to current drawing object, or NULL */ @@ -1318,688 +1318,688 @@ X/* Drawing methods */ X Xstatic void Xdrawing_dealloc(dp) -X drawingobject *dp; +X drawingobject *dp; X{ -X wenddrawing(dp->d_ref->w_win); -X Drawing = NULL; -X DECREF(dp->d_ref); -X free((char *)dp); +X wenddrawing(dp->d_ref->w_win); +X Drawing = NULL; +X DECREF(dp->d_ref); +X free((char *)dp); X} X Xstatic object * Xdrawing_generic(dp, args, func) -X drawingobject *dp; -X object *args; -X void (*func) FPROTO((int, int, int, int)); +X drawingobject *dp; +X object *args; +X void (*func) FPROTO((int, int, int, int)); X{ -X int a[4]; -X if (!getrectarg(args, a)) -X return NULL; -X (*func)(a[0], a[1], a[2], a[3]); -X INCREF(None); -X return None; +X int a[4]; +X if (!getrectarg(args, a)) +X return NULL; +X (*func)(a[0], a[1], a[2], a[3]); +X INCREF(None); +X return None; X} X Xstatic object * Xdrawing_line(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X drawing_generic(dp, args, wdrawline); +X drawing_generic(dp, args, wdrawline); X} X Xstatic object * Xdrawing_xorline(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X drawing_generic(dp, args, wxorline); +X drawing_generic(dp, args, wxorline); X} X Xstatic object * Xdrawing_circle(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X int a[3]; -X if (!getpointintarg(args, a)) -X return NULL; -X wdrawcircle(a[0], a[1], a[2]); -X INCREF(None); -X return None; +X int a[3]; +X if (!getpointintarg(args, a)) +X return NULL; +X wdrawcircle(a[0], a[1], a[2]); +X INCREF(None); +X return None; X} X Xstatic object * Xdrawing_elarc(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X int a[6]; -X if (!get3pointarg(args, a)) -X return NULL; -X wdrawelarc(a[0], a[1], a[2], a[3], a[4], a[5]); -X INCREF(None); -X return None; +X int a[6]; +X if (!get3pointarg(args, a)) +X return NULL; +X wdrawelarc(a[0], a[1], a[2], a[3], a[4], a[5]); +X INCREF(None); +X return None; X} X Xstatic object * Xdrawing_box(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X drawing_generic(dp, args, wdrawbox); +X drawing_generic(dp, args, wdrawbox); X} X Xstatic object * Xdrawing_erase(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X drawing_generic(dp, args, werase); +X drawing_generic(dp, args, werase); X} X Xstatic object * Xdrawing_paint(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X drawing_generic(dp, args, wpaint); +X drawing_generic(dp, args, wpaint); X} X Xstatic object * Xdrawing_invert(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X drawing_generic(dp, args, winvert); +X drawing_generic(dp, args, winvert); X} X Xstatic object * Xdrawing_cliprect(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X drawing_generic(dp, args, wcliprect); +X drawing_generic(dp, args, wcliprect); X} X Xstatic object * Xdrawing_noclip(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X wnoclip(); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X wnoclip(); +X INCREF(None); +X return None; X} X Xstatic object * Xdrawing_shade(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X int a[5]; -X if (!getrectintarg(args, a)) -X return NULL; -X wshade(a[0], a[1], a[2], a[3], a[4]); -X INCREF(None); -X return None; +X int a[5]; +X if (!getrectintarg(args, a)) +X return NULL; +X wshade(a[0], a[1], a[2], a[3], a[4]); +X INCREF(None); +X return None; X} X Xstatic object * Xdrawing_text(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X int a[2]; -X object *s; -X if (!getpointstrarg(args, a, &s)) -X return NULL; -X wdrawtext(a[0], a[1], getstringvalue(s), (int)getstringsize(s)); -X INCREF(None); -X return None; +X int a[2]; +X object *s; +X if (!getpointstrarg(args, a, &s)) +X return NULL; +X wdrawtext(a[0], a[1], getstringvalue(s), (int)getstringsize(s)); +X INCREF(None); +X return None; X} X X/* The following four are also used as stdwin functions */ X Xstatic object * Xdrawing_lineheight(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X return newintobject((long)wlineheight()); +X if (!getnoarg(args)) +X return NULL; +X return newintobject((long)wlineheight()); X} X Xstatic object * Xdrawing_baseline(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X return newintobject((long)wbaseline()); +X if (!getnoarg(args)) +X return NULL; +X return newintobject((long)wbaseline()); X} X Xstatic object * Xdrawing_textwidth(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X object *s; -X if (!getstrarg(args, &s)) -X return NULL; -X return newintobject( -X (long)wtextwidth(getstringvalue(s), (int)getstringsize(s))); +X object *s; +X if (!getstrarg(args, &s)) +X return NULL; +X return newintobject( +X (long)wtextwidth(getstringvalue(s), (int)getstringsize(s))); X} X Xstatic object * Xdrawing_textbreak(dp, args) -X drawingobject *dp; -X object *args; +X drawingobject *dp; +X object *args; X{ -X object *s; -X int a; -X if (!getstrintarg(args, &s, &a)) -X return NULL; -X return newintobject( -X (long)wtextbreak(getstringvalue(s), (int)getstringsize(s), a)); +X object *s; +X int a; +X if (!getstrintarg(args, &s, &a)) +X return NULL; +X return newintobject( +X (long)wtextbreak(getstringvalue(s), (int)getstringsize(s), a)); X} X Xstatic struct methodlist drawing_methods[] = { -X {"box", drawing_box}, -X {"circle", drawing_circle}, -X {"cliprect", drawing_cliprect}, -X {"elarc", drawing_elarc}, -X {"erase", drawing_erase}, -X {"invert", drawing_invert}, -X {"line", drawing_line}, -X {"noclip", drawing_noclip}, -X {"paint", drawing_paint}, -X {"shade", drawing_shade}, -X {"text", drawing_text}, -X {"xorline", drawing_xorline}, -X -X /* Text measuring methods: */ -X {"baseline", drawing_baseline}, -X {"lineheight", drawing_lineheight}, -X {"textbreak", drawing_textbreak}, -X {"textwidth", drawing_textwidth}, -X {NULL, NULL} /* sentinel */ +X {"box", drawing_box}, +X {"circle", drawing_circle}, +X {"cliprect", drawing_cliprect}, +X {"elarc", drawing_elarc}, +X {"erase", drawing_erase}, +X {"invert", drawing_invert}, +X {"line", drawing_line}, +X {"noclip", drawing_noclip}, +X {"paint", drawing_paint}, +X {"shade", drawing_shade}, +X {"text", drawing_text}, +X {"xorline", drawing_xorline}, +X +X /* Text measuring methods: */ +X {"baseline", drawing_baseline}, +X {"lineheight", drawing_lineheight}, +X {"textbreak", drawing_textbreak}, +X {"textwidth", drawing_textwidth}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xdrawing_getattr(wp, name) -X drawingobject *wp; -X char *name; +X drawingobject *wp; +X char *name; X{ -X return findmethod(drawing_methods, (object *)wp, name); +X return findmethod(drawing_methods, (object *)wp, name); X} X Xstatic typeobject Drawingtype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "drawing", /*tp_name*/ -X sizeof(drawingobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X drawing_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X drawing_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "drawing", /*tp_name*/ +X sizeof(drawingobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X drawing_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X drawing_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; X X X/* Text(edit) objects */ X Xtypedef struct { -X OB_HEAD -X TEXTEDIT *t_text; -X windowobject *t_ref; -X object *t_attr; /* Attributes dictionary */ +X OB_HEAD +X TEXTEDIT *t_text; +X windowobject *t_ref; +X object *t_attr; /* Attributes dictionary */ X} textobject; X -Xextern typeobject Texttype; /* Really static, forward */ +Xextern typeobject Texttype; /* Really static, forward */ X Xstatic textobject * Xnewtextobject(wp, left, top, right, bottom) -X windowobject *wp; -X int left, top, right, bottom; -X{ -X textobject *tp; -X tp = NEWOBJ(textobject, &Texttype); -X if (tp == NULL) -X return NULL; -X tp->t_attr = NULL; -X INCREF(wp); -X tp->t_ref = wp; -X tp->t_text = tecreate(wp->w_win, left, top, right, bottom); -X if (tp->t_text == NULL) { -X DECREF(tp); -X return (textobject *) err_nomem(); -X } -X return tp; +X windowobject *wp; +X int left, top, right, bottom; +X{ +X textobject *tp; +X tp = NEWOBJ(textobject, &Texttype); +X if (tp == NULL) +X return NULL; +X tp->t_attr = NULL; +X INCREF(wp); +X tp->t_ref = wp; +X tp->t_text = tecreate(wp->w_win, left, top, right, bottom); +X if (tp->t_text == NULL) { +X DECREF(tp); +X return (textobject *) err_nomem(); +X } +X return tp; X} X X/* Text(edit) methods */ X Xstatic void Xtext_dealloc(tp) -X textobject *tp; +X textobject *tp; X{ -X if (tp->t_text != NULL) -X tefree(tp->t_text); -X if (tp->t_attr != NULL) -X DECREF(tp->t_attr); -X DECREF(tp->t_ref); -X DEL(tp); +X if (tp->t_text != NULL) +X tefree(tp->t_text); +X if (tp->t_attr != NULL) +X DECREF(tp->t_attr); +X DECREF(tp->t_ref); +X DEL(tp); X} X Xstatic object * Xtext_arrow(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X int code; -X if (!getintarg(args, &code)) -X return NULL; -X tearrow(self->t_text, code); -X INCREF(None); -X return None; +X int code; +X if (!getintarg(args, &code)) +X return NULL; +X tearrow(self->t_text, code); +X INCREF(None); +X return None; X} X Xstatic object * Xtext_draw(self, args) -X textobject *self; -X object *args; -X{ -X register TEXTEDIT *tp = self->t_text; -X int a[4]; -X int left, top, right, bottom; -X if (!getrectarg(args, a)) -X return NULL; -X if (Drawing != NULL) { -X err_setstr(RuntimeError, "not drawing"); -X return NULL; -X } -X /* Clip to text area and ignore if area is empty */ -X left = tegetleft(tp); -X top = tegettop(tp); -X right = tegetright(tp); -X bottom = tegetbottom(tp); -X if (a[0] < left) a[0] = left; -X if (a[1] < top) a[1] = top; -X if (a[2] > right) a[2] = right; -X if (a[3] > bottom) a[3] = bottom; -X if (a[0] < a[2] && a[1] < a[3]) { -X /* Hide/show focus around draw call; these are undocumented, -X but required here to get the highlighting correct. -X The call to werase is also required for this reason. -X Finally, this forces us to require (above) that we are NOT -X already drawing. */ -X tehidefocus(tp); -X wbegindrawing(self->t_ref->w_win); -X werase(a[0], a[1], a[2], a[3]); -X tedrawnew(tp, a[0], a[1], a[2], a[3]); -X wenddrawing(self->t_ref->w_win); -X teshowfocus(tp); -X } -X INCREF(None); -X return None; +X textobject *self; +X object *args; +X{ +X register TEXTEDIT *tp = self->t_text; +X int a[4]; +X int left, top, right, bottom; +X if (!getrectarg(args, a)) +X return NULL; +X if (Drawing != NULL) { +X err_setstr(RuntimeError, "not drawing"); +X return NULL; +X } +X /* Clip to text area and ignore if area is empty */ +X left = tegetleft(tp); +X top = tegettop(tp); +X right = tegetright(tp); +X bottom = tegetbottom(tp); +X if (a[0] < left) a[0] = left; +X if (a[1] < top) a[1] = top; +X if (a[2] > right) a[2] = right; +X if (a[3] > bottom) a[3] = bottom; +X if (a[0] < a[2] && a[1] < a[3]) { +X /* Hide/show focus around draw call; these are undocumented, +X but required here to get the highlighting correct. +X The call to werase is also required for this reason. +X Finally, this forces us to require (above) that we are NOT +X already drawing. */ +X tehidefocus(tp); +X wbegindrawing(self->t_ref->w_win); +X werase(a[0], a[1], a[2], a[3]); +X tedrawnew(tp, a[0], a[1], a[2], a[3]); +X wenddrawing(self->t_ref->w_win); +X teshowfocus(tp); +X } +X INCREF(None); +X return None; X} X Xstatic object * Xtext_event(self, args) -X textobject *self; -X object *args; -X{ -X register TEXTEDIT *tp = self->t_text; -X EVENT e; -X if (!geteventarg(args, &e)) -X return NULL; -X if (e.type == WE_MOUSE_DOWN) { -X /* Cheat at the margins */ -X int width, height; -X wgetdocsize(e.window, &width, &height); -X if (e.u.where.h < 0 && tegetleft(tp) == 0) -X e.u.where.h = 0; -X else if (e.u.where.h > width && tegetright(tp) == width) -X e.u.where.h = width; -X if (e.u.where.v < 0 && tegettop(tp) == 0) -X e.u.where.v = 0; -X else if (e.u.where.v > height && tegetright(tp) == height) -X e.u.where.v = height; -X } -X return newintobject((long) teevent(tp, &e)); +X textobject *self; +X object *args; +X{ +X register TEXTEDIT *tp = self->t_text; +X EVENT e; +X if (!geteventarg(args, &e)) +X return NULL; +X if (e.type == WE_MOUSE_DOWN) { +X /* Cheat at the margins */ +X int width, height; +X wgetdocsize(e.window, &width, &height); +X if (e.u.where.h < 0 && tegetleft(tp) == 0) +X e.u.where.h = 0; +X else if (e.u.where.h > width && tegetright(tp) == width) +X e.u.where.h = width; +X if (e.u.where.v < 0 && tegettop(tp) == 0) +X e.u.where.v = 0; +X else if (e.u.where.v > height && tegetright(tp) == height) +X e.u.where.v = height; +X } +X return newintobject((long) teevent(tp, &e)); X} X Xstatic object * Xtext_getfocus(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X return makepoint(tegetfoc1(self->t_text), tegetfoc2(self->t_text)); +X if (!getnoarg(args)) +X return NULL; +X return makepoint(tegetfoc1(self->t_text), tegetfoc2(self->t_text)); X} X Xstatic object * Xtext_getfocustext(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X int f1, f2; -X char *text; -X if (!getnoarg(args)) -X return NULL; -X f1 = tegetfoc1(self->t_text); -X f2 = tegetfoc2(self->t_text); -X text = tegettext(self->t_text); -X return newsizedstringobject(text + f1, f2-f1); +X int f1, f2; +X char *text; +X if (!getnoarg(args)) +X return NULL; +X f1 = tegetfoc1(self->t_text); +X f2 = tegetfoc2(self->t_text); +X text = tegettext(self->t_text); +X return newsizedstringobject(text + f1, f2-f1); X} X Xstatic object * Xtext_getrect(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X return makerect(tegetleft(self->t_text), -X tegettop(self->t_text), -X tegetright(self->t_text), -X tegetbottom(self->t_text)); +X if (!getnoarg(args)) +X return NULL; +X return makerect(tegetleft(self->t_text), +X tegettop(self->t_text), +X tegetright(self->t_text), +X tegetbottom(self->t_text)); X} X Xstatic object * Xtext_gettext(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X return newsizedstringobject(tegettext(self->t_text), -X tegetlen(self->t_text)); +X if (!getnoarg(args)) +X return NULL; +X return newsizedstringobject(tegettext(self->t_text), +X tegetlen(self->t_text)); X} X Xstatic object * Xtext_move(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X int a[4]; -X if (!getrectarg(args, a)) -X return NULL; -X temovenew(self->t_text, a[0], a[1], a[2], a[3]); -X INCREF(None); -X return None; +X int a[4]; +X if (!getrectarg(args, a)) +X return NULL; +X temovenew(self->t_text, a[0], a[1], a[2], a[3]); +X INCREF(None); +X return None; X} X Xstatic object * Xtext_setfocus(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X int a[2]; -X if (!getpointarg(args, a)) -X return NULL; -X tesetfocus(self->t_text, a[0], a[1]); -X INCREF(None); -X return None; +X int a[2]; +X if (!getpointarg(args, a)) +X return NULL; +X tesetfocus(self->t_text, a[0], a[1]); +X INCREF(None); +X return None; X} X Xstatic object * Xtext_replace(self, args) -X textobject *self; -X object *args; +X textobject *self; +X object *args; X{ -X object *text; -X if (!getstrarg(args, &text)) -X return NULL; -X tereplace(self->t_text, getstringvalue(text)); -X INCREF(None); -X return None; +X object *text; +X if (!getstrarg(args, &text)) +X return NULL; +X tereplace(self->t_text, getstringvalue(text)); +X INCREF(None); +X return None; X} X Xstatic struct methodlist text_methods[] = { -X "arrow", text_arrow, -X "draw", text_draw, -X "event", text_event, -X "getfocus", text_getfocus, -X "getfocustext", text_getfocustext, -X "getrect", text_getrect, -X "gettext", text_gettext, -X "move", text_move, -X "replace", text_replace, -X "setfocus", text_setfocus, -X {NULL, NULL} /* sentinel */ +X "arrow", text_arrow, +X "draw", text_draw, +X "event", text_event, +X "getfocus", text_getfocus, +X "getfocustext", text_getfocustext, +X "getrect", text_getrect, +X "gettext", text_gettext, +X "move", text_move, +X "replace", text_replace, +X "setfocus", text_setfocus, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xtext_getattr(tp, name) -X textobject *tp; -X char *name; +X textobject *tp; +X char *name; X{ -X if (tp->t_attr != NULL) { -X object *v = dictlookup(tp->t_attr, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X } -X return findmethod(text_methods, (object *)tp, name); +X if (tp->t_attr != NULL) { +X object *v = dictlookup(tp->t_attr, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X } +X return findmethod(text_methods, (object *)tp, name); X} X Xstatic int Xtext_setattr(tp, name, v) -X textobject *tp; -X char *name; -X object *v; +X textobject *tp; +X char *name; +X object *v; X{ -X if (tp->t_attr == NULL) { -X tp->t_attr = newdictobject(); -X if (tp->t_attr == NULL) -X return -1; -X } -X if (v == NULL) -X return dictremove(tp->t_attr, name); -X else -X return dictinsert(tp->t_attr, name, v); +X if (tp->t_attr == NULL) { +X tp->t_attr = newdictobject(); +X if (tp->t_attr == NULL) +X return -1; +X } +X if (v == NULL) +X return dictremove(tp->t_attr, name); +X else +X return dictinsert(tp->t_attr, name, v); X} X Xstatic typeobject Texttype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "textedit", /*tp_name*/ -X sizeof(textobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X text_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X text_getattr, /*tp_getattr*/ -X text_setattr, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "textedit", /*tp_name*/ +X sizeof(textobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X text_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X text_getattr, /*tp_getattr*/ +X text_setattr, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; X X X/* Menu objects */ X -X#define IDOFFSET 10 /* Menu IDs we use start here */ -X#define MAXNMENU 20 /* Max #menus we allow */ +X#define IDOFFSET 10 /* Menu IDs we use start here */ +X#define MAXNMENU 20 /* Max #menus we allow */ Xstatic menuobject *menulist[MAXNMENU]; X Xstatic menuobject * Xnewmenuobject(title) -X object *title; -X{ -X int id; -X MENU *menu; -X menuobject *mp; -X for (id = 0; id < MAXNMENU; id++) { -X if (menulist[id] == NULL) -X break; -X } -X if (id >= MAXNMENU) -X return (menuobject *) err_nomem(); -X menu = wmenucreate(id + IDOFFSET, getstringvalue(title)); -X if (menu == NULL) -X return (menuobject *) err_nomem(); -X mp = NEWOBJ(menuobject, &Menutype); -X if (mp != NULL) { -X mp->m_menu = menu; -X mp->m_id = id + IDOFFSET; -X mp->m_attr = NULL; -X menulist[id] = mp; -X } -X else -X wmenudelete(menu); -X return mp; +X object *title; +X{ +X int id; +X MENU *menu; +X menuobject *mp; +X for (id = 0; id < MAXNMENU; id++) { +X if (menulist[id] == NULL) +X break; +X } +X if (id >= MAXNMENU) +X return (menuobject *) err_nomem(); +X menu = wmenucreate(id + IDOFFSET, getstringvalue(title)); +X if (menu == NULL) +X return (menuobject *) err_nomem(); +X mp = NEWOBJ(menuobject, &Menutype); +X if (mp != NULL) { +X mp->m_menu = menu; +X mp->m_id = id + IDOFFSET; +X mp->m_attr = NULL; +X menulist[id] = mp; +X } +X else +X wmenudelete(menu); +X return mp; X} X X/* Menu methods */ X Xstatic void Xmenu_dealloc(mp) -X menuobject *mp; +X menuobject *mp; X{ -X -X int id = mp->m_id - IDOFFSET; -X if (id >= 0 && id < MAXNMENU && menulist[id] == mp) { -X menulist[id] = NULL; -X } -X wmenudelete(mp->m_menu); -X if (mp->m_attr != NULL) -X DECREF(mp->m_attr); -X DEL(mp); +X +X int id = mp->m_id - IDOFFSET; +X if (id >= 0 && id < MAXNMENU && menulist[id] == mp) { +X menulist[id] = NULL; +X } +X wmenudelete(mp->m_menu); +X if (mp->m_attr != NULL) +X DECREF(mp->m_attr); +X DEL(mp); X} X Xstatic object * Xmenu_additem(self, args) -X menuobject *self; -X object *args; -X{ -X object *text; -X int shortcut; -X if (is_tupleobject(args)) { -X object *v; -X if (!getstrstrarg(args, &text, &v)) -X return NULL; -X if (getstringsize(v) != 1) { -X err_badarg(); -X return NULL; -X } -X shortcut = *getstringvalue(v) & 0xff; -X } -X else { -X if (!getstrarg(args, &text)) -X return NULL; -X shortcut = -1; -X } -X wmenuadditem(self->m_menu, getstringvalue(text), shortcut); -X INCREF(None); -X return None; +X menuobject *self; +X object *args; +X{ +X object *text; +X int shortcut; +X if (is_tupleobject(args)) { +X object *v; +X if (!getstrstrarg(args, &text, &v)) +X return NULL; +X if (getstringsize(v) != 1) { +X err_badarg(); +X return NULL; +X } +X shortcut = *getstringvalue(v) & 0xff; +X } +X else { +X if (!getstrarg(args, &text)) +X return NULL; +X shortcut = -1; +X } +X wmenuadditem(self->m_menu, getstringvalue(text), shortcut); +X INCREF(None); +X return None; X} X Xstatic object * Xmenu_setitem(self, args) -X menuobject *self; -X object *args; +X menuobject *self; +X object *args; X{ -X int index; -X object *text; -X if (!getintstrarg(args, &index, &text)) -X return NULL; -X wmenusetitem(self->m_menu, index, getstringvalue(text)); -X INCREF(None); -X return None; +X int index; +X object *text; +X if (!getintstrarg(args, &index, &text)) +X return NULL; +X wmenusetitem(self->m_menu, index, getstringvalue(text)); +X INCREF(None); +X return None; X} X Xstatic object * Xmenu_enable(self, args) -X menuobject *self; -X object *args; +X menuobject *self; +X object *args; X{ -X int index; -X int flag; -X if (!getintintarg(args, &index, &flag)) -X return NULL; -X wmenuenable(self->m_menu, index, flag); -X INCREF(None); -X return None; +X int index; +X int flag; +X if (!getintintarg(args, &index, &flag)) +X return NULL; +X wmenuenable(self->m_menu, index, flag); +X INCREF(None); +X return None; X} X Xstatic object * Xmenu_check(self, args) -X menuobject *self; -X object *args; +X menuobject *self; +X object *args; X{ -X int index; -X int flag; -X if (!getintintarg(args, &index, &flag)) -X return NULL; -X wmenucheck(self->m_menu, index, flag); -X INCREF(None); -X return None; +X int index; +X int flag; +X if (!getintintarg(args, &index, &flag)) +X return NULL; +X wmenucheck(self->m_menu, index, flag); +X INCREF(None); +X return None; X} X Xstatic struct methodlist menu_methods[] = { -X "additem", menu_additem, -X "setitem", menu_setitem, -X "enable", menu_enable, -X "check", menu_check, -X {NULL, NULL} /* sentinel */ +X "additem", menu_additem, +X "setitem", menu_setitem, +X "enable", menu_enable, +X "check", menu_check, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xmenu_getattr(mp, name) -X menuobject *mp; -X char *name; +X menuobject *mp; +X char *name; X{ -X if (mp->m_attr != NULL) { -X object *v = dictlookup(mp->m_attr, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X } -X return findmethod(menu_methods, (object *)mp, name); +X if (mp->m_attr != NULL) { +X object *v = dictlookup(mp->m_attr, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X } +X return findmethod(menu_methods, (object *)mp, name); X} X Xstatic int Xmenu_setattr(mp, name, v) -X menuobject *mp; -X char *name; -X object *v; +X menuobject *mp; +X char *name; +X object *v; X{ -X if (mp->m_attr == NULL) { -X mp->m_attr = newdictobject(); -X if (mp->m_attr == NULL) -X return -1; -X } -X if (v == NULL) -X return dictremove(mp->m_attr, name); -X else -X return dictinsert(mp->m_attr, name, v); +X if (mp->m_attr == NULL) { +X mp->m_attr = newdictobject(); +X if (mp->m_attr == NULL) +X return -1; +X } +X if (v == NULL) +X return dictremove(mp->m_attr, name); +X else +X return dictinsert(mp->m_attr, name, v); X} X Xstatic typeobject Menutype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "menu", /*tp_name*/ -X sizeof(menuobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X menu_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X menu_getattr, /*tp_getattr*/ -X menu_setattr, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "menu", /*tp_name*/ +X sizeof(menuobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X menu_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X menu_getattr, /*tp_getattr*/ +X menu_setattr, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; X X @@ -2012,744 +2012,744 @@ X/* Window methods */ X Xstatic void Xwindow_dealloc(wp) -X windowobject *wp; -X{ -X if (wp->w_win != NULL) { -X int tag = wgettag(wp->w_win); -X if (tag >= 0 && tag < MAXNWIN) -X windowlist[tag] = NULL; -X else -X fprintf(stderr, "XXX help! tag %d in window_dealloc\n", -X tag); -X wclose(wp->w_win); -X } -X DECREF(wp->w_title); -X if (wp->w_attr != NULL) -X DECREF(wp->w_attr); -X free((char *)wp); +X windowobject *wp; +X{ +X if (wp->w_win != NULL) { +X int tag = wgettag(wp->w_win); +X if (tag >= 0 && tag < MAXNWIN) +X windowlist[tag] = NULL; +X else +X fprintf(stderr, "XXX help! tag %d in window_dealloc\n", +X tag); +X wclose(wp->w_win); +X } +X DECREF(wp->w_title); +X if (wp->w_attr != NULL) +X DECREF(wp->w_attr); +X free((char *)wp); X} X Xstatic void Xwindow_print(wp, fp, flags) -X windowobject *wp; -X FILE *fp; -X int flags; +X windowobject *wp; +X FILE *fp; +X int flags; X{ -X fprintf(fp, "<window titled '%s'>", getstringvalue(wp->w_title)); +X fprintf(fp, "<window titled '%s'>", getstringvalue(wp->w_title)); X} X Xstatic object * Xwindow_begindrawing(wp, args) -X windowobject *wp; -X object *args; -X{ -X drawingobject *dp; -X if (!getnoarg(args)) -X return NULL; -X if (Drawing != NULL) { -X err_setstr(RuntimeError, "already drawing"); -X return NULL; -X } -X dp = NEWOBJ(drawingobject, &Drawingtype); -X if (dp == NULL) -X return NULL; -X Drawing = dp; -X INCREF(wp); -X dp->d_ref = wp; -X wbegindrawing(wp->w_win); -X return (object *)dp; +X windowobject *wp; +X object *args; +X{ +X drawingobject *dp; +X if (!getnoarg(args)) +X return NULL; +X if (Drawing != NULL) { +X err_setstr(RuntimeError, "already drawing"); +X return NULL; +X } +X dp = NEWOBJ(drawingobject, &Drawingtype); +X if (dp == NULL) +X return NULL; +X Drawing = dp; +X INCREF(wp); +X dp->d_ref = wp; +X wbegindrawing(wp->w_win); +X return (object *)dp; X} X Xstatic object * Xwindow_change(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int a[4]; -X if (!getrectarg(args, a)) -X return NULL; -X wchange(wp->w_win, a[0], a[1], a[2], a[3]); -X INCREF(None); -X return None; +X int a[4]; +X if (!getrectarg(args, a)) +X return NULL; +X wchange(wp->w_win, a[0], a[1], a[2], a[3]); +X INCREF(None); +X return None; X} X Xstatic object * Xwindow_gettitle(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X INCREF(wp->w_title); -X return wp->w_title; +X if (!getnoarg(args)) +X return NULL; +X INCREF(wp->w_title); +X return wp->w_title; X} X Xstatic object * Xwindow_getwinsize(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int width, height; -X if (!getnoarg(args)) -X return NULL; -X wgetwinsize(wp->w_win, &width, &height); -X return makepoint(width, height); +X int width, height; +X if (!getnoarg(args)) +X return NULL; +X wgetwinsize(wp->w_win, &width, &height); +X return makepoint(width, height); X} X Xstatic object * Xwindow_getdocsize(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int width, height; -X if (!getnoarg(args)) -X return NULL; -X wgetdocsize(wp->w_win, &width, &height); -X return makepoint(width, height); +X int width, height; +X if (!getnoarg(args)) +X return NULL; +X wgetdocsize(wp->w_win, &width, &height); +X return makepoint(width, height); X} X Xstatic object * Xwindow_getorigin(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int width, height; -X if (!getnoarg(args)) -X return NULL; -X wgetorigin(wp->w_win, &width, &height); -X return makepoint(width, height); +X int width, height; +X if (!getnoarg(args)) +X return NULL; +X wgetorigin(wp->w_win, &width, &height); +X return makepoint(width, height); X} X Xstatic object * Xwindow_scroll(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int a[6]; -X if (!getrectpointarg(args, a)) -X return NULL; -X wscroll(wp->w_win, a[0], a[1], a[2], a[3], a[4], a[5]); -X INCREF(None); -X return None; +X int a[6]; +X if (!getrectpointarg(args, a)) +X return NULL; +X wscroll(wp->w_win, a[0], a[1], a[2], a[3], a[4], a[5]); +X INCREF(None); +X return None; X} X Xstatic object * Xwindow_setdocsize(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int a[2]; -X if (!getpointarg(args, a)) -X return NULL; -X wsetdocsize(wp->w_win, a[0], a[1]); -X INCREF(None); -X return None; +X int a[2]; +X if (!getpointarg(args, a)) +X return NULL; +X wsetdocsize(wp->w_win, a[0], a[1]); +X INCREF(None); +X return None; X} X Xstatic object * Xwindow_setorigin(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int a[2]; -X if (!getpointarg(args, a)) -X return NULL; -X wsetorigin(wp->w_win, a[0], a[1]); -X INCREF(None); -X return None; +X int a[2]; +X if (!getpointarg(args, a)) +X return NULL; +X wsetorigin(wp->w_win, a[0], a[1]); +X INCREF(None); +X return None; X} X Xstatic object * Xwindow_settitle(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X object *title; -X if (!getstrarg(args, &title)) -X return NULL; -X DECREF(wp->w_title); -X INCREF(title); -X wp->w_title = title; -X wsettitle(wp->w_win, getstringvalue(title)); -X INCREF(None); -X return None; +X object *title; +X if (!getstrarg(args, &title)) +X return NULL; +X DECREF(wp->w_title); +X INCREF(title); +X wp->w_title = title; +X wsettitle(wp->w_win, getstringvalue(title)); +X INCREF(None); +X return None; X} X Xstatic object * Xwindow_show(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int a[4]; -X if (!getrectarg(args, a)) -X return NULL; -X wshow(wp->w_win, a[0], a[1], a[2], a[3]); -X INCREF(None); -X return None; +X int a[4]; +X if (!getrectarg(args, a)) +X return NULL; +X wshow(wp->w_win, a[0], a[1], a[2], a[3]); +X INCREF(None); +X return None; X} X Xstatic object * Xwindow_settimer(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int a; -X if (!getintarg(args, &a)) -X return NULL; -X wsettimer(wp->w_win, a); -X INCREF(None); -X return None; +X int a; +X if (!getintarg(args, &a)) +X return NULL; +X wsettimer(wp->w_win, a); +X INCREF(None); +X return None; X} X Xstatic object * Xwindow_menucreate(self, args) -X windowobject *self; -X object *args; +X windowobject *self; +X object *args; X{ -X menuobject *mp; -X object *title; -X if (!getstrarg(args, &title)) -X return NULL; -X wmenusetdeflocal(1); -X mp = newmenuobject(title); -X if (mp == NULL) -X return NULL; -X wmenuattach(self->w_win, mp->m_menu); -X return (object *)mp; +X menuobject *mp; +X object *title; +X if (!getstrarg(args, &title)) +X return NULL; +X wmenusetdeflocal(1); +X mp = newmenuobject(title); +X if (mp == NULL) +X return NULL; +X wmenuattach(self->w_win, mp->m_menu); +X return (object *)mp; X} X Xstatic object * Xwindow_textcreate(self, args) -X windowobject *self; -X object *args; +X windowobject *self; +X object *args; X{ -X textobject *tp; -X int a[4]; -X if (!getrectarg(args, a)) -X return NULL; -X return (object *) -X newtextobject(self, a[0], a[1], a[2], a[3]); +X textobject *tp; +X int a[4]; +X if (!getrectarg(args, a)) +X return NULL; +X return (object *) +X newtextobject(self, a[0], a[1], a[2], a[3]); X} X Xstatic object * Xwindow_setselection(self, args) -X windowobject *self; -X object *args; +X windowobject *self; +X object *args; X{ -X int sel; -X object *str; -X int ok; -X if (!getintstrarg(args, &sel, &str)) -X return NULL; -X ok = wsetselection(self->w_win, sel, -X getstringvalue(str), (int)getstringsize(str)); -X return newintobject(ok); +X int sel; +X object *str; +X int ok; +X if (!getintstrarg(args, &sel, &str)) +X return NULL; +X ok = wsetselection(self->w_win, sel, +X getstringvalue(str), (int)getstringsize(str)); +X return newintobject(ok); X} X Xstatic object * Xwindow_setwincursor(self, args) -X windowobject *self; -X object *args; -X{ -X object *str; -X CURSOR *c; -X if (!getstrarg(args, &str)) -X return NULL; -X c = wfetchcursor(getstringvalue(str)); -X if (c == NULL) { -X err_setstr(RuntimeError, "no such cursor"); -X return NULL; -X } -X wsetwincursor(self->w_win, c); -X INCREF(None); -X return None; +X windowobject *self; +X object *args; +X{ +X object *str; +X CURSOR *c; +X if (!getstrarg(args, &str)) +X return NULL; +X c = wfetchcursor(getstringvalue(str)); +X if (c == NULL) { +X err_setstr(RuntimeError, "no such cursor"); +X return NULL; +X } +X wsetwincursor(self->w_win, c); +X INCREF(None); +X return None; X} X Xstatic struct methodlist window_methods[] = { -X {"begindrawing",window_begindrawing}, -X {"change", window_change}, -X {"getdocsize", window_getdocsize}, -X {"getorigin", window_getorigin}, -X {"gettitle", window_gettitle}, -X {"getwinsize", window_getwinsize}, -X {"menucreate", window_menucreate}, -X {"scroll", window_scroll}, -X {"setwincursor",window_setwincursor}, -X {"setdocsize", window_setdocsize}, -X {"setorigin", window_setorigin}, -X {"setselection",window_setselection}, -X {"settimer", window_settimer}, -X {"settitle", window_settitle}, -X {"show", window_show}, -X {"textcreate", window_textcreate}, -X {NULL, NULL} /* sentinel */ +X {"begindrawing",window_begindrawing}, +X {"change", window_change}, +X {"getdocsize", window_getdocsize}, +X {"getorigin", window_getorigin}, +X {"gettitle", window_gettitle}, +X {"getwinsize", window_getwinsize}, +X {"menucreate", window_menucreate}, +X {"scroll", window_scroll}, +X {"setwincursor",window_setwincursor}, +X {"setdocsize", window_setdocsize}, +X {"setorigin", window_setorigin}, +X {"setselection",window_setselection}, +X {"settimer", window_settimer}, +X {"settitle", window_settitle}, +X {"show", window_show}, +X {"textcreate", window_textcreate}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xwindow_getattr(wp, name) -X windowobject *wp; -X char *name; +X windowobject *wp; +X char *name; X{ -X if (wp->w_attr != NULL) { -X object *v = dictlookup(wp->w_attr, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X } -X return findmethod(window_methods, (object *)wp, name); +X if (wp->w_attr != NULL) { +X object *v = dictlookup(wp->w_attr, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X } +X return findmethod(window_methods, (object *)wp, name); X} X Xstatic int Xwindow_setattr(wp, name, v) -X windowobject *wp; -X char *name; -X object *v; +X windowobject *wp; +X char *name; +X object *v; X{ -X if (wp->w_attr == NULL) { -X wp->w_attr = newdictobject(); -X if (wp->w_attr == NULL) -X return -1; -X } -X if (v == NULL) -X return dictremove(wp->w_attr, name); -X else -X return dictinsert(wp->w_attr, name, v); +X if (wp->w_attr == NULL) { +X wp->w_attr = newdictobject(); +X if (wp->w_attr == NULL) +X return -1; +X } +X if (v == NULL) +X return dictremove(wp->w_attr, name); +X else +X return dictinsert(wp->w_attr, name, v); X} X Xstatic typeobject Windowtype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "window", /*tp_name*/ -X sizeof(windowobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X window_dealloc, /*tp_dealloc*/ -X window_print, /*tp_print*/ -X window_getattr, /*tp_getattr*/ -X window_setattr, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "window", /*tp_name*/ +X sizeof(windowobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X window_dealloc, /*tp_dealloc*/ +X window_print, /*tp_print*/ +X window_getattr, /*tp_getattr*/ +X window_setattr, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; X X/* Stdwin methods */ X Xstatic object * Xstdwin_open(sw, args) -X object *sw; -X object *args; -X{ -X int tag; -X object *title; -X windowobject *wp; -X if (!getstrarg(args, &title)) -X return NULL; -X for (tag = 0; tag < MAXNWIN; tag++) { -X if (windowlist[tag] == NULL) -X break; -X } -X if (tag >= MAXNWIN) -X return err_nomem(); -X wp = NEWOBJ(windowobject, &Windowtype); -X if (wp == NULL) -X return NULL; -X INCREF(title); -X wp->w_title = title; -X wp->w_win = wopen(getstringvalue(title), (void (*)()) NULL); -X wp->w_attr = NULL; -X if (wp->w_win == NULL) { -X DECREF(wp); -X return NULL; -X } -X windowlist[tag] = wp; -X wsettag(wp->w_win, tag); -X return (object *)wp; +X object *sw; +X object *args; +X{ +X int tag; +X object *title; +X windowobject *wp; +X if (!getstrarg(args, &title)) +X return NULL; +X for (tag = 0; tag < MAXNWIN; tag++) { +X if (windowlist[tag] == NULL) +X break; +X } +X if (tag >= MAXNWIN) +X return err_nomem(); +X wp = NEWOBJ(windowobject, &Windowtype); +X if (wp == NULL) +X return NULL; +X INCREF(title); +X wp->w_title = title; +X wp->w_win = wopen(getstringvalue(title), (void (*)()) NULL); +X wp->w_attr = NULL; +X if (wp->w_win == NULL) { +X DECREF(wp); +X return NULL; +X } +X windowlist[tag] = wp; +X wsettag(wp->w_win, tag); +X return (object *)wp; X} X Xstatic object * Xstdwin_get_poll_event(poll, args) -X int poll; -X object *args; -X{ -X EVENT e; -X object *v, *w; -X if (!getnoarg(args)) -X return NULL; -X if (Drawing != NULL) { -X err_setstr(RuntimeError, "cannot getevent() while drawing"); -X return NULL; -X } +X int poll; +X object *args; +X{ +X EVENT e; +X object *v, *w; +X if (!getnoarg(args)) +X return NULL; +X if (Drawing != NULL) { +X err_setstr(RuntimeError, "cannot getevent() while drawing"); +X return NULL; +X } X/* again: */ -X if (poll) { -X if (!wpollevent(&e)) { -X INCREF(None); -X return None; -X } -X } -X else -X wgetevent(&e); -X if (e.type == WE_COMMAND && e.u.command == WC_CANCEL) { -X /* Turn keyboard interrupts into exceptions */ -X err_set(KeyboardInterrupt); -X return NULL; -X } +X if (poll) { +X if (!wpollevent(&e)) { +X INCREF(None); +X return None; +X } +X } +X else +X wgetevent(&e); +X if (e.type == WE_COMMAND && e.u.command == WC_CANCEL) { +X /* Turn keyboard interrupts into exceptions */ +X err_set(KeyboardInterrupt); +X return NULL; +X } X/* -X if (e.window == NULL && (e.type == WE_COMMAND || e.type == WE_CHAR)) -X goto again; +X if (e.window == NULL && (e.type == WE_COMMAND || e.type == WE_CHAR)) +X goto again; X*/ -X if (e.type == WE_COMMAND && e.u.command == WC_CLOSE) { -X /* Turn WC_CLOSE commands into WE_CLOSE events */ -X e.type = WE_CLOSE; -X } -X v = newtupleobject(3); -X if (v == NULL) -X return NULL; -X if ((w = newintobject((long)e.type)) == NULL) { -X DECREF(v); -X return NULL; -X } -X settupleitem(v, 0, w); -X if (e.window == NULL) -X w = None; -X else { -X int tag = wgettag(e.window); -X if (tag < 0 || tag >= MAXNWIN || windowlist[tag] == NULL) -X w = None; -X else -X w = (object *)windowlist[tag]; +X if (e.type == WE_COMMAND && e.u.command == WC_CLOSE) { +X /* Turn WC_CLOSE commands into WE_CLOSE events */ +X e.type = WE_CLOSE; +X } +X v = newtupleobject(3); +X if (v == NULL) +X return NULL; +X if ((w = newintobject((long)e.type)) == NULL) { +X DECREF(v); +X return NULL; +X } +X settupleitem(v, 0, w); +X if (e.window == NULL) +X w = None; +X else { +X int tag = wgettag(e.window); +X if (tag < 0 || tag >= MAXNWIN || windowlist[tag] == NULL) +X w = None; +X else +X w = (object *)windowlist[tag]; X#ifdef sgi -X /* XXX Trap for unexplained weird bug */ -X if ((long)w == (long)0x80000001) { -X err_setstr(SystemError, -X "bad pointer in stdwin.getevent()"); -X return NULL; -X } +X /* XXX Trap for unexplained weird bug */ +X if ((long)w == (long)0x80000001) { +X err_setstr(SystemError, +X "bad pointer in stdwin.getevent()"); +X return NULL; +X } X#endif -X } -X INCREF(w); -X settupleitem(v, 1, w); -X switch (e.type) { -X case WE_CHAR: -X { -X char c[1]; -X c[0] = e.u.character; -X w = newsizedstringobject(c, 1); -X } -X break; -X case WE_COMMAND: -X w = newintobject((long)e.u.command); -X break; -X case WE_DRAW: -X w = makerect(e.u.area.left, e.u.area.top, -X e.u.area.right, e.u.area.bottom); -X break; -X case WE_MOUSE_DOWN: -X case WE_MOUSE_MOVE: -X case WE_MOUSE_UP: -X w = makemouse(e.u.where.h, e.u.where.v, -X e.u.where.clicks, -X e.u.where.button, -X e.u.where.mask); -X break; -X case WE_MENU: -X if (e.u.m.id >= IDOFFSET && e.u.m.id < IDOFFSET+MAXNMENU && -X menulist[e.u.m.id - IDOFFSET] != NULL) -X w = (object *)menulist[e.u.m.id - IDOFFSET]; -X else -X w = None; -X w = makemenu(w, e.u.m.item); -X break; -X case WE_LOST_SEL: -X w = newintobject((long)e.u.sel); -X break; -X default: -X w = None; -X INCREF(w); -X break; -X } -X if (w == NULL) { -X DECREF(v); -X return NULL; -X } -X settupleitem(v, 2, w); -X return v; +X } +X INCREF(w); +X settupleitem(v, 1, w); +X switch (e.type) { +X case WE_CHAR: +X { +X char c[1]; +X c[0] = e.u.character; +X w = newsizedstringobject(c, 1); +X } +X break; +X case WE_COMMAND: +X w = newintobject((long)e.u.command); +X break; +X case WE_DRAW: +X w = makerect(e.u.area.left, e.u.area.top, +X e.u.area.right, e.u.area.bottom); +X break; +X case WE_MOUSE_DOWN: +X case WE_MOUSE_MOVE: +X case WE_MOUSE_UP: +X w = makemouse(e.u.where.h, e.u.where.v, +X e.u.where.clicks, +X e.u.where.button, +X e.u.where.mask); +X break; +X case WE_MENU: +X if (e.u.m.id >= IDOFFSET && e.u.m.id < IDOFFSET+MAXNMENU && +X menulist[e.u.m.id - IDOFFSET] != NULL) +X w = (object *)menulist[e.u.m.id - IDOFFSET]; +X else +X w = None; +X w = makemenu(w, e.u.m.item); +X break; +X case WE_LOST_SEL: +X w = newintobject((long)e.u.sel); +X break; +X default: +X w = None; +X INCREF(w); +X break; +X } +X if (w == NULL) { +X DECREF(v); +X return NULL; +X } +X settupleitem(v, 2, w); +X return v; X} X Xstatic object * Xstdwin_getevent(sw, args) -X object *sw; -X object *args; +X object *sw; +X object *args; X{ -X return stdwin_get_poll_event(0, args); +X return stdwin_get_poll_event(0, args); X} X Xstatic object * Xstdwin_pollevent(sw, args) -X object *sw; -X object *args; +X object *sw; +X object *args; X{ -X return stdwin_get_poll_event(1, args); +X return stdwin_get_poll_event(1, args); X} X Xstatic object * Xstdwin_setdefwinpos(sw, args) -X object *sw; -X object *args; +X object *sw; +X object *args; X{ -X int a[2]; -X if (!getpointarg(args, a)) -X return NULL; -X wsetdefwinpos(a[0], a[1]); -X INCREF(None); -X return None; +X int a[2]; +X if (!getpointarg(args, a)) +X return NULL; +X wsetdefwinpos(a[0], a[1]); +X INCREF(None); +X return None; X} X Xstatic object * Xstdwin_setdefwinsize(sw, args) -X object *sw; -X object *args; +X object *sw; +X object *args; X{ -X int a[2]; -X if (!getpointarg(args, a)) -X return NULL; -X wsetdefwinsize(a[0], a[1]); -X INCREF(None); -X return None; +X int a[2]; +X if (!getpointarg(args, a)) +X return NULL; +X wsetdefwinsize(a[0], a[1]); +X INCREF(None); +X return None; X} X Xstatic object * Xstdwin_getdefwinpos(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int h, v; -X if (!getnoarg(args)) -X return NULL; -X wgetdefwinpos(&h, &v); -X return makepoint(h, v); +X int h, v; +X if (!getnoarg(args)) +X return NULL; +X wgetdefwinpos(&h, &v); +X return makepoint(h, v); X} X Xstatic object * Xstdwin_getdefwinsize(wp, args) -X windowobject *wp; -X object *args; +X windowobject *wp; +X object *args; X{ -X int width, height; -X if (!getnoarg(args)) -X return NULL; -X wgetdefwinsize(&width, &height); -X return makepoint(width, height); +X int width, height; +X if (!getnoarg(args)) +X return NULL; +X wgetdefwinsize(&width, &height); +X return makepoint(width, height); X} X Xstatic object * Xstdwin_menucreate(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *title; -X if (!getstrarg(args, &title)) -X return NULL; -X wmenusetdeflocal(0); -X return (object *)newmenuobject(title); +X object *title; +X if (!getstrarg(args, &title)) +X return NULL; +X wmenusetdeflocal(0); +X return (object *)newmenuobject(title); X} X Xstatic object * Xstdwin_askfile(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *prompt, *dflt; -X int new, ret; -X char buf[256]; -X if (!getstrstrintarg(args, &prompt, &dflt, &new)) -X return NULL; -X strncpy(buf, getstringvalue(dflt), sizeof buf); -X buf[sizeof buf - 1] = '\0'; -X ret = waskfile(getstringvalue(prompt), buf, sizeof buf, new); -X if (!ret) { -X err_set(KeyboardInterrupt); -X return NULL; -X } -X return newstringobject(buf); +X object *prompt, *dflt; +X int new, ret; +X char buf[256]; +X if (!getstrstrintarg(args, &prompt, &dflt, &new)) +X return NULL; +X strncpy(buf, getstringvalue(dflt), sizeof buf); +X buf[sizeof buf - 1] = '\0'; +X ret = waskfile(getstringvalue(prompt), buf, sizeof buf, new); +X if (!ret) { +X err_set(KeyboardInterrupt); +X return NULL; +X } +X return newstringobject(buf); X} X Xstatic object * Xstdwin_askync(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *prompt; -X int new, ret; -X if (!getstrintarg(args, &prompt, &new)) -X return NULL; -X ret = waskync(getstringvalue(prompt), new); -X if (ret < 0) { -X err_set(KeyboardInterrupt); -X return NULL; -X } -X return newintobject((long)ret); +X object *prompt; +X int new, ret; +X if (!getstrintarg(args, &prompt, &new)) +X return NULL; +X ret = waskync(getstringvalue(prompt), new); +X if (ret < 0) { +X err_set(KeyboardInterrupt); +X return NULL; +X } +X return newintobject((long)ret); X} X Xstatic object * Xstdwin_askstr(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *prompt, *dflt; -X int ret; -X char buf[256]; -X if (!getstrstrarg(args, &prompt, &dflt)) -X return NULL; -X strncpy(buf, getstringvalue(dflt), sizeof buf); -X buf[sizeof buf - 1] = '\0'; -X ret = waskstr(getstringvalue(prompt), buf, sizeof buf); -X if (!ret) { -X err_set(KeyboardInterrupt); -X return NULL; -X } -X return newstringobject(buf); +X object *prompt, *dflt; +X int ret; +X char buf[256]; +X if (!getstrstrarg(args, &prompt, &dflt)) +X return NULL; +X strncpy(buf, getstringvalue(dflt), sizeof buf); +X buf[sizeof buf - 1] = '\0'; +X ret = waskstr(getstringvalue(prompt), buf, sizeof buf); +X if (!ret) { +X err_set(KeyboardInterrupt); +X return NULL; +X } +X return newstringobject(buf); X} X Xstatic object * Xstdwin_message(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *msg; -X if (!getstrarg(args, &msg)) -X return NULL; -X wmessage(getstringvalue(msg)); -X INCREF(None); -X return None; +X object *msg; +X if (!getstrarg(args, &msg)) +X return NULL; +X wmessage(getstringvalue(msg)); +X INCREF(None); +X return None; X} X Xstatic object * Xstdwin_fleep(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X wfleep(); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X wfleep(); +X INCREF(None); +X return None; X} X Xstatic object * Xstdwin_setcutbuffer(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int i; -X object *str; -X if (!getintstrarg(args, &i, &str)) -X return NULL; -X wsetcutbuffer(i, getstringvalue(str), getstringsize(str)); -X INCREF(None); -X return None; +X int i; +X object *str; +X if (!getintstrarg(args, &i, &str)) +X return NULL; +X wsetcutbuffer(i, getstringvalue(str), getstringsize(str)); +X INCREF(None); +X return None; X} X Xstatic object * Xstdwin_getcutbuffer(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int i; -X char *str; -X int len; -X if (!getintarg(args, &i)) -X return NULL; -X str = wgetcutbuffer(i, &len); -X if (str == NULL) { -X str = ""; -X len = 0; -X } -X return newsizedstringobject(str, len); +X int i; +X char *str; +X int len; +X if (!getintarg(args, &i)) +X return NULL; +X str = wgetcutbuffer(i, &len); +X if (str == NULL) { +X str = ""; +X len = 0; +X } +X return newsizedstringobject(str, len); X} X Xstatic object * Xstdwin_rotatecutbuffers(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int i; -X if (!getintarg(args, &i)) -X return NULL; -X wrotatecutbuffers(i); -X INCREF(None); -X return None; +X int i; +X if (!getintarg(args, &i)) +X return NULL; +X wrotatecutbuffers(i); +X INCREF(None); +X return None; X} X Xstatic object * Xstdwin_getselection(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int sel; -X char *data; -X int len; -X if (!getintarg(args, &sel)) -X return NULL; -X data = wgetselection(sel, &len); -X if (data == NULL) { -X data = ""; -X len = 0; -X } -X return newsizedstringobject(data, len); +X int sel; +X char *data; +X int len; +X if (!getintarg(args, &sel)) +X return NULL; +X data = wgetselection(sel, &len); +X if (data == NULL) { +X data = ""; +X len = 0; +X } +X return newsizedstringobject(data, len); X} X Xstatic object * Xstdwin_resetselection(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int sel; -X if (!getintarg(args, &sel)) -X return NULL; -X wresetselection(sel); -X INCREF(None); -X return None; +X int sel; +X if (!getintarg(args, &sel)) +X return NULL; +X wresetselection(sel); +X INCREF(None); +X return None; X} X Xstatic struct methodlist stdwin_methods[] = { -X {"askfile", stdwin_askfile}, -X {"askstr", stdwin_askstr}, -X {"askync", stdwin_askync}, -X {"fleep", stdwin_fleep}, -X {"getselection", stdwin_getselection}, -X {"getcutbuffer", stdwin_getcutbuffer}, -X {"getdefwinpos", stdwin_getdefwinpos}, -X {"getdefwinsize", stdwin_getdefwinsize}, -X {"getevent", stdwin_getevent}, -X {"menucreate", stdwin_menucreate}, -X {"message", stdwin_message}, -X {"open", stdwin_open}, -X {"pollevent", stdwin_pollevent}, -X {"resetselection", stdwin_resetselection}, -X {"rotatecutbuffers", stdwin_rotatecutbuffers}, -X {"setcutbuffer", stdwin_setcutbuffer}, -X {"setdefwinpos", stdwin_setdefwinpos}, -X {"setdefwinsize", stdwin_setdefwinsize}, -X -X /* Text measuring methods borrow code from drawing objects: */ -X {"baseline", drawing_baseline}, -X {"lineheight", drawing_lineheight}, -X {"textbreak", drawing_textbreak}, -X {"textwidth", drawing_textwidth}, -X {NULL, NULL} /* sentinel */ +X {"askfile", stdwin_askfile}, +X {"askstr", stdwin_askstr}, +X {"askync", stdwin_askync}, +X {"fleep", stdwin_fleep}, +X {"getselection", stdwin_getselection}, +X {"getcutbuffer", stdwin_getcutbuffer}, +X {"getdefwinpos", stdwin_getdefwinpos}, +X {"getdefwinsize", stdwin_getdefwinsize}, +X {"getevent", stdwin_getevent}, +X {"menucreate", stdwin_menucreate}, +X {"message", stdwin_message}, +X {"open", stdwin_open}, +X {"pollevent", stdwin_pollevent}, +X {"resetselection", stdwin_resetselection}, +X {"rotatecutbuffers", stdwin_rotatecutbuffers}, +X {"setcutbuffer", stdwin_setcutbuffer}, +X {"setdefwinpos", stdwin_setdefwinpos}, +X {"setdefwinsize", stdwin_setdefwinsize}, +X +X /* Text measuring methods borrow code from drawing objects: */ +X {"baseline", drawing_baseline}, +X {"lineheight", drawing_lineheight}, +X {"textbreak", drawing_textbreak}, +X {"textwidth", drawing_textwidth}, +X {NULL, NULL} /* sentinel */ X}; X Xvoid Xinitstdwin() X{ -X static int inited; -X if (!inited) { -X winit(); -X inited = 1; -X } -X initmodule("stdwin", stdwin_methods); +X static int inited; +X if (!inited) { +X winit(); +X inited = 1; +X } +X initmodule("stdwin", stdwin_methods); X} EOF fi echo 'Part 04 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-05-21.shar b/shar/python-0.9.1-05-21.shar index 2d7f035..ed014c6 100644 --- a/shar/python-0.9.1-05-21.shar +++ b/shar/python-0.9.1-05-21.shar @@ -9,21 +9,21 @@ else echo 'x - demo/sgi/audio_stdwin/README' sed 's/^X//' > 'demo/sgi/audio_stdwin/README' << 'EOF' XThree programs that provide a user interface based upon STDWIN to the -Xaudio device of the SGI 4D/25. These scripts also demonstrate the power +Xaudio device of the SGI 4D/25. These scripts also demonstrate the power Xof a set of window interface classes implemented in Python that simplify Xthe construction of all sorts of buttons, etc. X -Xjukebox Browses a directory full of sound samples and lets you -X play selected ones. (Probably not fully functional, it -X requires a conversion program.) +Xjukebox Browses a directory full of sound samples and lets you +X play selected ones. (Probably not fully functional, it +X requires a conversion program.) X -Xrec A tape recorder that lets you record a sound sample, -X play it back, and save it to a file. Various options to -X set sampling rate, volume etc. When idle it doubles -X as a VU meter. +Xrec A tape recorder that lets you record a sound sample, +X play it back, and save it to a file. Various options to +X set sampling rate, volume etc. When idle it doubles +X as a VU meter. X -Xvumeter A VU meter that displays a history of the volume of -X sound recently sampled from the microphone. +Xvumeter A VU meter that displays a history of the volume of +X sound recently sampled from the microphone. EOF fi if test -s 'src/panelmodule.c' @@ -35,12 +35,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -56,13 +56,13 @@ X X******************************************************************/ X X/* Panel module. -X Interface to the NASA Ames "panel library" for the SGI Graphics Library -X by David Tristram. -X -X NOTE: the panel library dumps core if you don't create a window before -X calling pnl.mkpanel(). A call to gl.winopen() suffices. -X If you don't want a window to be created, call gl.noport() before -X gl.winopen(). +X Interface to the NASA Ames "panel library" for the SGI Graphics Library +X by David Tristram. +X +X NOTE: the panel library dumps core if you don't create a window before +X calling pnl.mkpanel(). A call to gl.winopen() suffices. +X If you don't want a window to be created, call gl.noport() before +X gl.winopen(). X*/ X X#include <gl.h> @@ -76,9 +76,9 @@ X#include "cgensupport.h" X X X/* The offsetof() macro calculates the offset of a structure member -X in its structure. Unfortunately this cannot be written down portably, -X hence it is standardized by ANSI C. For pre-ANSI C compilers, -X we give a version here that works usually (but watch out!): */ +X in its structure. Unfortunately this cannot be written down portably, +X hence it is standardized by ANSI C. For pre-ANSI C compilers, +X we give a version here that works usually (but watch out!): */ X X#ifndef offsetof X#define offsetof(type, member) ( (int) & ((type*)0) -> member ) @@ -88,9 +88,9 @@ X X/* Panel objects */ X Xtypedef struct { -X OB_HEAD -X Panel *ob_panel; -X object *ob_paneldict; +X OB_HEAD +X Panel *ob_panel; +X object *ob_paneldict; X} panelobject; X Xextern typeobject Paneltype; /* Really static, forward */ @@ -101,8 +101,8 @@ X X/* Actuator objects */ X Xtypedef struct { -X OB_HEAD -X Actuator *ob_actuator; +X OB_HEAD +X Actuator *ob_actuator; X} actuatorobject; X Xextern typeobject Actuatortype; /* Really static, forward */ @@ -113,162 +113,162 @@ Xstatic object *newactuatorobject(); /* Forward */ X X X/* Since we allow different types of members than the functions from -X structmember.c, the memberlist stuff is replicated here. -X (Historically, it originated in this file and later became a generic -X feature.) */ +X structmember.c, the memberlist stuff is replicated here. +X (Historically, it originated in this file and later became a generic +X feature.) */ X X/* An array of memberlist structures defines the name, type and offset -X of selected members of a C structure. These can be read by -X panel_getmember() and set by panel_setmember() (except if their -X READONLY flag is set). The array must be terminated with an entry -X whose name pointer is NULL. */ +X of selected members of a C structure. These can be read by +X panel_getmember() and set by panel_setmember() (except if their +X READONLY flag is set). The array must be terminated with an entry +X whose name pointer is NULL. */ X Xstruct memberlist { -X char *name; -X int type; -X int offset; -X int readonly; +X char *name; +X int type; +X int offset; +X int readonly; X}; X X/* Types */ -X#define T_SHORT 0 -X#define T_DEVICE T_SHORT -X#define T_LONG 1 -X#define T_INT T_LONG -X#define T_BOOL T_LONG -X#define T_FLOAT 2 -X#define T_COORD T_FLOAT -X#define T_STRING 3 -X#define T_FUNC 4 -X#define T_ACTUATOR 5 +X#define T_SHORT 0 +X#define T_DEVICE T_SHORT +X#define T_LONG 1 +X#define T_INT T_LONG +X#define T_BOOL T_LONG +X#define T_FLOAT 2 +X#define T_COORD T_FLOAT +X#define T_STRING 3 +X#define T_FUNC 4 +X#define T_ACTUATOR 5 X X/* Readonly flag */ -X#define READONLY 1 -X#define RO READONLY /* Shorthand */ +X#define READONLY 1 +X#define RO READONLY /* Shorthand */ X Xstatic object * Xpanel_getmember(addr, mlist, name) -X char *addr; -X struct memberlist *mlist; -X char *name; +X char *addr; +X struct memberlist *mlist; +X char *name; X{ -X object *v; -X register struct memberlist *l; -X -X for (l = mlist; l->name != NULL; l++) { -X if (strcmp(l->name, name) == 0) { -X addr += l->offset; -X switch (l->type) { -X case T_SHORT: -X v = newintobject((long) *(short*)addr); -X break; -X case T_LONG: -X v = newintobject(*(long*)addr); -X break; -X case T_FLOAT: -X v = newfloatobject(*(float*)addr); -X break; -X case T_STRING: -X if (*(char**)addr == NULL) { -X INCREF(None); -X v = None; -X } -X else -X v = newstringobject(*(char**)addr); -X break; -X case T_ACTUATOR: -X v = newactuatorobject(*(Actuator**)addr); -X break; -X default: -X err_badarg(); -X v = NULL; -X } -X return v; -X } -X } -X err_setstr(NameError, name); -X return NULL; +X object *v; +X register struct memberlist *l; +X +X for (l = mlist; l->name != NULL; l++) { +X if (strcmp(l->name, name) == 0) { +X addr += l->offset; +X switch (l->type) { +X case T_SHORT: +X v = newintobject((long) *(short*)addr); +X break; +X case T_LONG: +X v = newintobject(*(long*)addr); +X break; +X case T_FLOAT: +X v = newfloatobject(*(float*)addr); +X break; +X case T_STRING: +X if (*(char**)addr == NULL) { +X INCREF(None); +X v = None; +X } +X else +X v = newstringobject(*(char**)addr); +X break; +X case T_ACTUATOR: +X v = newactuatorobject(*(Actuator**)addr); +X break; +X default: +X err_badarg(); +X v = NULL; +X } +X return v; +X } +X } +X err_setstr(NameError, name); +X return NULL; X} X -X/* Attempt to set a member. Return: 0 if OK; 1 if not found; -1 if error */ +X/* Attempt to set a member. Return: 0 if OK; 1 if not found; -1 if error */ X Xstatic int Xpanel_setmember(addr, mlist, name, v) -X char *addr; -X struct memberlist *mlist; -X char *name; -X object *v; +X char *addr; +X struct memberlist *mlist; +X char *name; +X object *v; X{ -X register struct memberlist *l; -X -X for (l = mlist; l->name != NULL; l++) { -X if (strcmp(l->name, name) == 0) { -X if (l->readonly) { -X err_setstr(TypeError, "read-only member"); -X return -1; -X } -X addr += l->offset; -X switch (l->type) { -X case T_SHORT: -X if (!is_intobject(v)) { -X err_setstr(TypeError, "int expected"); -X return -1; -X } -X *(short*)addr = getintvalue(v); -X break; -X case T_LONG: -X if (!is_intobject(v)) { -X err_setstr(TypeError, "int expected"); -X return -1; -X } -X *(long*)addr = getintvalue(v); -X break; -X case T_FLOAT: -X if (is_intobject(v)) -X *(float*)addr = getintvalue(v); -X else if (is_floatobject(v)) -X *(float*)addr = getfloatvalue(v); -X else { -X err_setstr(TypeError,"float expected"); -X return -1; -X } -X break; -X case T_STRING: -X /* XXX Should free(*(char**)addr) here -X but it's dangerous since we don't know -X if we set the label ourselves */ -X if (v == None) -X *(char**)addr = NULL; -X else if (!is_stringobject(v)) { -X err_setstr(TypeError, -X "string expected"); -X return -1; -X } -X else -X *(char**)addr = -X strdup(getstringvalue(v)); -X break; -X case T_ACTUATOR: -X if (v == None) -X *(Actuator**)addr = NULL; -X else if (!is_actuatorobject(v)) { -X err_setstr(TypeError, -X "actuator expected"); -X return -1; -X } -X else -X *(Actuator**)addr = -X ((actuatorobject *)v)->ob_actuator; -X break; -X default: -X err_setstr(SystemError, "unknown member type"); -X return -1; -X } -X return 0; /* Found it */ -X } -X } -X -X return 1; /* Not found */ +X register struct memberlist *l; +X +X for (l = mlist; l->name != NULL; l++) { +X if (strcmp(l->name, name) == 0) { +X if (l->readonly) { +X err_setstr(TypeError, "read-only member"); +X return -1; +X } +X addr += l->offset; +X switch (l->type) { +X case T_SHORT: +X if (!is_intobject(v)) { +X err_setstr(TypeError, "int expected"); +X return -1; +X } +X *(short*)addr = getintvalue(v); +X break; +X case T_LONG: +X if (!is_intobject(v)) { +X err_setstr(TypeError, "int expected"); +X return -1; +X } +X *(long*)addr = getintvalue(v); +X break; +X case T_FLOAT: +X if (is_intobject(v)) +X *(float*)addr = getintvalue(v); +X else if (is_floatobject(v)) +X *(float*)addr = getfloatvalue(v); +X else { +X err_setstr(TypeError,"float expected"); +X return -1; +X } +X break; +X case T_STRING: +X /* XXX Should free(*(char**)addr) here +X but it's dangerous since we don't know +X if we set the label ourselves */ +X if (v == None) +X *(char**)addr = NULL; +X else if (!is_stringobject(v)) { +X err_setstr(TypeError, +X "string expected"); +X return -1; +X } +X else +X *(char**)addr = +X strdup(getstringvalue(v)); +X break; +X case T_ACTUATOR: +X if (v == None) +X *(Actuator**)addr = NULL; +X else if (!is_actuatorobject(v)) { +X err_setstr(TypeError, +X "actuator expected"); +X return -1; +X } +X else +X *(Actuator**)addr = +X ((actuatorobject *)v)->ob_actuator; +X break; +X default: +X err_setstr(SystemError, "unknown member type"); +X return -1; +X } +X return 0; /* Found it */ +X } +X } +X +X return 1; /* Not found */ X} X X @@ -276,84 +276,84 @@ X/* Panel object methods */ X Xstatic object * Xpanel_addpanel(self, args) -X panelobject *self; -X object *args; +X panelobject *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X pnl_addpanel(self->ob_panel); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X pnl_addpanel(self->ob_panel); +X INCREF(None); +X return None; X} X Xstatic object * Xpanel_endgroup(self, args) -X panelobject *self; -X object *args; +X panelobject *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X pnl_endgroup(self->ob_panel); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X pnl_endgroup(self->ob_panel); +X INCREF(None); +X return None; X} X Xstatic object * Xpanel_fixpanel(self, args) -X panelobject *self; -X object *args; +X panelobject *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X pnl_fixpanel(self->ob_panel); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X pnl_fixpanel(self->ob_panel); +X INCREF(None); +X return None; X} X Xstatic object * Xpanel_strwidth(self, args) -X panelobject *self; -X object *args; +X panelobject *self; +X object *args; X{ -X object *v; -X double width; -X if (!getstrarg(args, &v)) -X return NULL; -X width = pnl_strwidth(self->ob_panel, getstringvalue(v)); -X return newfloatobject(width); +X object *v; +X double width; +X if (!getstrarg(args, &v)) +X return NULL; +X width = pnl_strwidth(self->ob_panel, getstringvalue(v)); +X return newfloatobject(width); X} X Xstatic struct methodlist panel_methods[] = { -X {"addpanel", panel_addpanel}, -X {"endgroup", panel_endgroup}, -X {"fixpanel", panel_fixpanel}, -X {"strwidth", panel_strwidth}, -X {NULL, NULL} /* sentinel */ +X {"addpanel", panel_addpanel}, +X {"endgroup", panel_endgroup}, +X {"fixpanel", panel_fixpanel}, +X {"strwidth", panel_strwidth}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xnewpanelobject() X{ -X panelobject *p; -X p = NEWOBJ(panelobject, &Paneltype); -X if (p == NULL) -X return NULL; -X p->ob_panel = pnl_mkpanel(); -X if ((p->ob_paneldict = newdictobject()) == NULL) { -X DECREF(p); -X return NULL; -X } -X return (object *)p; +X panelobject *p; +X p = NEWOBJ(panelobject, &Paneltype); +X if (p == NULL) +X return NULL; +X p->ob_panel = pnl_mkpanel(); +X if ((p->ob_paneldict = newdictobject()) == NULL) { +X DECREF(p); +X return NULL; +X } +X return (object *)p; X} X Xstatic void Xpanel_dealloc(p) -X panelobject *p; +X panelobject *p; X{ -X pnl_delpanel(p->ob_panel); -X if (p->ob_paneldict != NULL) -X DECREF(p->ob_paneldict); -X DEL(p); +X pnl_delpanel(p->ob_panel); +X if (p->ob_paneldict != NULL) +X DECREF(p->ob_paneldict); +X DEL(p); X} X X @@ -362,285 +362,285 @@ X X#define PANOFF(member) offsetof(Panel, member) X Xstatic struct memberlist panel_memberlist[] = { -X {"id", T_SHORT, PANOFF(id), READONLY}, -X {"a", T_ACTUATOR, PANOFF(a), READONLY}, -X {"al", T_ACTUATOR, PANOFF(al), READONLY}, -X {"lastgroup", T_ACTUATOR, PANOFF(lastgroup), READONLY}, -X -X {"active", T_BOOL, PANOFF(active)}, -X {"selectable", T_BOOL, PANOFF(selectable)}, -X -X {"x", T_LONG, PANOFF(x)}, -X {"y", T_LONG, PANOFF(y)}, -X {"w", T_LONG, PANOFF(w)}, -X {"h", T_LONG, PANOFF(h)}, -X -X {"minx", T_COORD, PANOFF(minx)}, -X {"maxx", T_COORD, PANOFF(maxx)}, -X {"miny", T_COORD, PANOFF(miny)}, -X {"maxy", T_COORD, PANOFF(maxy)}, -X -X {"cw", T_COORD, PANOFF(cw)}, -X {"ch", T_COORD, PANOFF(ch)}, -X -X {"gid", T_LONG, PANOFF(gid), READONLY}, -X {"usergid", T_LONG, PANOFF(usergid), READONLY}, -X -X {"vobj", T_LONG, PANOFF(vobj), READONLY}, -X {"ppu", T_FLOAT, PANOFF(ppu)}, -X -X {"label", T_STRING, PANOFF(label)}, -X -X /* Panel callbacks are not supported */ -X -X {"visible", T_BOOL, PANOFF(visible)}, -X {"somedirty", T_INT, PANOFF(somedirty)}, -X {"dirtycnt", T_INT, PANOFF(dirtycnt)}, -X -X /* T_PANEL is not supported */ -X /* -X {"next", T_PANEL, PANOFF(next), READONLY}, -X */ -X -X {NULL, 0, 0} /* Sentinel */ +X {"id", T_SHORT, PANOFF(id), READONLY}, +X {"a", T_ACTUATOR, PANOFF(a), READONLY}, +X {"al", T_ACTUATOR, PANOFF(al), READONLY}, +X {"lastgroup", T_ACTUATOR, PANOFF(lastgroup), READONLY}, +X +X {"active", T_BOOL, PANOFF(active)}, +X {"selectable", T_BOOL, PANOFF(selectable)}, +X +X {"x", T_LONG, PANOFF(x)}, +X {"y", T_LONG, PANOFF(y)}, +X {"w", T_LONG, PANOFF(w)}, +X {"h", T_LONG, PANOFF(h)}, +X +X {"minx", T_COORD, PANOFF(minx)}, +X {"maxx", T_COORD, PANOFF(maxx)}, +X {"miny", T_COORD, PANOFF(miny)}, +X {"maxy", T_COORD, PANOFF(maxy)}, +X +X {"cw", T_COORD, PANOFF(cw)}, +X {"ch", T_COORD, PANOFF(ch)}, +X +X {"gid", T_LONG, PANOFF(gid), READONLY}, +X {"usergid", T_LONG, PANOFF(usergid), READONLY}, +X +X {"vobj", T_LONG, PANOFF(vobj), READONLY}, +X {"ppu", T_FLOAT, PANOFF(ppu)}, +X +X {"label", T_STRING, PANOFF(label)}, +X +X /* Panel callbacks are not supported */ +X +X {"visible", T_BOOL, PANOFF(visible)}, +X {"somedirty", T_INT, PANOFF(somedirty)}, +X {"dirtycnt", T_INT, PANOFF(dirtycnt)}, +X +X /* T_PANEL is not supported */ +X /* +X {"next", T_PANEL, PANOFF(next), READONLY}, +X */ +X +X {NULL, 0, 0} /* Sentinel */ X}; X Xstatic object * Xpanel_getattr(p, name) -X panelobject *p; -X char *name; +X panelobject *p; +X char *name; X{ -X object *v; -X -X v = dictlookup(p->ob_paneldict, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X -X v = findmethod(panel_methods, (object *)p, name); -X if (v != NULL) -X return v; -X err_clear(); -X return panel_getmember((char *)p->ob_panel, panel_memberlist, name); +X object *v; +X +X v = dictlookup(p->ob_paneldict, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X +X v = findmethod(panel_methods, (object *)p, name); +X if (v != NULL) +X return v; +X err_clear(); +X return panel_getmember((char *)p->ob_panel, panel_memberlist, name); X} X Xstatic int Xpanel_setattr(p, name, v) -X panelobject *p; -X char *name; -X object *v; +X panelobject *p; +X char *name; +X object *v; X{ -X int err; -X -X /* We don't allow deletion of attributes */ -X if (v == NULL) { -X err_setstr(TypeError, "read-only panel attribute"); -X return -1; -X } -X err = panel_setmember((char *)p->ob_panel, panel_memberlist, name, v); -X if (err != 1) -X return err; -X return dictinsert(p->ob_paneldict, name, v); +X int err; +X +X /* We don't allow deletion of attributes */ +X if (v == NULL) { +X err_setstr(TypeError, "read-only panel attribute"); +X return -1; +X } +X err = panel_setmember((char *)p->ob_panel, panel_memberlist, name, v); +X if (err != 1) +X return err; +X return dictinsert(p->ob_paneldict, name, v); X} X Xstatic typeobject Paneltype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "panel", /*tp_name*/ -X sizeof(panelobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X panel_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X panel_getattr, /*tp_getattr*/ -X panel_setattr, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "panel", /*tp_name*/ +X sizeof(panelobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X panel_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X panel_getattr, /*tp_getattr*/ +X panel_setattr, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; X X X/* Descriptions of actuator-specific data members */ X Xstruct memberlist slider_spec[] = { -X {"mode", T_INT, offsetof(Slider, mode)}, -X {"finefactor", T_FLOAT, offsetof(Slider, finefactor)}, -X {"differentialfactor", -X T_FLOAT, offsetof(Slider, differentialfactor)}, -X {"valsave", T_FLOAT, offsetof(Slider, valsave), RO}, -X {"wsave", T_COORD, offsetof(Slider, wsave)}, -X {"bh", T_COORD, offsetof(Slider, bh)}, -X {NULL} +X {"mode", T_INT, offsetof(Slider, mode)}, +X {"finefactor", T_FLOAT, offsetof(Slider, finefactor)}, +X {"differentialfactor", +X T_FLOAT, offsetof(Slider, differentialfactor)}, +X {"valsave", T_FLOAT, offsetof(Slider, valsave), RO}, +X {"wsave", T_COORD, offsetof(Slider, wsave)}, +X {"bh", T_COORD, offsetof(Slider, bh)}, +X {NULL} X}; X X#define palette_spec slider_spec X Xstruct memberlist puck_spec[] = { -X /* Actuators already have members x and y, so the Puck's x and y -X have different names */ -X {"puck_x", T_FLOAT, offsetof(Puck, x)}, -X {"puck_y", T_FLOAT, offsetof(Puck, y)}, -X {NULL} +X /* Actuators already have members x and y, so the Puck's x and y +X have different names */ +X {"puck_x", T_FLOAT, offsetof(Puck, x)}, +X {"puck_y", T_FLOAT, offsetof(Puck, y)}, +X {NULL} X}; X Xstruct memberlist dial_spec[] = { -X {"mode", T_INT, offsetof(Dial, mode)}, -X {"finefactor", T_FLOAT, offsetof(Dial, finefactor)}, -X {"valsave", T_FLOAT, offsetof(Dial, valsave), RO}, -X {"wsave", T_COORD, offsetof(Dial, wsave)}, -X {"winds", T_FLOAT, offsetof(Dial, winds)}, -X {NULL} +X {"mode", T_INT, offsetof(Dial, mode)}, +X {"finefactor", T_FLOAT, offsetof(Dial, finefactor)}, +X {"valsave", T_FLOAT, offsetof(Dial, valsave), RO}, +X {"wsave", T_COORD, offsetof(Dial, wsave)}, +X {"winds", T_FLOAT, offsetof(Dial, winds)}, +X {NULL} X}; X Xstruct memberlist slideroid_spec[] = { -X {"mode", T_INT, offsetof(Slideroid, mode)}, -X {"finemode", T_BOOL, offsetof(Slideroid, finemode)}, -X {"resetmode", T_BOOL, offsetof(Slideroid, resetmode)}, -X /* XXX Can't do resettarget (pointer to float) */ -X /* XXX This makes resetval pretty useless... */ -X /* -X {"resetval", T_FLOAT, offsetof(Slideroid, resetval)}, -X */ -X {"valsave", T_FLOAT, offsetof(Slideroid, valsave), RO}, -X {"wsave", T_COORD, offsetof(Slideroid, wsave)}, -X {NULL} +X {"mode", T_INT, offsetof(Slideroid, mode)}, +X {"finemode", T_BOOL, offsetof(Slideroid, finemode)}, +X {"resetmode", T_BOOL, offsetof(Slideroid, resetmode)}, +X /* XXX Can't do resettarget (pointer to float) */ +X /* XXX This makes resetval pretty useless... */ +X /* +X {"resetval", T_FLOAT, offsetof(Slideroid, resetval)}, +X */ +X {"valsave", T_FLOAT, offsetof(Slideroid, valsave), RO}, +X {"wsave", T_COORD, offsetof(Slideroid, wsave)}, +X {NULL} X}; X Xstruct memberlist stripchart_spec[] = { -X {"firstpt", T_INT, offsetof(Stripchart, firstpt), RO}, -X {"lastpt", T_INT, offsetof(Stripchart, lastpt), RO}, -X {"Bind_Low", T_BOOL, offsetof(Stripchart, Bind_Low)}, -X {"Bind_High", T_BOOL, offsetof(Stripchart, Bind_High)}, -X /* XXX Can't do y (array of floats) */ -X {"lowlabel", T_ACTUATOR, offsetof(Stripchart, lowlabel), RO}, -X {"highlabel", T_ACTUATOR, offsetof(Stripchart, highlabel), RO}, -X {NULL} +X {"firstpt", T_INT, offsetof(Stripchart, firstpt), RO}, +X {"lastpt", T_INT, offsetof(Stripchart, lastpt), RO}, +X {"Bind_Low", T_BOOL, offsetof(Stripchart, Bind_Low)}, +X {"Bind_High", T_BOOL, offsetof(Stripchart, Bind_High)}, +X /* XXX Can't do y (array of floats) */ +X {"lowlabel", T_ACTUATOR, offsetof(Stripchart, lowlabel), RO}, +X {"highlabel", T_ACTUATOR, offsetof(Stripchart, highlabel), RO}, +X {NULL} X}; X Xstruct memberlist typein_spec[] = { -X /* Note: these should be readonly after the actuator is added -X to a panel */ -X {"str", T_STRING, offsetof(Typein, str)}, -X {"len", T_INT, offsetof(Typein, len)}, -X {NULL} +X /* Note: these should be readonly after the actuator is added +X to a panel */ +X {"str", T_STRING, offsetof(Typein, str)}, +X {"len", T_INT, offsetof(Typein, len)}, +X {NULL} X}; X Xstruct memberlist typeout_spec[] = { -X {"mode", T_INT, offsetof(Typeout, mode)}, -X /* XXX The buffer is managed by the actuator; but how do we -X add text? */ -X {"buf", T_STRING, offsetof(Typeout, buf), READONLY}, -X {"delimstr", T_STRING, offsetof(Typeout, delimstr)}, -X {"start", T_INT, offsetof(Typeout, start)}, -X {"dot", T_INT, offsetof(Typeout, dot)}, -X {"mark", T_INT, offsetof(Typeout, mark)}, -X {"col", T_INT, offsetof(Typeout, col)}, -X {"lin", T_INT, offsetof(Typeout, lin)}, -X {"len", T_INT, offsetof(Typeout, len)}, -X {"size", T_INT, offsetof(Typeout, size)}, -X {NULL} +X {"mode", T_INT, offsetof(Typeout, mode)}, +X /* XXX The buffer is managed by the actuator; but how do we +X add text? */ +X {"buf", T_STRING, offsetof(Typeout, buf), READONLY}, +X {"delimstr", T_STRING, offsetof(Typeout, delimstr)}, +X {"start", T_INT, offsetof(Typeout, start)}, +X {"dot", T_INT, offsetof(Typeout, dot)}, +X {"mark", T_INT, offsetof(Typeout, mark)}, +X {"col", T_INT, offsetof(Typeout, col)}, +X {"lin", T_INT, offsetof(Typeout, lin)}, +X {"len", T_INT, offsetof(Typeout, len)}, +X {"size", T_INT, offsetof(Typeout, size)}, +X {NULL} X}; X Xstruct memberlist mouse_spec[] = { -X /* Actuators already have members x and y, so the Mouse's x and y -X have different names */ -X {"mouse_x", T_FLOAT, offsetof(Mouse, x)}, -X {"mouse_y", T_FLOAT, offsetof(Mouse, y)}, -X {NULL} +X /* Actuators already have members x and y, so the Mouse's x and y +X have different names */ +X {"mouse_x", T_FLOAT, offsetof(Mouse, x)}, +X {"mouse_y", T_FLOAT, offsetof(Mouse, y)}, +X {NULL} X}; X -X#define MULOFF(member) offsetof(Multislider, member) +X#define MULOFF(member) offsetof(Multislider, member) X Xstruct memberlist multislider_spec[] = { -X {"mode", T_INT, MULOFF(mode)}, -X {"n", T_INT, MULOFF(n)}, -X {"finefactor", T_FLOAT, MULOFF(finefactor)}, -X {"wsave", T_COORD, MULOFF(wsave)}, -X {"sa", T_ACTUATOR, MULOFF(sa)}, -X {"bh", T_COORD, MULOFF(bh)}, -X {"clrx", T_COORD, MULOFF(clrx)}, -X {"clry", T_COORD, MULOFF(clry)}, -X {"clrw", T_COORD, MULOFF(clrw)}, -X {"clrh", T_COORD, MULOFF(clrh)}, -X /* XXX acttype? */ -X {NULL} +X {"mode", T_INT, MULOFF(mode)}, +X {"n", T_INT, MULOFF(n)}, +X {"finefactor", T_FLOAT, MULOFF(finefactor)}, +X {"wsave", T_COORD, MULOFF(wsave)}, +X {"sa", T_ACTUATOR, MULOFF(sa)}, +X {"bh", T_COORD, MULOFF(bh)}, +X {"clrx", T_COORD, MULOFF(clrx)}, +X {"clry", T_COORD, MULOFF(clry)}, +X {"clrw", T_COORD, MULOFF(clrw)}, +X {"clrh", T_COORD, MULOFF(clrh)}, +X /* XXX acttype? */ +X {NULL} X}; X X/* XXX Still to do: -X Frame -X Icon -X Cycle -X Scroll -X Menu +X Frame +X Icon +X Cycle +X Scroll +X Menu X*/ X X/* List of known actuator initializer functions */ X Xstruct { -X char *name; -X void (*func)(); -X struct memberlist *spec; +X char *name; +X void (*func)(); +X struct memberlist *spec; X} initializerlist[] = { -X {"analog_bar", pnl_analog_bar}, -X {"analog_meter", pnl_analog_meter}, -X {"button", pnl_button}, -X {"cycle", pnl_cycle}, -X /* Doesn't exist: */ -X/* {"dhslider", pnl_dhslider, slider_spec}, */ -X {"dial", pnl_dial, dial_spec}, -X {"down_arrow_button", pnl_down_arrow_button}, -X {"down_double_arrow_button", pnl_down_double_arrow_button}, -X {"dvslider", pnl_dvslider, slider_spec}, -X {"filled_hslider", pnl_filled_hslider, slider_spec}, -X {"filled_slider", pnl_filled_slider, slider_spec}, -X {"filled_vslider", pnl_filled_vslider, slider_spec}, -X {"floating_puck", pnl_floating_puck, puck_spec}, -X {"frame", pnl_frame}, -X {"graphframe", pnl_graphframe}, -X {"hmultislider", pnl_hmultislider, multislider_spec}, -X {"hmultislider_bar", pnl_hmultislider_bar}, -X {"hmultislider_open_bar", pnl_hmultislider_open_bar}, -X {"hpalette", pnl_hpalette, palette_spec}, -X {"hslider", pnl_hslider, slider_spec}, -X {"icon", pnl_icon}, -X {"icon_menu", pnl_icon_menu}, -X {"label", pnl_label}, -X {"left_arrow_button", pnl_left_arrow_button}, -X {"left_double_arrow_button", pnl_left_double_arrow_button}, -X {"menu", pnl_menu}, -X {"menu_item", pnl_menu_item}, -X {"meter", pnl_meter}, -X {"mouse", pnl_mouse, mouse_spec}, -X {"multislider", pnl_multislider, multislider_spec}, -X {"multislider_bar", pnl_multislider_bar}, -X {"multislider_open_bar", pnl_multislider_open_bar}, -X {"palette", pnl_palette, palette_spec}, -X {"puck", pnl_puck, puck_spec}, -X {"radio_button", pnl_radio_button}, -X {"radio_check_button", pnl_radio_check_button}, -X {"right_arrow_button", pnl_right_arrow_button}, -X {"right_double_arrow_button", pnl_right_double_arrow_button}, -X {"rubber_puck", pnl_rubber_puck, puck_spec}, -X {"scale_chart", pnl_scale_chart, stripchart_spec}, -X {"scroll", pnl_scroll}, -X {"signal", pnl_signal}, -X {"slider", pnl_slider, slider_spec}, -X {"slideroid", pnl_slideroid, slideroid_spec}, -X {"strip_chart", pnl_strip_chart, stripchart_spec}, -X {"sub_menu", pnl_sub_menu}, -X {"toggle_button", pnl_toggle_button}, -X {"typein", pnl_typein, typein_spec}, -X {"typeout", pnl_typeout, typeout_spec}, -X {"up_arrow_button", pnl_up_arrow_button}, -X {"up_double_arrow_button", pnl_up_double_arrow_button}, -X {"viewframe", pnl_viewframe}, -X {"vmultislider", pnl_vmultislider, multislider_spec}, -X {"vmultislider_bar", pnl_vmultislider_bar}, -X {"vmultislider_open_bar", pnl_vmultislider_open_bar}, -X {"vpalette", pnl_vpalette, palette_spec}, -X {"vslider", pnl_vslider, slider_spec}, -X {"wide_button", pnl_wide_button}, -X {NULL, NULL} /* Sentinel */ +X {"analog_bar", pnl_analog_bar}, +X {"analog_meter", pnl_analog_meter}, +X {"button", pnl_button}, +X {"cycle", pnl_cycle}, +X /* Doesn't exist: */ +X/* {"dhslider", pnl_dhslider, slider_spec}, */ +X {"dial", pnl_dial, dial_spec}, +X {"down_arrow_button", pnl_down_arrow_button}, +X {"down_double_arrow_button", pnl_down_double_arrow_button}, +X {"dvslider", pnl_dvslider, slider_spec}, +X {"filled_hslider", pnl_filled_hslider, slider_spec}, +X {"filled_slider", pnl_filled_slider, slider_spec}, +X {"filled_vslider", pnl_filled_vslider, slider_spec}, +X {"floating_puck", pnl_floating_puck, puck_spec}, +X {"frame", pnl_frame}, +X {"graphframe", pnl_graphframe}, +X {"hmultislider", pnl_hmultislider, multislider_spec}, +X {"hmultislider_bar", pnl_hmultislider_bar}, +X {"hmultislider_open_bar", pnl_hmultislider_open_bar}, +X {"hpalette", pnl_hpalette, palette_spec}, +X {"hslider", pnl_hslider, slider_spec}, +X {"icon", pnl_icon}, +X {"icon_menu", pnl_icon_menu}, +X {"label", pnl_label}, +X {"left_arrow_button", pnl_left_arrow_button}, +X {"left_double_arrow_button", pnl_left_double_arrow_button}, +X {"menu", pnl_menu}, +X {"menu_item", pnl_menu_item}, +X {"meter", pnl_meter}, +X {"mouse", pnl_mouse, mouse_spec}, +X {"multislider", pnl_multislider, multislider_spec}, +X {"multislider_bar", pnl_multislider_bar}, +X {"multislider_open_bar", pnl_multislider_open_bar}, +X {"palette", pnl_palette, palette_spec}, +X {"puck", pnl_puck, puck_spec}, +X {"radio_button", pnl_radio_button}, +X {"radio_check_button", pnl_radio_check_button}, +X {"right_arrow_button", pnl_right_arrow_button}, +X {"right_double_arrow_button", pnl_right_double_arrow_button}, +X {"rubber_puck", pnl_rubber_puck, puck_spec}, +X {"scale_chart", pnl_scale_chart, stripchart_spec}, +X {"scroll", pnl_scroll}, +X {"signal", pnl_signal}, +X {"slider", pnl_slider, slider_spec}, +X {"slideroid", pnl_slideroid, slideroid_spec}, +X {"strip_chart", pnl_strip_chart, stripchart_spec}, +X {"sub_menu", pnl_sub_menu}, +X {"toggle_button", pnl_toggle_button}, +X {"typein", pnl_typein, typein_spec}, +X {"typeout", pnl_typeout, typeout_spec}, +X {"up_arrow_button", pnl_up_arrow_button}, +X {"up_double_arrow_button", pnl_up_double_arrow_button}, +X {"viewframe", pnl_viewframe}, +X {"vmultislider", pnl_vmultislider, multislider_spec}, +X {"vmultislider_bar", pnl_vmultislider_bar}, +X {"vmultislider_open_bar", pnl_vmultislider_open_bar}, +X {"vpalette", pnl_vpalette, palette_spec}, +X {"vslider", pnl_vslider, slider_spec}, +X {"wide_button", pnl_wide_button}, +X {NULL, NULL} /* Sentinel */ X}; X X @@ -650,34 +650,34 @@ Xstatic Actuator *down_pend, *active_pend, *up_pend; X Xstatic void Xdownfunc(a) -X Actuator *a; +X Actuator *a; X{ -X if (down_pend == NULL) -X down_pend = a; +X if (down_pend == NULL) +X down_pend = a; X} X Xstatic void Xactivefunc(a) -X Actuator *a; +X Actuator *a; X{ -X if (active_pend == NULL) -X active_pend = a; +X if (active_pend == NULL) +X active_pend = a; X} X Xstatic void Xupfunc(a) -X Actuator *a; +X Actuator *a; X{ -X if (up_pend == NULL) -X up_pend = a; +X if (up_pend == NULL) +X up_pend = a; X} X X X/* Lay-out for the user data */ X Xstruct userdata { -X object *dict; /* Dictionary object for additional attributes */ -X struct memberlist *spec; /* Actuator-specific members */ +X object *dict; /* Dictionary object for additional attributes */ +X struct memberlist *spec; /* Actuator-specific members */ X}; X X @@ -685,35 +685,35 @@ X/* Create a new actuator; the actuator type is given as a string */ X Xstatic Actuator * Xmakeactuator(name) -X char *name; +X char *name; X{ -X Actuator *act; -X void (*initializer)() = NULL; -X int i; -X struct userdata *u; -X for (i = 0; initializerlist[i].name != NULL; i++) { -X if (strcmp(initializerlist[i].name, name) == 0) { -X initializer = initializerlist[i].func; -X break; -X } -X } -X if (initializerlist[i].name == NULL) { -X err_badarg(); -X return NULL; -X } -X u = NEW(struct userdata, 1); -X if (u == NULL) { -X err_nomem(); -X return NULL; -X } -X u->dict = NULL; -X u->spec = initializerlist[i].spec; -X act = pnl_mkact(initializer); -X act->u = (char *)u; -X act->downfunc = downfunc; -X act->activefunc = activefunc; -X act->upfunc = upfunc; -X return act; +X Actuator *act; +X void (*initializer)() = NULL; +X int i; +X struct userdata *u; +X for (i = 0; initializerlist[i].name != NULL; i++) { +X if (strcmp(initializerlist[i].name, name) == 0) { +X initializer = initializerlist[i].func; +X break; +X } +X } +X if (initializerlist[i].name == NULL) { +X err_badarg(); +X return NULL; +X } +X u = NEW(struct userdata, 1); +X if (u == NULL) { +X err_nomem(); +X return NULL; +X } +X u->dict = NULL; +X u->spec = initializerlist[i].spec; +X act = pnl_mkact(initializer); +X act->u = (char *)u; +X act->downfunc = downfunc; +X act->activefunc = activefunc; +X act->upfunc = upfunc; +X return act; X} X X @@ -721,114 +721,114 @@ X/* Actuator objects methods */ X Xstatic object * Xactuator_addact(self, args) -X actuatorobject *self; -X object *args; +X actuatorobject *self; +X object *args; X{ -X Panel *p; -X if (!is_panelobject(args)) { -X err_badarg(); -X return NULL; -X } -X p = ((panelobject *)args) -> ob_panel; -X pnl_addact(self->ob_actuator, p); -X INCREF(None); -X return None; +X Panel *p; +X if (!is_panelobject(args)) { +X err_badarg(); +X return NULL; +X } +X p = ((panelobject *)args) -> ob_panel; +X pnl_addact(self->ob_actuator, p); +X INCREF(None); +X return None; X} X Xstatic object * Xactuator_addsubact(self, args) -X actuatorobject *self; -X object *args; +X actuatorobject *self; +X object *args; X{ -X Actuator *a; -X if (!is_actuatorobject(args)) { -X err_badarg(); -X return NULL; -X } -X a = ((actuatorobject *)args) -> ob_actuator; -X pnl_addsubact(self->ob_actuator, a); -X INCREF(None); -X return None; +X Actuator *a; +X if (!is_actuatorobject(args)) { +X err_badarg(); +X return NULL; +X } +X a = ((actuatorobject *)args) -> ob_actuator; +X pnl_addsubact(self->ob_actuator, a); +X INCREF(None); +X return None; X} X Xstatic object * Xactuator_delact(self, args) -X actuatorobject *self; -X object *args; +X actuatorobject *self; +X object *args; X{ -X Panel *p; -X if (!getnoarg(args)) -X return NULL; -X pnl_delact(self->ob_actuator); -X INCREF(None); -X return None; +X Panel *p; +X if (!getnoarg(args)) +X return NULL; +X pnl_delact(self->ob_actuator); +X INCREF(None); +X return None; X} X Xstatic object * Xactuator_fixact(self, args) -X actuatorobject *self; -X object *args; +X actuatorobject *self; +X object *args; X{ -X Panel *p; -X if (!getnoarg(args)) -X return NULL; -X pnl_fixact(self->ob_actuator); -X INCREF(None); -X return None; +X Panel *p; +X if (!getnoarg(args)) +X return NULL; +X pnl_fixact(self->ob_actuator); +X INCREF(None); +X return None; X} X Xstatic object * Xactuator_tprint(self, args) -X actuatorobject *self; -X object *args; +X actuatorobject *self; +X object *args; X{ -X object *str; -X if (self->ob_actuator->type != PNL_TYPEOUT) { -X err_setstr(TypeError, "tprint for non-typeout panel"); -X return NULL; -X } -X if (!getstrarg(args, &str)) -X return NULL; -X tprint(self->ob_actuator, getstringvalue(str)); -X /* XXX Can't turn tprint's errors into exceptions, sorry */ -X INCREF(None); -X return None; +X object *str; +X if (self->ob_actuator->type != PNL_TYPEOUT) { +X err_setstr(TypeError, "tprint for non-typeout panel"); +X return NULL; +X } +X if (!getstrarg(args, &str)) +X return NULL; +X tprint(self->ob_actuator, getstringvalue(str)); +X /* XXX Can't turn tprint's errors into exceptions, sorry */ +X INCREF(None); +X return None; X} X Xstatic struct methodlist actuator_methods[] = { -X {"addact", actuator_addact}, -X {"addsubact", actuator_addsubact}, -X {"delact", actuator_delact}, -X {"fixact", actuator_fixact}, -X {"tprint", actuator_tprint}, -X {NULL, NULL} /* sentinel */ +X {"addact", actuator_addact}, +X {"addsubact", actuator_addsubact}, +X {"delact", actuator_delact}, +X {"fixact", actuator_fixact}, +X {"tprint", actuator_tprint}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xnewactuatorobject(act) -X Actuator *act; +X Actuator *act; X{ -X actuatorobject *a; -X if (act == NULL) { -X INCREF(None); -X return None; -X } -X a = NEWOBJ(actuatorobject, &Actuatortype); -X if (a == NULL) -X return NULL; -X a->ob_actuator = act; -X return (object *)a; +X actuatorobject *a; +X if (act == NULL) { +X INCREF(None); +X return None; +X } +X a = NEWOBJ(actuatorobject, &Actuatortype); +X if (a == NULL) +X return NULL; +X a->ob_actuator = act; +X return (object *)a; X} X Xstatic void Xactuator_dealloc(a) -X actuatorobject *a; +X actuatorobject *a; X{ -X /* Do NOT delete the actuator; most actuator objects are created -X to hold a temporary reference to an actuator, like one gotten -X from pnl_dopanel(). */ -X -X DEL(a); +X /* Do NOT delete the actuator; most actuator objects are created +X to hold a temporary reference to an actuator, like one gotten +X from pnl_dopanel(). */ +X +X DEL(a); X} X X @@ -837,167 +837,167 @@ X X#define ACTOFF(member) offsetof(Actuator, member) X Xstruct memberlist act_memberlist[] = { -X {"id", T_SHORT, ACTOFF(id), READONLY}, -X -X /* T_PANEL is not defined */ -X /* -X {"p", T_PANEL, ACTOFF(p), READONLY}, -X */ -X -X {"pa", T_ACTUATOR, ACTOFF(pa), READONLY}, -X {"ca", T_ACTUATOR, ACTOFF(ca), READONLY}, -X {"al", T_ACTUATOR, ACTOFF(al), READONLY}, -X {"na", T_INT, ACTOFF(na), READONLY}, -X {"type", T_INT, ACTOFF(type), READONLY}, -X {"active", T_BOOL, ACTOFF(active)}, -X -X {"x", T_COORD, ACTOFF(x)}, -X {"y", T_COORD, ACTOFF(y)}, -X {"w", T_COORD, ACTOFF(w)}, -X {"h", T_COORD, ACTOFF(h)}, -X -X {"lx", T_COORD, ACTOFF(lx)}, -X {"ly", T_COORD, ACTOFF(ly)}, -X {"lw", T_COORD, ACTOFF(lw)}, -X {"lh", T_COORD, ACTOFF(lh)}, -X {"ld", T_COORD, ACTOFF(ld)}, -X -X {"val", T_FLOAT, ACTOFF(val)}, -X {"extval", T_FLOAT, ACTOFF(extval)}, -X {"initval", T_FLOAT, ACTOFF(initval)}, -X {"maxval", T_FLOAT, ACTOFF(maxval)}, -X {"minval", T_FLOAT, ACTOFF(minval)}, -X {"scalefactor", T_FLOAT, ACTOFF(scalefactor)}, -X -X {"label", T_STRING, ACTOFF(label)}, -X {"key", T_DEVICE, ACTOFF(key)}, -X {"labeltype", T_INT, ACTOFF(labeltype)}, -X -X /* Internal callbacks are not supported; -X user callbacks are treated special! */ -X -X {"dirtycnt", T_INT, ACTOFF(dirtycnt)}, -X -X /* members u and data are accessed differently */ -X -X {"automatic", T_BOOL, ACTOFF(automatic)}, -X {"selectable", T_BOOL, ACTOFF(selectable)}, -X {"visible", T_BOOL, ACTOFF(visible)}, -X {"beveled", T_BOOL, ACTOFF(beveled)}, -X -X {"group", T_ACTUATOR, ACTOFF(group), READONLY}, -X {"next", T_ACTUATOR, ACTOFF(next), READONLY}, -X -X {NULL, 0, 0} /* Sentinel */ +X {"id", T_SHORT, ACTOFF(id), READONLY}, +X +X /* T_PANEL is not defined */ +X /* +X {"p", T_PANEL, ACTOFF(p), READONLY}, +X */ +X +X {"pa", T_ACTUATOR, ACTOFF(pa), READONLY}, +X {"ca", T_ACTUATOR, ACTOFF(ca), READONLY}, +X {"al", T_ACTUATOR, ACTOFF(al), READONLY}, +X {"na", T_INT, ACTOFF(na), READONLY}, +X {"type", T_INT, ACTOFF(type), READONLY}, +X {"active", T_BOOL, ACTOFF(active)}, +X +X {"x", T_COORD, ACTOFF(x)}, +X {"y", T_COORD, ACTOFF(y)}, +X {"w", T_COORD, ACTOFF(w)}, +X {"h", T_COORD, ACTOFF(h)}, +X +X {"lx", T_COORD, ACTOFF(lx)}, +X {"ly", T_COORD, ACTOFF(ly)}, +X {"lw", T_COORD, ACTOFF(lw)}, +X {"lh", T_COORD, ACTOFF(lh)}, +X {"ld", T_COORD, ACTOFF(ld)}, +X +X {"val", T_FLOAT, ACTOFF(val)}, +X {"extval", T_FLOAT, ACTOFF(extval)}, +X {"initval", T_FLOAT, ACTOFF(initval)}, +X {"maxval", T_FLOAT, ACTOFF(maxval)}, +X {"minval", T_FLOAT, ACTOFF(minval)}, +X {"scalefactor", T_FLOAT, ACTOFF(scalefactor)}, +X +X {"label", T_STRING, ACTOFF(label)}, +X {"key", T_DEVICE, ACTOFF(key)}, +X {"labeltype", T_INT, ACTOFF(labeltype)}, +X +X /* Internal callbacks are not supported; +X user callbacks are treated special! */ +X +X {"dirtycnt", T_INT, ACTOFF(dirtycnt)}, +X +X /* members u and data are accessed differently */ +X +X {"automatic", T_BOOL, ACTOFF(automatic)}, +X {"selectable", T_BOOL, ACTOFF(selectable)}, +X {"visible", T_BOOL, ACTOFF(visible)}, +X {"beveled", T_BOOL, ACTOFF(beveled)}, +X +X {"group", T_ACTUATOR, ACTOFF(group), READONLY}, +X {"next", T_ACTUATOR, ACTOFF(next), READONLY}, +X +X {NULL, 0, 0} /* Sentinel */ X}; X X X/* Potential name conflicts between attributes are solved as follows. -X - Actuator-specific attributes always override generic attributes. -X - When reading, the dictionary has overrides everything else; -X when writing, everything else overrides the dictionary. -X - When reading, methods are tried last. +X - Actuator-specific attributes always override generic attributes. +X - When reading, the dictionary has overrides everything else; +X when writing, everything else overrides the dictionary. +X - When reading, methods are tried last. X*/ X Xstatic object * Xactuator_getattr(a, name) -X actuatorobject *a; -X char *name; +X actuatorobject *a; +X char *name; X{ -X Actuator *act = a->ob_actuator; -X struct userdata *u = (struct userdata *) act->u; -X object *v; -X -X if (u != NULL) { -X /* 1. Try the dictionary */ -X if (u->dict != NULL) { -X v = dictlookup(u->dict, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X } -X -X /* 2. Try actuator-specific attributes */ -X if (u->spec != NULL) { -X v = panel_getmember(act->data, u->spec, name); -X if (v != NULL) -X return v; -X err_clear(); -X } -X } -X -X /* 3. Try generic actuator attributes */ -X v = panel_getmember((char *)act, act_memberlist, name); -X if (v != NULL) -X return v; -X -X /* 4. Try methods */ -X err_clear(); -X return findmethod(actuator_methods, (object *)a, name); +X Actuator *act = a->ob_actuator; +X struct userdata *u = (struct userdata *) act->u; +X object *v; +X +X if (u != NULL) { +X /* 1. Try the dictionary */ +X if (u->dict != NULL) { +X v = dictlookup(u->dict, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X } +X +X /* 2. Try actuator-specific attributes */ +X if (u->spec != NULL) { +X v = panel_getmember(act->data, u->spec, name); +X if (v != NULL) +X return v; +X err_clear(); +X } +X } +X +X /* 3. Try generic actuator attributes */ +X v = panel_getmember((char *)act, act_memberlist, name); +X if (v != NULL) +X return v; +X +X /* 4. Try methods */ +X err_clear(); +X return findmethod(actuator_methods, (object *)a, name); X} X Xstatic int Xactuator_setattr(a, name, v) -X actuatorobject *a; -X char *name; -X object *v; +X actuatorobject *a; +X char *name; +X object *v; X{ -X Actuator *act = a->ob_actuator; -X struct userdata *u = (struct userdata *) act->u; -X int err; -X -X /* 0. We don't allow deletion of attributes */ -X if (v == NULL) { -X err_setstr(TypeError, "read-only actuator attribute"); -X return -1; -X } -X -X /* 1. Try actuator-specific attributes */ -X if (u != NULL && u->spec != NULL) { -X err = panel_setmember(act->data, u->spec, name, v); -X if (err != 1) -X return err; -X } -X -X /* 2. Try generic actuator attributes */ -X err = panel_setmember((char *)act, act_memberlist, name, v); -X if (err != 1) -X return err; -X -X /* 3. Try the dictionary */ -X if (u != NULL) { -X if (u->dict == NULL && (u->dict = newdictobject()) == NULL) -X return NULL; -X return dictinsert(u->dict, name, v); -X } -X -X err_setstr(NameError, name); -X return -1; +X Actuator *act = a->ob_actuator; +X struct userdata *u = (struct userdata *) act->u; +X int err; +X +X /* 0. We don't allow deletion of attributes */ +X if (v == NULL) { +X err_setstr(TypeError, "read-only actuator attribute"); +X return -1; +X } +X +X /* 1. Try actuator-specific attributes */ +X if (u != NULL && u->spec != NULL) { +X err = panel_setmember(act->data, u->spec, name, v); +X if (err != 1) +X return err; +X } +X +X /* 2. Try generic actuator attributes */ +X err = panel_setmember((char *)act, act_memberlist, name, v); +X if (err != 1) +X return err; +X +X /* 3. Try the dictionary */ +X if (u != NULL) { +X if (u->dict == NULL && (u->dict = newdictobject()) == NULL) +X return NULL; +X return dictinsert(u->dict, name, v); +X } +X +X err_setstr(NameError, name); +X return -1; X} X Xstatic int Xactuator_compare(v, w) -X actuatorobject *v, *w; +X actuatorobject *v, *w; X{ -X long i = (long)v->ob_actuator; -X long j = (long)w->ob_actuator; -X return (i < j) ? -1 : (i > j) ? 1 : 0; +X long i = (long)v->ob_actuator; +X long j = (long)w->ob_actuator; +X return (i < j) ? -1 : (i > j) ? 1 : 0; X} X Xstatic typeobject Actuatortype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "actuator", /*tp_name*/ -X sizeof(actuatorobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X actuator_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X actuator_getattr, /*tp_getattr*/ -X actuator_setattr, /*tp_setattr*/ -X actuator_compare, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "actuator", /*tp_name*/ +X sizeof(actuatorobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X actuator_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X actuator_getattr, /*tp_getattr*/ +X actuator_setattr, /*tp_setattr*/ +X actuator_compare, /*tp_compare*/ +X 0, /*tp_repr*/ X}; X X @@ -1005,121 +1005,121 @@ X/* The panel module itself */ X Xstatic object * Xmodule_mkpanel(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X return newpanelobject(); +X if (!getnoarg(args)) +X return NULL; +X return newpanelobject(); X} X Xstatic object * Xmodule_mkact(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *v; -X Actuator *a; -X if (!getstrarg(args, &v)) -X return NULL; -X a = makeactuator(getstringvalue(v)); -X if (a == NULL) -X return NULL; -X return newactuatorobject(a); +X object *v; +X Actuator *a; +X if (!getstrarg(args, &v)) +X return NULL; +X a = makeactuator(getstringvalue(v)); +X if (a == NULL) +X return NULL; +X return newactuatorobject(a); X} X Xstatic object * Xmodule_dopanel(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X Actuator *a; -X object *v, *w; -X if (!getnoarg(args)) -X return NULL; -X a = pnl_dopanel(); -X v = newtupleobject(4); -X if (v == NULL) -X return NULL; -X settupleitem(v, 0, newactuatorobject(a)); -X settupleitem(v, 1, newactuatorobject(down_pend)); -X settupleitem(v, 2, newactuatorobject(active_pend)); -X settupleitem(v, 3, newactuatorobject(up_pend)); -X down_pend = active_pend = up_pend = NULL; -X return v; +X Actuator *a; +X object *v, *w; +X if (!getnoarg(args)) +X return NULL; +X a = pnl_dopanel(); +X v = newtupleobject(4); +X if (v == NULL) +X return NULL; +X settupleitem(v, 0, newactuatorobject(a)); +X settupleitem(v, 1, newactuatorobject(down_pend)); +X settupleitem(v, 2, newactuatorobject(active_pend)); +X settupleitem(v, 3, newactuatorobject(up_pend)); +X down_pend = active_pend = up_pend = NULL; +X return v; X} X Xstatic object * Xmodule_drawpanel(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X pnl_drawpanel(); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X pnl_drawpanel(); +X INCREF(None); +X return None; X} X Xstatic object * Xmodule_needredraw(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X pnl_needredraw(); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X pnl_needredraw(); +X INCREF(None); +X return None; X} X Xstatic object * Xmodule_userredraw(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X short wid; -X if (!getnoarg(args)) -X return NULL; -X wid = pnl_userredraw(); -X return newintobject((long)wid); +X short wid; +X if (!getnoarg(args)) +X return NULL; +X wid = pnl_userredraw(); +X return newintobject((long)wid); X} X Xstatic object * Xmodule_block(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int flag; -X if (!getintarg(args, &flag)) -X return NULL; -X pnl_block = flag; -X INCREF(None); -X return None; +X int flag; +X if (!getintarg(args, &flag)) +X return NULL; +X pnl_block = flag; +X INCREF(None); +X return None; X} X Xstatic struct methodlist module_methods[] = { -X {"block", module_block}, -X {"dopanel", module_dopanel}, -X {"drawpanel", module_drawpanel}, -X {"mkpanel", module_mkpanel}, -X {"mkact", module_mkact}, -X {"needredraw", module_needredraw}, -X {"userredraw", module_userredraw}, -X {NULL, NULL} /* sentinel */ +X {"block", module_block}, +X {"dopanel", module_dopanel}, +X {"drawpanel", module_drawpanel}, +X {"mkpanel", module_mkpanel}, +X {"mkact", module_mkact}, +X {"needredraw", module_needredraw}, +X {"userredraw", module_userredraw}, +X {NULL, NULL} /* sentinel */ X}; X Xvoid Xinitpanel() X{ -X /* Setting pnl_block to 1 would greatly reduce the CPU usage -X of an idle application. Unfortunately it also breaks our -X little hacks to get callback functions in Python called. -X So we clear pnl_block here. You can set/clear pnl_block -X from Python using pnl.block(flag). It works if you have -X no upfuncs. */ -X pnl_block = 0; -X initmodule("pnl", module_methods); +X /* Setting pnl_block to 1 would greatly reduce the CPU usage +X of an idle application. Unfortunately it also breaks our +X little hacks to get callback functions in Python called. +X So we clear pnl_block here. You can set/clear pnl_block +X from Python using pnl.block(flag). It works if you have +X no upfuncs. */ +X pnl_block = 0; +X initmodule("pnl", module_methods); X} EOF fi @@ -1132,12 +1132,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1155,50 +1155,50 @@ X X/* X * regcomp and regexec -- regsub and regerror are elsewhere X * -X * Copyright (c) 1986 by University of Toronto. -X * Written by Henry Spencer. Not derived from licensed software. +X * Copyright (c) 1986 by University of Toronto. +X * Written by Henry Spencer. Not derived from licensed software. X#ifdef MULTILINE -X * Changed by Guido van Rossum, CWI, Amsterdam -X * for multi-line support. +X * Changed by Guido van Rossum, CWI, Amsterdam +X * for multi-line support. X#endif X * -X * Permission is granted to anyone to use this software for any -X * purpose on any computer system, and to redistribute it freely, -X * subject to the following restrictions: +X * Permission is granted to anyone to use this software for any +X * purpose on any computer system, and to redistribute it freely, +X * subject to the following restrictions: X * -X * 1. The author is not responsible for the consequences of use of -X * this software, no matter how awful, even if they arise -X * from defects in it. +X * 1. The author is not responsible for the consequences of use of +X * this software, no matter how awful, even if they arise +X * from defects in it. X * -X * 2. The origin of this software must not be misrepresented, either -X * by explicit claim or by omission. +X * 2. The origin of this software must not be misrepresented, either +X * by explicit claim or by omission. X * -X * 3. Altered versions must be plainly marked as such, and must not -X * be misrepresented as being the original software. +X * 3. Altered versions must be plainly marked as such, and must not +X * be misrepresented as being the original software. X * X * Beware that some of this code is subtly aware of the way operator -X * precedence is structured in regular expressions. Serious changes in +X * precedence is structured in regular expressions. Serious changes in X * regular-expression syntax might require a total rethink. X */ X#include <stdio.h> X#include "PROTO.h" X#include "malloc.h" X#undef ANY /* Conflicting identifier defined in malloc.h */ -X#include <string.h> /* XXX Remove if not found */ +X#include <string.h> /* XXX Remove if not found */ X#include "regexp.h" X#include "regmagic.h" X X#ifdef MULTILINE X/* X * Defining MULTILINE turns on the following changes in the semantics: -X * 1. The '.' operator matches all characters except a newline. -X * 2. The '^' operator matches at the beginning of the string or after -X * a newline. (Anchored matches are retried after each newline.) -X * 3. The '$' operator matches at the end of the string or before -X * a newline. -X * 4. A '\' followed by an 'n' matches a newline. (This is an -X * unfortunate exception to the rule that '\' followed by a -X * character matches that character...) +X * 1. The '.' operator matches all characters except a newline. +X * 2. The '^' operator matches at the beginning of the string or after +X * a newline. (Anchored matches are retried after each newline.) +X * 3. The '$' operator matches at the end of the string or before +X * a newline. +X * 4. A '\' followed by an 'n' matches a newline. (This is an +X * unfortunate exception to the rule that '\' followed by a +X * character matches that character...) X * X * Also, there is a new function reglexec(prog, string, offset) X * which searches for a match starting at 'string+offset'; @@ -1210,91 +1210,91 @@ X X/* X * The "internal use only" fields in regexp.h are present to pass info from X * compile to execute that permits the execute phase to run lots faster on -X * simple cases. They are: +X * simple cases. They are: X * -X * regstart char that must begin a match; '\0' if none obvious -X * reganch is the match anchored (at beginning-of-line only)? -X * regmust string (pointer into program) that match must include, or NULL -X * regmlen length of regmust string +X * regstart char that must begin a match; '\0' if none obvious +X * reganch is the match anchored (at beginning-of-line only)? +X * regmust string (pointer into program) that match must include, or NULL +X * regmlen length of regmust string X * X * Regstart and reganch permit very fast decisions on suitable starting points -X * for a match, cutting down the work a lot. Regmust permits fast rejection -X * of lines that cannot possibly match. The regmust tests are costly enough +X * for a match, cutting down the work a lot. Regmust permits fast rejection +X * of lines that cannot possibly match. The regmust tests are costly enough X * that regcomp() supplies a regmust only if the r.e. contains something X * potentially expensive (at present, the only such thing detected is * or + -X * at the start of the r.e., which can involve a lot of backup). Regmlen is +X * at the start of the r.e., which can involve a lot of backup). Regmlen is X * supplied because the test in regexec() needs it and regcomp() is computing X * it anyway. X */ X X/* -X * Structure for regexp "program". This is essentially a linear encoding +X * Structure for regexp "program". This is essentially a linear encoding X * of a nondeterministic finite-state machine (aka syntax charts or -X * "railroad normal form" in parsing technology). Each node is an opcode -X * plus a "next" pointer, possibly plus an operand. "Next" pointers of +X * "railroad normal form" in parsing technology). Each node is an opcode +X * plus a "next" pointer, possibly plus an operand. "Next" pointers of X * all nodes except BRANCH implement concatenation; a "next" pointer with -X * a BRANCH on both ends of it is connecting two alternatives. (Here we -X * have one of the subtle syntax dependencies: an individual BRANCH (as +X * a BRANCH on both ends of it is connecting two alternatives. (Here we +X * have one of the subtle syntax dependencies: an individual BRANCH (as X * opposed to a collection of them) is never concatenated with anything -X * because of operator precedence.) The operand of some types of node is -X * a literal string; for others, it is a node leading into a sub-FSM. In +X * because of operator precedence.) The operand of some types of node is +X * a literal string; for others, it is a node leading into a sub-FSM. In X * particular, the operand of a BRANCH node is the first node of the branch. -X * (NB this is *not* a tree structure: the tail of the branch connects -X * to the thing following the set of BRANCHes.) The opcodes are: +X * (NB this is *not* a tree structure: the tail of the branch connects +X * to the thing following the set of BRANCHes.) The opcodes are: X */ X -X/* definition number opnd? meaning */ -X#define END 0 /* no End of program. */ -X#define BOL 1 /* no Match "" at beginning of line. */ -X#define EOL 2 /* no Match "" at end of line. */ -X#define ANY 3 /* no Match any one character. */ -X#define ANYOF 4 /* str Match any character in this string. */ -X#define ANYBUT 5 /* str Match any character not in this string. */ -X#define BRANCH 6 /* node Match this alternative, or the next... */ -X#define BACK 7 /* no Match "", "next" ptr points backward. */ -X#define EXACTLY 8 /* str Match this string. */ -X#define NOTHING 9 /* no Match empty string. */ -X#define STAR 10 /* node Match this (simple) thing 0 or more times. */ -X#define PLUS 11 /* node Match this (simple) thing 1 or more times. */ -X#define OPEN 20 /* no Mark this point in input as start of #n. */ -X /* OPEN+1 is number 1, etc. */ -X#define CLOSE 30 /* no Analogous to OPEN. */ +X/* definition number opnd? meaning */ +X#define END 0 /* no End of program. */ +X#define BOL 1 /* no Match "" at beginning of line. */ +X#define EOL 2 /* no Match "" at end of line. */ +X#define ANY 3 /* no Match any one character. */ +X#define ANYOF 4 /* str Match any character in this string. */ +X#define ANYBUT 5 /* str Match any character not in this string. */ +X#define BRANCH 6 /* node Match this alternative, or the next... */ +X#define BACK 7 /* no Match "", "next" ptr points backward. */ +X#define EXACTLY 8 /* str Match this string. */ +X#define NOTHING 9 /* no Match empty string. */ +X#define STAR 10 /* node Match this (simple) thing 0 or more times. */ +X#define PLUS 11 /* node Match this (simple) thing 1 or more times. */ +X#define OPEN 20 /* no Mark this point in input as start of #n. */ +X /* OPEN+1 is number 1, etc. */ +X#define CLOSE 30 /* no Analogous to OPEN. */ X X/* X * Opcode notes: X * -X * BRANCH The set of branches constituting a single choice are hooked -X * together with their "next" pointers, since precedence prevents -X * anything being concatenated to any individual branch. The -X * "next" pointer of the last BRANCH in a choice points to the -X * thing following the whole choice. This is also where the -X * final "next" pointer of each individual branch points; each -X * branch starts with the operand node of a BRANCH node. +X * BRANCH The set of branches constituting a single choice are hooked +X * together with their "next" pointers, since precedence prevents +X * anything being concatenated to any individual branch. The +X * "next" pointer of the last BRANCH in a choice points to the +X * thing following the whole choice. This is also where the +X * final "next" pointer of each individual branch points; each +X * branch starts with the operand node of a BRANCH node. X * -X * BACK Normal "next" pointers all implicitly point forward; BACK -X * exists to make loop structures possible. +X * BACK Normal "next" pointers all implicitly point forward; BACK +X * exists to make loop structures possible. X * -X * STAR,PLUS '?', and complex '*' and '+', are implemented as circular -X * BRANCH structures using BACK. Simple cases (one character -X * per match) are implemented with STAR and PLUS for speed -X * and to minimize recursive plunges. +X * STAR,PLUS '?', and complex '*' and '+', are implemented as circular +X * BRANCH structures using BACK. Simple cases (one character +X * per match) are implemented with STAR and PLUS for speed +X * and to minimize recursive plunges. X * -X * OPEN,CLOSE ...are numbered at compile time. +X * OPEN,CLOSE ...are numbered at compile time. X */ X X/* X * A node is one char of opcode followed by two chars of "next" pointer. -X * "Next" pointers are stored as two 8-bit pieces, high order first. The +X * "Next" pointers are stored as two 8-bit pieces, high order first. The X * value is a positive offset from the opcode of the node containing it. -X * An operand, if any, simply follows the node. (Note that much of the +X * An operand, if any, simply follows the node. (Note that much of the X * code generation knows about this implicit relationship.) X * X * Using two bytes for the "next" pointer is vast overkill for most things, X * but allows patterns to get big without disasters. X */ -X#define OP(p) (*(p)) -X#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377)) -X#define OPERAND(p) ((p) + 3) +X#define OP(p) (*(p)) +X#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377)) +X#define OPERAND(p) ((p) + 3) X X/* X * See regmagic.h for one further detail of program structure. @@ -1305,40 +1305,40 @@ X/* X * Utility definitions. X */ X#ifndef CHARBITS -X#define UCHARAT(p) ((int)*(unsigned char *)(p)) +X#define UCHARAT(p) ((int)*(unsigned char *)(p)) X#else -X#define UCHARAT(p) ((int)*(p)&CHARBITS) +X#define UCHARAT(p) ((int)*(p)&CHARBITS) X#endif X -X#define FAIL(m) { regerror(m); return(NULL); } -X#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?') -X#define META "^$.[()|?+*\\" +X#define FAIL(m) { regerror(m); return(NULL); } +X#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?') +X#define META "^$.[()|?+*\\" X X/* X * Flags to be passed up and down. X */ -X#define HASWIDTH 01 /* Known never to match null string. */ -X#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */ -X#define SPSTART 04 /* Starts with * or +. */ -X#define WORST 0 /* Worst case. */ +X#define HASWIDTH 01 /* Known never to match null string. */ +X#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */ +X#define SPSTART 04 /* Starts with * or +. */ +X#define WORST 0 /* Worst case. */ X X/* X * Global work variables for regcomp(). X */ -Xstatic char *regparse; /* Input-scan pointer. */ -Xstatic int regnpar; /* () count. */ +Xstatic char *regparse; /* Input-scan pointer. */ +Xstatic int regnpar; /* () count. */ Xstatic char regdummy; -Xstatic char *regcode; /* Code-emit pointer; ®dummy = don't. */ -Xstatic long regsize; /* Code size. */ +Xstatic char *regcode; /* Code-emit pointer; ®dummy = don't. */ +Xstatic long regsize; /* Code size. */ X#ifdef MULTILINE -Xstatic int regnl; /* '\n' detected. */ +Xstatic int regnl; /* '\n' detected. */ X#endif X X/* X * Forward declarations for regcomp()'s friends. X */ X#ifndef STATIC -X#define STATIC static +X#define STATIC static X#endif XSTATIC char *reg(); XSTATIC char *regbranch(); @@ -1359,11 +1359,11 @@ X - regcomp - compile a regular expression into internal code X * X * We can't allocate space until we know how big the compiled form will be, X * but we can't compile it (and thus know how big it is) until we've got a -X * place to put the code. So we cheat: we compile it twice, once with code +X * place to put the code. So we cheat: we compile it twice, once with code X * generation turned off and size counting turned on, and once "for real". X * This also means that we don't allocate space until we are sure that the X * thing really will compile successfully, and we never have to move the -X * code and thus invalidate pointers into it. (Note that it has to be in +X * code and thus invalidate pointers into it. (Note that it has to be in X * one piece because free() must be able to free it all.) X * X * Beware that the optimization-preparation code in here knows about some @@ -1373,85 +1373,85 @@ Xregexp * Xregcomp(exp) Xchar *exp; X{ -X register regexp *r; -X register char *scan; -X register char *longest; -X register int len; -X int flags; -X -X if (exp == NULL) -X FAIL("NULL argument"); -X -X /* First pass: determine size, legality. */ -X regparse = exp; -X regnpar = 1; -X regsize = 0L; -X regcode = ®dummy; +X register regexp *r; +X register char *scan; +X register char *longest; +X register int len; +X int flags; +X +X if (exp == NULL) +X FAIL("NULL argument"); +X +X /* First pass: determine size, legality. */ +X regparse = exp; +X regnpar = 1; +X regsize = 0L; +X regcode = ®dummy; X#ifdef MULTILINE -X regnl = 0; +X regnl = 0; X#endif -X regc(MAGIC); -X if (reg(0, &flags) == NULL) -X return(NULL); -X -X /* Small enough for pointer-storage convention? */ -X if (regsize >= 32767L) /* Probably could be 65535L. */ -X FAIL("regexp too big"); -X -X /* Allocate space. */ -X r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize); -X if (r == NULL) -X FAIL("out of space"); -X -X /* Second pass: emit code. */ -X regparse = exp; -X regnpar = 1; -X regcode = r->program; -X regc(MAGIC); -X if (reg(0, &flags) == NULL) -X return(NULL); -X -X /* Dig out information for optimizations. */ -X r->regstart = '\0'; /* Worst-case defaults. */ -X r->reganch = 0; -X r->regmust = NULL; -X r->regmlen = 0; -X scan = r->program+1; /* First BRANCH. */ -X if (OP(regnext(scan)) == END) { /* Only one top-level choice. */ -X scan = OPERAND(scan); -X -X /* Starting-point info. */ -X if (OP(scan) == EXACTLY) -X r->regstart = *OPERAND(scan); -X else if (OP(scan) == BOL) -X r->reganch++; -X -X /* -X * If there's something expensive in the r.e., find the -X * longest literal string that must appear and make it the -X * regmust. Resolve ties in favor of later strings, since -X * the regstart check works with the beginning of the r.e. -X * and avoiding duplication strengthens checking. Not a -X * strong reason, but sufficient in the absence of others. -X */ +X regc(MAGIC); +X if (reg(0, &flags) == NULL) +X return(NULL); +X +X /* Small enough for pointer-storage convention? */ +X if (regsize >= 32767L) /* Probably could be 65535L. */ +X FAIL("regexp too big"); +X +X /* Allocate space. */ +X r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize); +X if (r == NULL) +X FAIL("out of space"); +X +X /* Second pass: emit code. */ +X regparse = exp; +X regnpar = 1; +X regcode = r->program; +X regc(MAGIC); +X if (reg(0, &flags) == NULL) +X return(NULL); +X +X /* Dig out information for optimizations. */ +X r->regstart = '\0'; /* Worst-case defaults. */ +X r->reganch = 0; +X r->regmust = NULL; +X r->regmlen = 0; +X scan = r->program+1; /* First BRANCH. */ +X if (OP(regnext(scan)) == END) { /* Only one top-level choice. */ +X scan = OPERAND(scan); +X +X /* Starting-point info. */ +X if (OP(scan) == EXACTLY) +X r->regstart = *OPERAND(scan); +X else if (OP(scan) == BOL) +X r->reganch++; +X +X /* +X * If there's something expensive in the r.e., find the +X * longest literal string that must appear and make it the +X * regmust. Resolve ties in favor of later strings, since +X * the regstart check works with the beginning of the r.e. +X * and avoiding duplication strengthens checking. Not a +X * strong reason, but sufficient in the absence of others. +X */ X#ifdef MULTILINE -X if ((flags&SPSTART) && !regnl) { +X if ((flags&SPSTART) && !regnl) { X#else -X if (flags&SPSTART) { +X if (flags&SPSTART) { X#endif -X longest = NULL; -X len = 0; -X for (; scan != NULL; scan = regnext(scan)) -X if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) { -X longest = OPERAND(scan); -X len = strlen(OPERAND(scan)); -X } -X r->regmust = longest; -X r->regmlen = len; -X } -X } -X -X return(r); +X longest = NULL; +X len = 0; +X for (; scan != NULL; scan = regnext(scan)) +X if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) { +X longest = OPERAND(scan); +X len = strlen(OPERAND(scan)); +X } +X r->regmust = longest; +X r->regmlen = len; +X } +X } +X +X return(r); X} X X/* @@ -1465,69 +1465,69 @@ X * follows makes it hard to avoid. X */ Xstatic char * Xreg(paren, flagp) -Xint paren; /* Parenthesized? */ +Xint paren; /* Parenthesized? */ Xint *flagp; X{ -X register char *ret; -X register char *br; -X register char *ender; -X register int parno; -X int flags; -X -X *flagp = HASWIDTH; /* Tentatively. */ -X -X /* Make an OPEN node, if parenthesized. */ -X if (paren) { -X if (regnpar >= NSUBEXP) -X FAIL("too many ()"); -X parno = regnpar; -X regnpar++; -X ret = regnode(OPEN+parno); -X } else -X ret = NULL; -X -X /* Pick up the branches, linking them together. */ -X br = regbranch(&flags); -X if (br == NULL) -X return(NULL); -X if (ret != NULL) -X regtail(ret, br); /* OPEN -> first. */ -X else -X ret = br; -X if (!(flags&HASWIDTH)) -X *flagp &= ~HASWIDTH; -X *flagp |= flags&SPSTART; -X while (*regparse == '|') { -X regparse++; -X br = regbranch(&flags); -X if (br == NULL) -X return(NULL); -X regtail(ret, br); /* BRANCH -> BRANCH. */ -X if (!(flags&HASWIDTH)) -X *flagp &= ~HASWIDTH; -X *flagp |= flags&SPSTART; -X } -X -X /* Make a closing node, and hook it on the end. */ -X ender = regnode((paren) ? CLOSE+parno : END); -X regtail(ret, ender); -X -X /* Hook the tails of the branches to the closing node. */ -X for (br = ret; br != NULL; br = regnext(br)) -X regoptail(br, ender); -X -X /* Check for proper termination. */ -X if (paren && *regparse++ != ')') { -X FAIL("unmatched ()"); -X } else if (!paren && *regparse != '\0') { -X if (*regparse == ')') { -X FAIL("unmatched ()"); -X } else -X FAIL("junk on end"); /* "Can't happen". */ -X /* NOTREACHED */ -X } -X -X return(ret); +X register char *ret; +X register char *br; +X register char *ender; +X register int parno; +X int flags; +X +X *flagp = HASWIDTH; /* Tentatively. */ +X +X /* Make an OPEN node, if parenthesized. */ +X if (paren) { +X if (regnpar >= NSUBEXP) +X FAIL("too many ()"); +X parno = regnpar; +X regnpar++; +X ret = regnode(OPEN+parno); +X } else +X ret = NULL; +X +X /* Pick up the branches, linking them together. */ +X br = regbranch(&flags); +X if (br == NULL) +X return(NULL); +X if (ret != NULL) +X regtail(ret, br); /* OPEN -> first. */ +X else +X ret = br; +X if (!(flags&HASWIDTH)) +X *flagp &= ~HASWIDTH; +X *flagp |= flags&SPSTART; +X while (*regparse == '|') { +X regparse++; +X br = regbranch(&flags); +X if (br == NULL) +X return(NULL); +X regtail(ret, br); /* BRANCH -> BRANCH. */ +X if (!(flags&HASWIDTH)) +X *flagp &= ~HASWIDTH; +X *flagp |= flags&SPSTART; +X } +X +X /* Make a closing node, and hook it on the end. */ +X ender = regnode((paren) ? CLOSE+parno : END); +X regtail(ret, ender); +X +X /* Hook the tails of the branches to the closing node. */ +X for (br = ret; br != NULL; br = regnext(br)) +X regoptail(br, ender); +X +X /* Check for proper termination. */ +X if (paren && *regparse++ != ')') { +X FAIL("unmatched ()"); +X } else if (!paren && *regparse != '\0') { +X if (*regparse == ')') { +X FAIL("unmatched ()"); +X } else +X FAIL("junk on end"); /* "Can't happen". */ +X /* NOTREACHED */ +X } +X +X return(ret); X} X X/* @@ -1539,37 +1539,37 @@ Xstatic char * Xregbranch(flagp) Xint *flagp; X{ -X register char *ret; -X register char *chain; -X register char *latest; -X int flags; -X -X *flagp = WORST; /* Tentatively. */ -X -X ret = regnode(BRANCH); -X chain = NULL; -X while (*regparse != '\0' && *regparse != '|' && *regparse != ')') { -X latest = regpiece(&flags); -X if (latest == NULL) -X return(NULL); -X *flagp |= flags&HASWIDTH; -X if (chain == NULL) /* First piece. */ -X *flagp |= flags&SPSTART; -X else -X regtail(chain, latest); -X chain = latest; -X } -X if (chain == NULL) /* Loop ran zero times. */ -X (void) regnode(NOTHING); -X -X return(ret); +X register char *ret; +X register char *chain; +X register char *latest; +X int flags; +X +X *flagp = WORST; /* Tentatively. */ +X +X ret = regnode(BRANCH); +X chain = NULL; +X while (*regparse != '\0' && *regparse != '|' && *regparse != ')') { +X latest = regpiece(&flags); +X if (latest == NULL) +X return(NULL); +X *flagp |= flags&HASWIDTH; +X if (chain == NULL) /* First piece. */ +X *flagp |= flags&SPSTART; +X else +X regtail(chain, latest); +X chain = latest; +X } +X if (chain == NULL) /* Loop ran zero times. */ +X (void) regnode(NOTHING); +X +X return(ret); X} X X/* X - regpiece - something followed by possible [*+?] X * X * Note that the branching code sequences used for ? and the general cases -X * of * and + are somewhat optimized: they use the same NOTHING node as +X * of * and + are somewhat optimized: they use the same NOTHING node as X * both the endmarker for their branch list and the body of the last branch. X * It might seem that this node could be dispensed with entirely, but the X * endmarker role is not redundant. @@ -1578,207 +1578,207 @@ Xstatic char * Xregpiece(flagp) Xint *flagp; X{ -X register char *ret; -X register char op; -X register char *next; -X int flags; -X -X ret = regatom(&flags); -X if (ret == NULL) -X return(NULL); -X -X op = *regparse; -X if (!ISMULT(op)) { -X *flagp = flags; -X return(ret); -X } -X -X if (!(flags&HASWIDTH) && op != '?') -X FAIL("*+ operand could be empty"); -X *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH); -X -X if (op == '*' && (flags&SIMPLE)) -X reginsert(STAR, ret); -X else if (op == '*') { -X /* Emit x* as (x&|), where & means "self". */ -X reginsert(BRANCH, ret); /* Either x */ -X regoptail(ret, regnode(BACK)); /* and loop */ -X regoptail(ret, ret); /* back */ -X regtail(ret, regnode(BRANCH)); /* or */ -X regtail(ret, regnode(NOTHING)); /* null. */ -X } else if (op == '+' && (flags&SIMPLE)) -X reginsert(PLUS, ret); -X else if (op == '+') { -X /* Emit x+ as x(&|), where & means "self". */ -X next = regnode(BRANCH); /* Either */ -X regtail(ret, next); -X regtail(regnode(BACK), ret); /* loop back */ -X regtail(next, regnode(BRANCH)); /* or */ -X regtail(ret, regnode(NOTHING)); /* null. */ -X } else if (op == '?') { -X /* Emit x? as (x|) */ -X reginsert(BRANCH, ret); /* Either x */ -X regtail(ret, regnode(BRANCH)); /* or */ -X next = regnode(NOTHING); /* null. */ -X regtail(ret, next); -X regoptail(ret, next); -X } -X regparse++; -X if (ISMULT(*regparse)) -X FAIL("nested *?+"); -X -X return(ret); +X register char *ret; +X register char op; +X register char *next; +X int flags; +X +X ret = regatom(&flags); +X if (ret == NULL) +X return(NULL); +X +X op = *regparse; +X if (!ISMULT(op)) { +X *flagp = flags; +X return(ret); +X } +X +X if (!(flags&HASWIDTH) && op != '?') +X FAIL("*+ operand could be empty"); +X *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH); +X +X if (op == '*' && (flags&SIMPLE)) +X reginsert(STAR, ret); +X else if (op == '*') { +X /* Emit x* as (x&|), where & means "self". */ +X reginsert(BRANCH, ret); /* Either x */ +X regoptail(ret, regnode(BACK)); /* and loop */ +X regoptail(ret, ret); /* back */ +X regtail(ret, regnode(BRANCH)); /* or */ +X regtail(ret, regnode(NOTHING)); /* null. */ +X } else if (op == '+' && (flags&SIMPLE)) +X reginsert(PLUS, ret); +X else if (op == '+') { +X /* Emit x+ as x(&|), where & means "self". */ +X next = regnode(BRANCH); /* Either */ +X regtail(ret, next); +X regtail(regnode(BACK), ret); /* loop back */ +X regtail(next, regnode(BRANCH)); /* or */ +X regtail(ret, regnode(NOTHING)); /* null. */ +X } else if (op == '?') { +X /* Emit x? as (x|) */ +X reginsert(BRANCH, ret); /* Either x */ +X regtail(ret, regnode(BRANCH)); /* or */ +X next = regnode(NOTHING); /* null. */ +X regtail(ret, next); +X regoptail(ret, next); +X } +X regparse++; +X if (ISMULT(*regparse)) +X FAIL("nested *?+"); +X +X return(ret); X} X X/* X - regatom - the lowest level X * -X * Optimization: gobbles an entire sequence of ordinary characters so that +X * Optimization: gobbles an entire sequence of ordinary characters so that X * it can turn them into a single node, which is smaller to store and -X * faster to run. Backslashed characters are exceptions, each becoming a +X * faster to run. Backslashed characters are exceptions, each becoming a X * separate node; the code is simpler that way and it's not worth fixing. X */ Xstatic char * Xregatom(flagp) Xint *flagp; X{ -X register char *ret; -X int flags; -X -X *flagp = WORST; /* Tentatively. */ -X -X switch (*regparse++) { -X case '^': -X ret = regnode(BOL); -X break; -X case '$': -X ret = regnode(EOL); -X break; -X case '.': -X ret = regnode(ANY); -X *flagp |= HASWIDTH|SIMPLE; -X break; -X case '[': { -X register int class; -X register int classend; -X -X if (*regparse == '^') { /* Complement of range. */ -X ret = regnode(ANYBUT); -X regparse++; -X } else -X ret = regnode(ANYOF); -X if (*regparse == ']' || *regparse == '-') -X regc(*regparse++); -X while (*regparse != '\0' && *regparse != ']') { -X if (*regparse == '-') { -X regparse++; -X if (*regparse == ']' || *regparse == '\0') -X regc('-'); -X else { -X class = UCHARAT(regparse-2)+1; -X classend = UCHARAT(regparse); -X if (class > classend+1) -X FAIL("invalid [] range"); -X for (; class <= classend; class++) -X regc(class); -X regparse++; -X } -X } else -X regc(*regparse++); -X } -X regc('\0'); -X if (*regparse != ']') -X FAIL("unmatched []"); -X regparse++; -X *flagp |= HASWIDTH|SIMPLE; -X } -X break; -X case '(': -X ret = reg(1, &flags); -X if (ret == NULL) -X return(NULL); -X *flagp |= flags&(HASWIDTH|SPSTART); -X break; -X case '\0': -X case '|': -X case ')': -X FAIL("internal urp"); /* Supposed to be caught earlier. */ -X break; -X case '?': -X case '+': -X case '*': -X FAIL("?+* follows nothing"); -X break; -X case '\\': -X if (*regparse == '\0') -X FAIL("trailing \\"); -X ret = regnode(EXACTLY); +X register char *ret; +X int flags; +X +X *flagp = WORST; /* Tentatively. */ +X +X switch (*regparse++) { +X case '^': +X ret = regnode(BOL); +X break; +X case '$': +X ret = regnode(EOL); +X break; +X case '.': +X ret = regnode(ANY); +X *flagp |= HASWIDTH|SIMPLE; +X break; +X case '[': { +X register int class; +X register int classend; +X +X if (*regparse == '^') { /* Complement of range. */ +X ret = regnode(ANYBUT); +X regparse++; +X } else +X ret = regnode(ANYOF); +X if (*regparse == ']' || *regparse == '-') +X regc(*regparse++); +X while (*regparse != '\0' && *regparse != ']') { +X if (*regparse == '-') { +X regparse++; +X if (*regparse == ']' || *regparse == '\0') +X regc('-'); +X else { +X class = UCHARAT(regparse-2)+1; +X classend = UCHARAT(regparse); +X if (class > classend+1) +X FAIL("invalid [] range"); +X for (; class <= classend; class++) +X regc(class); +X regparse++; +X } +X } else +X regc(*regparse++); +X } +X regc('\0'); +X if (*regparse != ']') +X FAIL("unmatched []"); +X regparse++; +X *flagp |= HASWIDTH|SIMPLE; +X } +X break; +X case '(': +X ret = reg(1, &flags); +X if (ret == NULL) +X return(NULL); +X *flagp |= flags&(HASWIDTH|SPSTART); +X break; +X case '\0': +X case '|': +X case ')': +X FAIL("internal urp"); /* Supposed to be caught earlier. */ +X break; +X case '?': +X case '+': +X case '*': +X FAIL("?+* follows nothing"); +X break; +X case '\\': +X if (*regparse == '\0') +X FAIL("trailing \\"); +X ret = regnode(EXACTLY); X#ifdef MULTILINE -X if (*regparse == 'n') { -X regc('\n'); -X regparse++; -X regnl++; -X } -X else +X if (*regparse == 'n') { +X regc('\n'); +X regparse++; +X regnl++; +X } +X else X#endif -X regc(*regparse++); -X regc('\0'); -X *flagp |= HASWIDTH|SIMPLE; -X break; -X default: { -X register int len; -X register char ender; -X -X regparse--; -X len = strcspn(regparse, META); -X if (len <= 0) -X FAIL("internal disaster"); -X ender = *(regparse+len); -X if (len > 1 && ISMULT(ender)) -X len--; /* Back off clear of ?+* operand. */ -X *flagp |= HASWIDTH; -X if (len == 1) -X *flagp |= SIMPLE; -X ret = regnode(EXACTLY); -X while (len > 0) { +X regc(*regparse++); +X regc('\0'); +X *flagp |= HASWIDTH|SIMPLE; +X break; +X default: { +X register int len; +X register char ender; +X +X regparse--; +X len = strcspn(regparse, META); +X if (len <= 0) +X FAIL("internal disaster"); +X ender = *(regparse+len); +X if (len > 1 && ISMULT(ender)) +X len--; /* Back off clear of ?+* operand. */ +X *flagp |= HASWIDTH; +X if (len == 1) +X *flagp |= SIMPLE; +X ret = regnode(EXACTLY); +X while (len > 0) { X#ifdef MULTILINE -X if (*regparse == '\n') -X regnl++; +X if (*regparse == '\n') +X regnl++; X#endif -X regc(*regparse++); -X len--; -X } -X regc('\0'); -X } -X break; -X } -X -X return(ret); +X regc(*regparse++); +X len--; +X } +X regc('\0'); +X } +X break; +X } +X +X return(ret); X} X X/* X - regnode - emit a node X */ -Xstatic char * /* Location. */ +Xstatic char * /* Location. */ Xregnode(op) Xchar op; X{ -X register char *ret; -X register char *ptr; -X -X ret = regcode; -X if (ret == ®dummy) { -X regsize += 3; -X return(ret); -X } -X -X ptr = ret; -X *ptr++ = op; -X *ptr++ = '\0'; /* Null "next" pointer. */ -X *ptr++ = '\0'; -X regcode = ptr; -X -X return(ret); +X register char *ret; +X register char *ptr; +X +X ret = regcode; +X if (ret == ®dummy) { +X regsize += 3; +X return(ret); +X } +X +X ptr = ret; +X *ptr++ = op; +X *ptr++ = '\0'; /* Null "next" pointer. */ +X *ptr++ = '\0'; +X regcode = ptr; +X +X return(ret); X} X X/* @@ -1788,10 +1788,10 @@ Xstatic void Xregc(b) Xchar b; X{ -X if (regcode != ®dummy) -X *regcode++ = b; -X else -X regsize++; +X if (regcode != ®dummy) +X *regcode++ = b; +X else +X regsize++; X} X X/* @@ -1804,25 +1804,25 @@ Xreginsert(op, opnd) Xchar op; Xchar *opnd; X{ -X register char *src; -X register char *dst; -X register char *place; -X -X if (regcode == ®dummy) { -X regsize += 3; -X return; -X } -X -X src = regcode; -X regcode += 3; -X dst = regcode; -X while (src > opnd) -X *--dst = *--src; -X -X place = opnd; /* Op node, where operand used to be. */ -X *place++ = op; -X *place++ = '\0'; -X *place++ = '\0'; +X register char *src; +X register char *dst; +X register char *place; +X +X if (regcode == ®dummy) { +X regsize += 3; +X return; +X } +X +X src = regcode; +X regcode += 3; +X dst = regcode; +X while (src > opnd) +X *--dst = *--src; +X +X place = opnd; /* Op node, where operand used to be. */ +X *place++ = op; +X *place++ = '\0'; +X *place++ = '\0'; X} X X/* @@ -1833,28 +1833,28 @@ Xregtail(p, val) Xchar *p; Xchar *val; X{ -X register char *scan; -X register char *temp; -X register int offset; -X -X if (p == ®dummy) -X return; -X -X /* Find last node. */ -X scan = p; -X for (;;) { -X temp = regnext(scan); -X if (temp == NULL) -X break; -X scan = temp; -X } -X -X if (OP(scan) == BACK) -X offset = scan - val; -X else -X offset = val - scan; -X *(scan+1) = (offset>>8)&0377; -X *(scan+2) = offset&0377; +X register char *scan; +X register char *temp; +X register int offset; +X +X if (p == ®dummy) +X return; +X +X /* Find last node. */ +X scan = p; +X for (;;) { +X temp = regnext(scan); +X if (temp == NULL) +X break; +X scan = temp; +X } +X +X if (OP(scan) == BACK) +X offset = scan - val; +X else +X offset = val - scan; +X *(scan+1) = (offset>>8)&0377; +X *(scan+2) = offset&0377; X} X X/* @@ -1865,10 +1865,10 @@ Xregoptail(p, val) Xchar *p; Xchar *val; X{ -X /* "Operandless" and "op != BRANCH" are synonymous in practice. */ -X if (p == NULL || p == ®dummy || OP(p) != BRANCH) -X return; -X regtail(OPERAND(p), val); +X /* "Operandless" and "op != BRANCH" are synonymous in practice. */ +X if (p == NULL || p == ®dummy || OP(p) != BRANCH) +X return; +X regtail(OPERAND(p), val); X} X X/* @@ -1878,10 +1878,10 @@ X X/* X * Global work variables for regexec(). X */ -Xstatic char *reginput; /* String-input pointer. */ -Xstatic char *regbol; /* Beginning of input, for ^ check. */ -Xstatic char **regstartp; /* Pointer to startp array. */ -Xstatic char **regendp; /* Ditto for endp. */ +Xstatic char *reginput; /* String-input pointer. */ +Xstatic char *regbol; /* Beginning of input, for ^ check. */ +Xstatic char **regstartp; /* Pointer to startp array. */ +Xstatic char **regendp; /* Ditto for endp. */ X X/* X * Forwards. @@ -1904,64 +1904,64 @@ Xregexec(prog, string) Xregister regexp *prog; Xregister char *string; X{ -X register char *s; -X extern char *strchr(); +X register char *s; +X extern char *strchr(); X -X /* Be paranoid... */ -X if (prog == NULL || string == NULL) { -X regerror("NULL parameter"); -X return(0); -X } +X /* Be paranoid... */ +X if (prog == NULL || string == NULL) { +X regerror("NULL parameter"); +X return(0); +X } X X#ifdef MULTILINE -X /* Check for \n in string, and if so, call the more general routine. */ -X if (strchr(string, '\n') != NULL) -X return reglexec(prog, string, 0); +X /* Check for \n in string, and if so, call the more general routine. */ +X if (strchr(string, '\n') != NULL) +X return reglexec(prog, string, 0); X#endif X -X /* Check validity of program. */ -X if (UCHARAT(prog->program) != MAGIC) { -X regerror("corrupted program"); -X return(0); -X } -X -X /* If there is a "must appear" string, look for it. */ -X if (prog->regmust != NULL) { -X s = string; -X while ((s = strchr(s, prog->regmust[0])) != NULL) { -X if (strncmp(s, prog->regmust, prog->regmlen) == 0) -X break; /* Found it. */ -X s++; -X } -X if (s == NULL) /* Not present. */ -X return(0); -X } -X -X /* Mark beginning of line for ^ . */ -X regbol = string; -X -X /* Simplest case: anchored match need be tried only once. */ -X if (prog->reganch) -X return(regtry(prog, string)); -X -X /* Messy cases: unanchored match. */ -X s = string; -X if (prog->regstart != '\0') -X /* We know what char it must start with. */ -X while ((s = strchr(s, prog->regstart)) != NULL) { -X if (regtry(prog, s)) -X return(1); -X s++; -X } -X else -X /* We don't -- general case. */ -X do { -X if (regtry(prog, s)) -X return(1); -X } while (*s++ != '\0'); -X -X /* Failure. */ -X return(0); +X /* Check validity of program. */ +X if (UCHARAT(prog->program) != MAGIC) { +X regerror("corrupted program"); +X return(0); +X } +X +X /* If there is a "must appear" string, look for it. */ +X if (prog->regmust != NULL) { +X s = string; +X while ((s = strchr(s, prog->regmust[0])) != NULL) { +X if (strncmp(s, prog->regmust, prog->regmlen) == 0) +X break; /* Found it. */ +X s++; +X } +X if (s == NULL) /* Not present. */ +X return(0); +X } +X +X /* Mark beginning of line for ^ . */ +X regbol = string; +X +X /* Simplest case: anchored match need be tried only once. */ +X if (prog->reganch) +X return(regtry(prog, string)); +X +X /* Messy cases: unanchored match. */ +X s = string; +X if (prog->regstart != '\0') +X /* We know what char it must start with. */ +X while ((s = strchr(s, prog->regstart)) != NULL) { +X if (regtry(prog, s)) +X return(1); +X s++; +X } +X else +X /* We don't -- general case. */ +X do { +X if (regtry(prog, s)) +X return(1); +X } while (*s++ != '\0'); +X +X /* Failure. */ +X return(0); X} X X#ifdef MULTILINE @@ -1973,303 +1973,303 @@ Xreglexec(prog, string, offset) Xregister regexp *prog; Xregister char *string; X{ -X register char *s; -X extern char *strchr(); -X -X /* Be paranoid... */ -X if (prog == NULL || string == NULL) { -X regerror("NULL parameter"); -X return(0); -X } -X -X /* Check validity of program. */ -X if (UCHARAT(prog->program) != MAGIC) { -X regerror("corrupted program"); -X return(0); -X } -X -X /* (Don't look for "must appear" string -- string can be long.) */ -X -X /* Mark beginning of line for ^ . */ -X regbol = string; -X -X /* Apply offset. -X Assume 0 <= offset <= strlen(string), but don't check, -X as string can be long. */ -X s= string + offset; -X -X /* Anchored match need be tried only at line starts. */ -X if (prog->reganch) { -X while (!regtry(prog, s)) { -X s = strchr(s, '\n'); -X if (s == NULL) -X return(0); -X s++; -X } -X return(1); -X } -X -X /* Messy cases: unanchored match. */ -X if (prog->regstart != '\0') -X /* We know what char it must start with. */ -X while ((s = strchr(s, prog->regstart)) != NULL) { -X if (regtry(prog, s)) -X return(1); -X s++; -X } -X else -X /* We don't -- general case. */ -X do { -X if (regtry(prog, s)) -X return(1); -X } while (*s++ != '\0'); -X -X /* Failure. */ -X return(0); +X register char *s; +X extern char *strchr(); +X +X /* Be paranoid... */ +X if (prog == NULL || string == NULL) { +X regerror("NULL parameter"); +X return(0); +X } +X +X /* Check validity of program. */ +X if (UCHARAT(prog->program) != MAGIC) { +X regerror("corrupted program"); +X return(0); +X } +X +X /* (Don't look for "must appear" string -- string can be long.) */ +X +X /* Mark beginning of line for ^ . */ +X regbol = string; +X +X /* Apply offset. +X Assume 0 <= offset <= strlen(string), but don't check, +X as string can be long. */ +X s= string + offset; +X +X /* Anchored match need be tried only at line starts. */ +X if (prog->reganch) { +X while (!regtry(prog, s)) { +X s = strchr(s, '\n'); +X if (s == NULL) +X return(0); +X s++; +X } +X return(1); +X } +X +X /* Messy cases: unanchored match. */ +X if (prog->regstart != '\0') +X /* We know what char it must start with. */ +X while ((s = strchr(s, prog->regstart)) != NULL) { +X if (regtry(prog, s)) +X return(1); +X s++; +X } +X else +X /* We don't -- general case. */ +X do { +X if (regtry(prog, s)) +X return(1); +X } while (*s++ != '\0'); +X +X /* Failure. */ +X return(0); X} X#endif X X/* X - regtry - try match at specific point X */ -Xstatic int /* 0 failure, 1 success */ +Xstatic int /* 0 failure, 1 success */ Xregtry(prog, string) Xregexp *prog; Xchar *string; X{ -X register int i; -X register char **sp; -X register char **ep; -X -X reginput = string; -X regstartp = prog->startp; -X regendp = prog->endp; -X -X sp = prog->startp; -X ep = prog->endp; -X for (i = NSUBEXP; i > 0; i--) { -X *sp++ = NULL; -X *ep++ = NULL; -X } -X if (regmatch(prog->program + 1)) { -X prog->startp[0] = string; -X prog->endp[0] = reginput; -X return(1); -X } else -X return(0); +X register int i; +X register char **sp; +X register char **ep; +X +X reginput = string; +X regstartp = prog->startp; +X regendp = prog->endp; +X +X sp = prog->startp; +X ep = prog->endp; +X for (i = NSUBEXP; i > 0; i--) { +X *sp++ = NULL; +X *ep++ = NULL; +X } +X if (regmatch(prog->program + 1)) { +X prog->startp[0] = string; +X prog->endp[0] = reginput; +X return(1); +X } else +X return(0); X} X X/* X - regmatch - main matching routine X * -X * Conceptually the strategy is simple: check to see whether the current +X * Conceptually the strategy is simple: check to see whether the current X * node matches, call self recursively to see whether the rest matches, -X * and then act accordingly. In practice we make some effort to avoid +X * and then act accordingly. In practice we make some effort to avoid X * recursion, in particular by going through "ordinary" nodes (that don't X * need to know whether the rest of the match failed) by a loop instead of X * by recursion. X */ -Xstatic int /* 0 failure, 1 success */ +Xstatic int /* 0 failure, 1 success */ Xregmatch(prog) Xchar *prog; X{ -X register char *scan; /* Current node. */ -X char *next; /* Next node. */ -X extern char *strchr(); +X register char *scan; /* Current node. */ +X char *next; /* Next node. */ +X extern char *strchr(); X -X scan = prog; +X scan = prog; X#ifdef DEBUG -X if (scan != NULL && regnarrate) -X fprintf(stderr, "%s(\n", regprop(scan)); +X if (scan != NULL && regnarrate) +X fprintf(stderr, "%s(\n", regprop(scan)); X#endif -X while (scan != NULL) { +X while (scan != NULL) { X#ifdef DEBUG -X if (regnarrate) -X fprintf(stderr, "%s...\n", regprop(scan)); +X if (regnarrate) +X fprintf(stderr, "%s...\n", regprop(scan)); X#endif -X next = regnext(scan); +X next = regnext(scan); X -X switch (OP(scan)) { -X case BOL: +X switch (OP(scan)) { +X case BOL: X#ifdef MULTILINE -X if (!(reginput == regbol || -X reginput > regbol && *(reginput-1) == '\n')) +X if (!(reginput == regbol || +X reginput > regbol && *(reginput-1) == '\n')) X#else -X if (reginput != regbol) +X if (reginput != regbol) X#endif -X return(0); -X break; -X case EOL: +X return(0); +X break; +X case EOL: X#ifdef MULTILINE -X if (*reginput != '\0' && *reginput != '\n') +X if (*reginput != '\0' && *reginput != '\n') X#else -X if (*reginput != '\0') +X if (*reginput != '\0') X#endif -X return(0); -X break; -X case ANY: +X return(0); +X break; +X case ANY: X#ifdef MULTILINE -X if (*reginput == '\0' || *reginput == '\n') +X if (*reginput == '\0' || *reginput == '\n') X#else -X if (*reginput == '\0') +X if (*reginput == '\0') X#endif -X return(0); -X reginput++; -X break; -X case EXACTLY: { -X register int len; -X register char *opnd; -X -X opnd = OPERAND(scan); -X /* Inline the first character, for speed. */ -X if (*opnd != *reginput) -X return(0); -X len = strlen(opnd); -X if (len > 1 && strncmp(opnd, reginput, len) != 0) -X return(0); -X reginput += len; -X } -X break; -X case ANYOF: -X if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL) -X return(0); -X reginput++; -X break; -X case ANYBUT: +X return(0); +X reginput++; +X break; +X case EXACTLY: { +X register int len; +X register char *opnd; +X +X opnd = OPERAND(scan); +X /* Inline the first character, for speed. */ +X if (*opnd != *reginput) +X return(0); +X len = strlen(opnd); +X if (len > 1 && strncmp(opnd, reginput, len) != 0) +X return(0); +X reginput += len; +X } +X break; +X case ANYOF: +X if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL) +X return(0); +X reginput++; +X break; +X case ANYBUT: X#ifdef MULTILINE -X if (*reginput == '\0' || *reginput == '\n' || -X strchr(OPERAND(scan), *reginput) != NULL) +X if (*reginput == '\0' || *reginput == '\n' || +X strchr(OPERAND(scan), *reginput) != NULL) X#else -X if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL) +X if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL) X#endif -X return(0); -X reginput++; -X break; -X case NOTHING: -X break; -X case BACK: -X break; -X case OPEN+1: -X case OPEN+2: -X case OPEN+3: -X case OPEN+4: -X case OPEN+5: -X case OPEN+6: -X case OPEN+7: -X case OPEN+8: -X case OPEN+9: { -X register int no; -X register char *save; -X -X no = OP(scan) - OPEN; -X save = reginput; -X -X if (regmatch(next)) { -X /* -X * Don't set startp if some later -X * invocation of the same parentheses -X * already has. -X */ -X if (regstartp[no] == NULL) -X regstartp[no] = save; -X return(1); -X } else -X return(0); -X } -X break; -X case CLOSE+1: -X case CLOSE+2: -X case CLOSE+3: -X case CLOSE+4: -X case CLOSE+5: -X case CLOSE+6: -X case CLOSE+7: -X case CLOSE+8: -X case CLOSE+9: { -X register int no; -X register char *save; -X -X no = OP(scan) - CLOSE; -X save = reginput; -X -X if (regmatch(next)) { -X /* -X * Don't set endp if some later -X * invocation of the same parentheses -X * already has. -X */ -X if (regendp[no] == NULL) -X regendp[no] = save; -X return(1); -X } else -X return(0); -X } -X break; -X case BRANCH: { -X register char *save; -X -X if (OP(next) != BRANCH) /* No choice. */ -X next = OPERAND(scan); /* Avoid recursion. */ -X else { -X do { -X save = reginput; -X if (regmatch(OPERAND(scan))) -X return(1); -X reginput = save; -X scan = regnext(scan); -X } while (scan != NULL && OP(scan) == BRANCH); -X return(0); -X /* NOTREACHED */ -X } -X } -X break; -X case STAR: -X case PLUS: { -X register char nextch; -X register int no; -X register char *save; -X register int min; -X -X /* -X * Lookahead to avoid useless match attempts -X * when we know what character comes next. -X */ -X nextch = '\0'; -X if (OP(next) == EXACTLY) -X nextch = *OPERAND(next); -X min = (OP(scan) == STAR) ? 0 : 1; -X save = reginput; -X no = regrepeat(OPERAND(scan)); -X while (no >= min) { -X /* If it could work, try it. */ -X if (nextch == '\0' || *reginput == nextch) -X if (regmatch(next)) -X return(1); -X /* Couldn't or didn't -- back up. */ -X no--; -X reginput = save + no; -X } -X return(0); -X } -X break; -X case END: -X return(1); /* Success! */ -X break; -X default: -X regerror("memory corruption"); -X return(0); -X break; -X } -X -X scan = next; -X } -X -X /* -X * We get here only if there's trouble -- normally "case END" is -X * the terminating point. -X */ -X regerror("corrupted pointers"); -X return(0); +X return(0); +X reginput++; +X break; +X case NOTHING: +X break; +X case BACK: +X break; +X case OPEN+1: +X case OPEN+2: +X case OPEN+3: +X case OPEN+4: +X case OPEN+5: +X case OPEN+6: +X case OPEN+7: +X case OPEN+8: +X case OPEN+9: { +X register int no; +X register char *save; +X +X no = OP(scan) - OPEN; +X save = reginput; +X +X if (regmatch(next)) { +X /* +X * Don't set startp if some later +X * invocation of the same parentheses +X * already has. +X */ +X if (regstartp[no] == NULL) +X regstartp[no] = save; +X return(1); +X } else +X return(0); +X } +X break; +X case CLOSE+1: +X case CLOSE+2: +X case CLOSE+3: +X case CLOSE+4: +X case CLOSE+5: +X case CLOSE+6: +X case CLOSE+7: +X case CLOSE+8: +X case CLOSE+9: { +X register int no; +X register char *save; +X +X no = OP(scan) - CLOSE; +X save = reginput; +X +X if (regmatch(next)) { +X /* +X * Don't set endp if some later +X * invocation of the same parentheses +X * already has. +X */ +X if (regendp[no] == NULL) +X regendp[no] = save; +X return(1); +X } else +X return(0); +X } +X break; +X case BRANCH: { +X register char *save; +X +X if (OP(next) != BRANCH) /* No choice. */ +X next = OPERAND(scan); /* Avoid recursion. */ +X else { +X do { +X save = reginput; +X if (regmatch(OPERAND(scan))) +X return(1); +X reginput = save; +X scan = regnext(scan); +X } while (scan != NULL && OP(scan) == BRANCH); +X return(0); +X /* NOTREACHED */ +X } +X } +X break; +X case STAR: +X case PLUS: { +X register char nextch; +X register int no; +X register char *save; +X register int min; +X +X /* +X * Lookahead to avoid useless match attempts +X * when we know what character comes next. +X */ +X nextch = '\0'; +X if (OP(next) == EXACTLY) +X nextch = *OPERAND(next); +X min = (OP(scan) == STAR) ? 0 : 1; +X save = reginput; +X no = regrepeat(OPERAND(scan)); +X while (no >= min) { +X /* If it could work, try it. */ +X if (nextch == '\0' || *reginput == nextch) +X if (regmatch(next)) +X return(1); +X /* Couldn't or didn't -- back up. */ +X no--; +X reginput = save + no; +X } +X return(0); +X } +X break; +X case END: +X return(1); /* Success! */ +X break; +X default: +X regerror("memory corruption"); +X return(0); +X break; +X } +X +X scan = next; +X } +X +X /* +X * We get here only if there's trouble -- normally "case END" is +X * the terminating point. +X */ +X regerror("corrupted pointers"); +X return(0); X} X X/* @@ -2279,58 +2279,58 @@ Xstatic int Xregrepeat(p) Xchar *p; X{ -X register int count = 0; -X register char *scan; -X register char *opnd; +X register int count = 0; +X register char *scan; +X register char *opnd; X#ifdef MULTILINE -X register char *eol; +X register char *eol; X#endif X -X scan = reginput; -X opnd = OPERAND(p); -X switch (OP(p)) { -X case ANY: +X scan = reginput; +X opnd = OPERAND(p); +X switch (OP(p)) { +X case ANY: X#ifdef MULTILINE -X if ((eol = strchr(scan, '\n')) != NULL) { -X count += eol - scan; -X scan = eol; -X break; -X } +X if ((eol = strchr(scan, '\n')) != NULL) { +X count += eol - scan; +X scan = eol; +X break; +X } X#endif -X count = strlen(scan); -X scan += count; -X break; -X case EXACTLY: -X while (*opnd == *scan) { -X count++; -X scan++; -X } -X break; -X case ANYOF: -X while (*scan != '\0' && strchr(opnd, *scan) != NULL) { -X count++; -X scan++; -X } -X break; -X case ANYBUT: +X count = strlen(scan); +X scan += count; +X break; +X case EXACTLY: +X while (*opnd == *scan) { +X count++; +X scan++; +X } +X break; +X case ANYOF: +X while (*scan != '\0' && strchr(opnd, *scan) != NULL) { +X count++; +X scan++; +X } +X break; +X case ANYBUT: X#ifdef MULTILINE -X while (*scan != '\0' && *scan != '\n' && -X strchr(opnd, *scan) == NULL) { +X while (*scan != '\0' && *scan != '\n' && +X strchr(opnd, *scan) == NULL) { X#else -X while (*scan != '\0' && strchr(opnd, *scan) == NULL) { +X while (*scan != '\0' && strchr(opnd, *scan) == NULL) { X#endif -X count++; -X scan++; -X } -X break; -X default: /* Oh dear. Called inappropriately. */ -X regerror("internal foulup"); -X count = 0; /* Best compromise. */ -X break; -X } -X reginput = scan; -X -X return(count); +X count++; +X scan++; +X } +X break; +X default: /* Oh dear. Called inappropriately. */ +X regerror("internal foulup"); +X count = 0; /* Best compromise. */ +X break; +X } +X reginput = scan; +X +X return(count); X} X X/* @@ -2340,19 +2340,19 @@ Xstatic char * Xregnext(p) Xregister char *p; X{ -X register int offset; +X register int offset; X -X if (p == ®dummy) -X return(NULL); +X if (p == ®dummy) +X return(NULL); X -X offset = NEXT(p); -X if (offset == 0) -X return(NULL); +X offset = NEXT(p); +X if (offset == 0) +X return(NULL); X -X if (OP(p) == BACK) -X return(p-offset); -X else -X return(p+offset); +X if (OP(p) == BACK) +X return(p-offset); +X else +X return(p+offset); X} X X#ifdef DEBUG @@ -2366,46 +2366,46 @@ Xvoid Xregdump(r) Xregexp *r; X{ -X register char *s; -X register char op = EXACTLY; /* Arbitrary non-END op. */ -X register char *next; -X extern char *strchr(); -X -X -X s = r->program + 1; -X while (op != END) { /* While that wasn't END last time... */ -X op = OP(s); -X printf("%2d%s", (int)(s-r->program), regprop(s)); /* Where, what. */ -X next = regnext(s); -X if (next == NULL) /* Next ptr. */ -X printf("(0)"); -X else -X printf("(%d)", (int)((s-r->program)+(next-s))); -X s += 3; -X if (op == ANYOF || op == ANYBUT || op == EXACTLY) { -X /* Literal string, where present. */ -X while (*s != '\0') { +X register char *s; +X register char op = EXACTLY; /* Arbitrary non-END op. */ +X register char *next; +X extern char *strchr(); +X +X +X s = r->program + 1; +X while (op != END) { /* While that wasn't END last time... */ +X op = OP(s); +X printf("%2d%s", (int)(s-r->program), regprop(s)); /* Where, what. */ +X next = regnext(s); +X if (next == NULL) /* Next ptr. */ +X printf("(0)"); +X else +X printf("(%d)", (int)((s-r->program)+(next-s))); +X s += 3; +X if (op == ANYOF || op == ANYBUT || op == EXACTLY) { +X /* Literal string, where present. */ +X while (*s != '\0') { X#ifdef MULTILINE -X if (*s == '\n') -X printf("\\n"); -X else +X if (*s == '\n') +X printf("\\n"); +X else X#endif -X putchar(*s); -X s++; -X } -X s++; -X } -X putchar('\n'); -X } -X -X /* Header fields of interest. */ -X if (r->regstart != '\0') -X printf("start `%c' ", r->regstart); -X if (r->reganch) -X printf("anchored "); -X if (r->regmust != NULL) -X printf("must have \"%s\"", r->regmust); -X printf("\n"); +X putchar(*s); +X s++; +X } +X s++; +X } +X putchar('\n'); +X } +X +X /* Header fields of interest. */ +X if (r->regstart != '\0') +X printf("start `%c' ", r->regstart); +X if (r->reganch) +X printf("anchored "); +X if (r->regmust != NULL) +X printf("must have \"%s\"", r->regmust); +X printf("\n"); X} X X/* @@ -2415,85 +2415,85 @@ Xstatic char * Xregprop(op) Xchar *op; X{ -X register char *p; -X static char buf[50]; -X -X (void) strcpy(buf, ":"); -X -X switch (OP(op)) { -X case BOL: -X p = "BOL"; -X break; -X case EOL: -X p = "EOL"; -X break; -X case ANY: -X p = "ANY"; -X break; -X case ANYOF: -X p = "ANYOF"; -X break; -X case ANYBUT: -X p = "ANYBUT"; -X break; -X case BRANCH: -X p = "BRANCH"; -X break; -X case EXACTLY: -X p = "EXACTLY"; -X break; -X case NOTHING: -X p = "NOTHING"; -X break; -X case BACK: -X p = "BACK"; -X break; -X case END: -X p = "END"; -X break; -X case OPEN+1: -X case OPEN+2: -X case OPEN+3: -X case OPEN+4: -X case OPEN+5: -X case OPEN+6: -X case OPEN+7: -X case OPEN+8: -X case OPEN+9: -X sprintf(buf+strlen(buf), "OPEN%d", (int)(OP(op)-OPEN)); -X p = NULL; -X break; -X case CLOSE+1: -X case CLOSE+2: -X case CLOSE+3: -X case CLOSE+4: -X case CLOSE+5: -X case CLOSE+6: -X case CLOSE+7: -X case CLOSE+8: -X case CLOSE+9: -X sprintf(buf+strlen(buf), "CLOSE%d", (int)(OP(op)-CLOSE)); -X p = NULL; -X break; -X case STAR: -X p = "STAR"; -X break; -X case PLUS: -X p = "PLUS"; -X break; -X default: -X regerror("corrupted opcode"); -X break; -X } -X if (p != NULL) -X (void) strcat(buf, p); -X return(buf); +X register char *p; +X static char buf[50]; +X +X (void) strcpy(buf, ":"); +X +X switch (OP(op)) { +X case BOL: +X p = "BOL"; +X break; +X case EOL: +X p = "EOL"; +X break; +X case ANY: +X p = "ANY"; +X break; +X case ANYOF: +X p = "ANYOF"; +X break; +X case ANYBUT: +X p = "ANYBUT"; +X break; +X case BRANCH: +X p = "BRANCH"; +X break; +X case EXACTLY: +X p = "EXACTLY"; +X break; +X case NOTHING: +X p = "NOTHING"; +X break; +X case BACK: +X p = "BACK"; +X break; +X case END: +X p = "END"; +X break; +X case OPEN+1: +X case OPEN+2: +X case OPEN+3: +X case OPEN+4: +X case OPEN+5: +X case OPEN+6: +X case OPEN+7: +X case OPEN+8: +X case OPEN+9: +X sprintf(buf+strlen(buf), "OPEN%d", (int)(OP(op)-OPEN)); +X p = NULL; +X break; +X case CLOSE+1: +X case CLOSE+2: +X case CLOSE+3: +X case CLOSE+4: +X case CLOSE+5: +X case CLOSE+6: +X case CLOSE+7: +X case CLOSE+8: +X case CLOSE+9: +X sprintf(buf+strlen(buf), "CLOSE%d", (int)(OP(op)-CLOSE)); +X p = NULL; +X break; +X case STAR: +X p = "STAR"; +X break; +X case PLUS: +X p = "PLUS"; +X break; +X default: +X regerror("corrupted opcode"); +X break; +X } +X if (p != NULL) +X (void) strcat(buf, p); +X return(buf); X} X#endif X X/* X * The following is provided for those people who do not have strcspn() in -X * their C libraries. They should get off their butts and do something +X * their C libraries. They should get off their butts and do something X * about it; at least one public-domain implementation of those (highly X * useful) string routines has been published on Usenet. X */ @@ -2508,21 +2508,21 @@ Xstrcspn(s1, s2) Xchar *s1; Xchar *s2; X{ -X register char *scan1; -X register char *scan2; -X register int count; -X -X count = 0; -X for (scan1 = s1; *scan1 != '\0'; scan1++) { -X for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */ -X if (*scan1 == *scan2++) -X return(count); -X count++; -X } -X return(count); +X register char *scan1; +X register char *scan2; +X register int count; +X +X count = 0; +X for (scan1 = s1; *scan1 != '\0'; scan1++) { +X for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */ +X if (*scan1 == *scan2++) +X return(count); +X count++; +X } +X return(count); X} X#endif EOF fi echo 'Part 05 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-06-21.shar b/shar/python-0.9.1-06-21.shar index 2d2194b..c3ec232 100644 --- a/shar/python-0.9.1-06-21.shar +++ b/shar/python-0.9.1-06-21.shar @@ -10,51 +10,51 @@ echo 'x - doc/Makefile' sed 's/^X//' > 'doc/Makefile' << 'EOF' X# Makefile for Python documentation. X -XLATEX= latex -XDVIPS= dvips -XTEXPREVIEW= xdvi +XLATEX= latex +XDVIPS= dvips +XTEXPREVIEW= xdvi X -XPRINT= lpr +XPRINT= lpr X -Xtut: tut.dvi -X $(TEXPREVIEW) tut +Xtut: tut.dvi +X $(TEXPREVIEW) tut X -Xtut.dvi tut.ps: tut.toc tut.tex myformat.sty +Xtut.dvi tut.ps: tut.toc tut.tex myformat.sty X -Xmod: mod.dvi -X $(TEXPREVIEW) mod +Xmod: mod.dvi +X $(TEXPREVIEW) mod X -Xmod.dvi mod.ps: mod.toc mod.tex mod1.tex mod2.tex mod3.tex myformat.sty +Xmod.dvi mod.ps: mod.toc mod.tex mod1.tex mod2.tex mod3.tex myformat.sty X -XALL= tut.ps mod.ps +XALL= tut.ps mod.ps X -Xall: $(ALL) +Xall: $(ALL) X -Xprint: $(ALL) -X $(PRINT) $(ALL) +Xprint: $(ALL) +X $(PRINT) $(ALL) X Xclean: -X rm -f *.dvi *.aux *.toc *.log *.ps core [#@,]* *~ +X rm -f *.dvi *.aux *.toc *.log *.ps core [#@,]* *~ X -X.SUFFIXES: # Remove default suffixes +X.SUFFIXES: # Remove default suffixes X -X.SUFFIXES: .tex .aux .toc .dvi .ps +X.SUFFIXES: .tex .aux .toc .dvi .ps X X.tex.aux: -X $(LATEX) $* +X $(LATEX) $* X X.tex.toc: -X $(LATEX) $* +X $(LATEX) $* X X.tex.dvi: -X $(LATEX) $* +X $(LATEX) $* X X.dvi.ps: -X $(DVIPS) $* >$*.ps +X $(DVIPS) $* >$*.ps X X.tex.ps: -X $(LATEX) $* -X $(DVIPS) $* >$*.ps +X $(LATEX) $* +X $(DVIPS) $* >$*.ps EOF fi if test -s 'doc/mod2.tex' @@ -151,12 +151,12 @@ X{\tt cosh(x)}, X{\tt exp(x)}, X{\tt fabs(x)}, X{\tt floor(x)}, -X%{\tt fmod(...)} XXX not yet +X%{\tt fmod(...)} XXX not yet X%{\tt frexp(...)} XXX not yet X%{\tt ldexp(...)} XXX not yet X{\tt log(x)}, X{\tt log10(x)}, -X%{\tt modf(...)} XXX not yet +X%{\tt modf(...)} XXX not yet X{\tt pow(x,y)}, X{\tt sin(x)}, X{\tt sinh(x)}, @@ -257,7 +257,7 @@ X>>> s[1:6] # The entire match X'--b--' X>>> s[3:4] # The subpattern X'b' -X>>> +X>>> X\end{verbatim}\ecode X X\subsection{Built-in Module {\tt posix}} @@ -757,16 +757,16 @@ Ximport stdwin Xfrom stdwinevents import * X Xdef main(): -X mywin = stdwin.open('Hello') -X # -X while 1: -X (type, win, detail) = stdwin.getevent() -X if type = WE_DRAW: -X draw = win.begindrawing() -X draw.text((0, 0), 'Hello, world') -X del draw -X elif type = WE_CLOSE: -X break +X mywin = stdwin.open('Hello') +X # +X while 1: +X (type, win, detail) = stdwin.getevent() +X if type = WE_DRAW: +X draw = win.begindrawing() +X draw.text((0, 0), 'Hello, world') +X del draw +X elif type = WE_CLOSE: +X break X Xmain() X\end{verbatim}\ecode @@ -844,7 +844,7 @@ XFor example: X\bcode\begin{verbatim} X>>> amoeba.name_lookup('/profile/cap') Xaa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a -X>>> +X>>> X\end{verbatim}\ecode XThe following methods are defined for capability objects. X\begin{description} @@ -943,7 +943,7 @@ X%.br XAmplifies a chunk of samples by a variable factor changing from X{\tt f1}/256 to {\tt f2}/256. XNegative factors are allowed. -XResulting values that are to large to fit in a byte are clipped. +XResulting values that are to large to fit in a byte are clipped. X\funcitem{reverse}{buf} X%.br XReturns a chunk of samples backwards. @@ -1064,7 +1064,7 @@ Xis called for the normal, and then X{\tt v3f()} Xis called for the point. X\funcitem{vnarray}{} -XSimilar to +XSimilar to X{\tt nvarray()} Xbut the pairs have the point first and the normal second. X\funcitem{nurbssurface}{s\_k[], t\_k[], ctl[][], s\_ord, t\_ord, type} @@ -1106,22 +1106,22 @@ X\bcode\begin{verbatim} Ximport gl, GL, time X Xdef main(): -X gl.foreground() -X gl.prefposition(500, 900, 500, 900) -X w = gl.winopen('CrissCross') -X gl.ortho2(0.0, 400.0, 0.0, 400.0) -X gl.color(GL.WHITE) -X gl.clear() -X gl.color(GL.RED) -X gl.bgnline() -X gl.v2f(0.0, 0.0) -X gl.v2f(400.0, 400.0) -X gl.endline() -X gl.bgnline() -X gl.v2f(400.0, 0.0) -X gl.v2f(0.0, 400.0) -X gl.endline() -X time.sleep(5) +X gl.foreground() +X gl.prefposition(500, 900, 500, 900) +X w = gl.winopen('CrissCross') +X gl.ortho2(0.0, 400.0, 0.0, 400.0) +X gl.color(GL.WHITE) +X gl.clear() +X gl.color(GL.RED) +X gl.bgnline() +X gl.v2f(0.0, 0.0) +X gl.v2f(400.0, 400.0) +X gl.endline() +X gl.bgnline() +X gl.v2f(400.0, 0.0) +X gl.v2f(0.0, 400.0) +X gl.endline() +X time.sleep(5) X Xmain() X\end{verbatim}\ecode @@ -1156,12 +1156,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1197,410 +1197,410 @@ X#include "intobject.h" X#include "listobject.h" X Xtypedef struct s_loopstruct { -X struct s_loopstruct *l_next; /* Make a list of it */ -X TscOperand l_label; /* Indentify the loop */ -X int l_index; /* The index of the list */ -X int l_size; /* The size of the list */ -X int l_retaddr; /* Addres to jump back */ -X int l_endaddr; /* Addres to jump to end */ -X object *l_list; /* The list to append to */ +X struct s_loopstruct *l_next; /* Make a list of it */ +X TscOperand l_label; /* Indentify the loop */ +X int l_index; /* The index of the list */ +X int l_size; /* The size of the list */ +X int l_retaddr; /* Addres to jump back */ +X int l_endaddr; /* Addres to jump to end */ +X object *l_list; /* The list to append to */ X} TsLoop, *TpsLoop; X X X/* -X** This file contains the Stubcode interpreter. -X** All the instructions have there own function. The interpreter -X** reads an instruction from the data and if needed also an operand. -X** After this it calls the function that executes the instruction. +X** This file contains the Stubcode interpreter. +X** All the instructions have there own function. The interpreter +X** reads an instruction from the data and if needed also an operand. +X** After this it calls the function that executes the instruction. X*/ X Xstruct sc_ProcessBlock { -X object **stack; -X unsigned char *buffer, *data; -X int sp, bp, pc, maxbufsize, datsize; -X header hdr; -X TpsLoop loops; +X object **stack; +X unsigned char *buffer, *data; +X int sp, bp, pc, maxbufsize, datsize; +X header hdr; +X TpsLoop loops; X}; X Xextern getcapability(); X X/* -X * Clean up the mess the loops make. +X * Clean up the mess the loops make. X */ X Xstatic void XxCleanUpLoops(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X TpsLoop prev, this; -X -X if (sc_pb->loops == NULL) -X return; -X prev = sc_pb->loops; -X this = sc_pb->loops->l_next; -X while(this) { -X free((char *)prev); -X prev = this; -X this = this->l_next; -X } -X free((char *)prev); +X TpsLoop prev, this; +X +X if (sc_pb->loops == NULL) +X return; +X prev = sc_pb->loops; +X this = sc_pb->loops->l_next; +X while(this) { +X free((char *)prev); +X prev = this; +X this = this->l_next; +X } +X free((char *)prev); X} X Xstatic int Xfindendloop(label, sc_pb) -X TscOperand label; -X struct sc_ProcessBlock *sc_pb; +X TscOperand label; +X struct sc_ProcessBlock *sc_pb; X{ -X TscOperand operand; -X TscOpcode opcode; -X int walk = sc_pb->pc, found = 0; -X -X while (!found && (walk < sc_pb->datsize)) { -X memcpy(&opcode, &sc_pb->data[walk], sizeof(TscOpcode)); -X walk += sizeof(TscOpcode); -X if (opcode & (FLAGS | OPERAND)) { -X memcpy(&operand, &sc_pb->data[walk], sizeof(TscOperand)); -X walk += sizeof(TscOperand); -X } -X if (opcode == EndLoop) -X if (operand == label) found = 1; -X } -X if (found) -X return walk; -X return -1; +X TscOperand operand; +X TscOpcode opcode; +X int walk = sc_pb->pc, found = 0; +X +X while (!found && (walk < sc_pb->datsize)) { +X memcpy(&opcode, &sc_pb->data[walk], sizeof(TscOpcode)); +X walk += sizeof(TscOpcode); +X if (opcode & (FLAGS | OPERAND)) { +X memcpy(&operand, &sc_pb->data[walk], sizeof(TscOperand)); +X walk += sizeof(TscOperand); +X } +X if (opcode == EndLoop) +X if (operand == label) found = 1; +X } +X if (found) +X return walk; +X return -1; X} X Xstatic int Xfindloop(ret, label, sc_pb) -X TpsLoop *ret; -X TscOperand label; -X struct sc_ProcessBlock *sc_pb; +X TpsLoop *ret; +X TscOperand label; +X struct sc_ProcessBlock *sc_pb; X{ -X TpsLoop walk; -X -X for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { -X if (walk->l_label == label) break; -X } -X if (walk == NULL) { -X TpsLoop newloop; -X -X newloop = (TpsLoop)malloc(sizeof(TsLoop)); -X if (newloop == NULL) { -X err_nomem(); -X return -1; -X } -X newloop->l_label = label; -X newloop->l_index = 0; -X newloop->l_retaddr = sc_pb->pc - (sizeof(TscOpcode) + sizeof(TscOperand)); -X /* -X ** We need a correction because the pc points to -X ** the instruction after the XXXLoop. -X */ -X if ((newloop->l_endaddr = findendloop(label, sc_pb)) < 0) { -X free((char *)newloop); -X err_scerr(NoEndLoop); -X return -1; -X } -X newloop->l_list = NULL; -X newloop->l_next = sc_pb->loops; -X sc_pb->loops = newloop; -X *ret = newloop; -X return 1; -X } -X *ret = walk; -X return 0; +X TpsLoop walk; +X +X for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { +X if (walk->l_label == label) break; +X } +X if (walk == NULL) { +X TpsLoop newloop; +X +X newloop = (TpsLoop)malloc(sizeof(TsLoop)); +X if (newloop == NULL) { +X err_nomem(); +X return -1; +X } +X newloop->l_label = label; +X newloop->l_index = 0; +X newloop->l_retaddr = sc_pb->pc - (sizeof(TscOpcode) + sizeof(TscOperand)); +X /* +X ** We need a correction because the pc points to +X ** the instruction after the XXXLoop. +X */ +X if ((newloop->l_endaddr = findendloop(label, sc_pb)) < 0) { +X free((char *)newloop); +X err_scerr(NoEndLoop); +X return -1; +X } +X newloop->l_list = NULL; +X newloop->l_next = sc_pb->loops; +X sc_pb->loops = newloop; +X *ret = newloop; +X return 1; +X } +X *ret = walk; +X return 0; X} X X#ifdef 0 X Xstatic void Xremoveloop(this, sc_pb) -X TpsLoop this; -X struct sc_ProcessBlock *sc_pb; +X TpsLoop this; +X struct sc_ProcessBlock *sc_pb; X{ -X TpsLoop walk, prev = NULL; -X -X for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { -X if (walk->l_label == this->l_label) { -X if (prev != NULL) { -X prev->l_next = walk->l_next; -X } else { -X loop = walk->l_next; -X } -X free((char *)this); -X break; -X } -X prev = walk; -X } +X TpsLoop walk, prev = NULL; +X +X for (walk = sc_pb->loops; walk != NULL; walk = walk->l_next) { +X if (walk->l_label == this->l_label) { +X if (prev != NULL) { +X prev->l_next = walk->l_next; +X } else { +X loop = walk->l_next; +X } +X free((char *)this); +X break; +X } +X prev = walk; +X } X} X X#endif X Xstatic int Xinit(self, sc_pb) -X object *self; -X struct sc_ProcessBlock *sc_pb; +X object *self; +X struct sc_ProcessBlock *sc_pb; X{ Xobject *string; Xint datasize; X -X string = gettupleitem(self, STUBC); -X if (string == NULL) -X return -1; -X sc_pb->data = getstringvalue(string); -X if (sc_pb->data == NULL) -X return -1; -X datasize = (int)getstringsize(string); -X if (datasize == -1) -X return -1; -X sc_pb->stack = (object **)malloc(STKSIZE * sizeof(object *)); -X if (sc_pb->stack == NULL) { -X err_nomem(); -X return -1; -X } -X sc_pb->bp = sc_pb->sp = sc_pb->pc = 0; -X sc_pb->loops = NULL; -X return datasize; +X string = gettupleitem(self, STUBC); +X if (string == NULL) +X return -1; +X sc_pb->data = getstringvalue(string); +X if (sc_pb->data == NULL) +X return -1; +X datasize = (int)getstringsize(string); +X if (datasize == -1) +X return -1; +X sc_pb->stack = (object **)malloc(STKSIZE * sizeof(object *)); +X if (sc_pb->stack == NULL) { +X err_nomem(); +X return -1; +X } +X sc_pb->bp = sc_pb->sp = sc_pb->pc = 0; +X sc_pb->loops = NULL; +X return datasize; X} X Xstatic void reinit(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X int i; +X int i; X -X sc_pb->bp = 0; -X for (i = 0; i < sc_pb->sp; i++) { -X DECREF(sc_pb->stack[i]); -X } -X sc_pb->sp = 0; +X sc_pb->bp = 0; +X for (i = 0; i < sc_pb->sp; i++) { +X DECREF(sc_pb->stack[i]); +X } +X sc_pb->sp = 0; X} X Xstatic void UnInit(self, sc_pb) -X object *self; -X struct sc_ProcessBlock *sc_pb; +X object *self; +X struct sc_ProcessBlock *sc_pb; X{ -X int i; +X int i; X -X free(sc_pb->buffer); -X reinit(sc_pb); -X free((char *)sc_pb->stack); -X xCleanUpLoops(sc_pb); +X free(sc_pb->buffer); +X reinit(sc_pb); +X free((char *)sc_pb->stack); +X xCleanUpLoops(sc_pb); X} X Xstatic object * Xstacktop(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ X -X if (sc_pb->sp == 0) -X return err_scerr(StackUnderflow); -X if (sc_pb->sp == (STKSIZE + 1)) -X return err_scerr(StackOverflow); -X return sc_pb->stack[sc_pb->sp - 1]; +X if (sc_pb->sp == 0) +X return err_scerr(StackUnderflow); +X if (sc_pb->sp == (STKSIZE + 1)) +X return err_scerr(StackOverflow); +X return sc_pb->stack[sc_pb->sp - 1]; X} X X/* -X * Push an object on the stack. +X * Push an object on the stack. X */ Xstatic int XxPush(element, sc_pb) -X object *element; -X struct sc_ProcessBlock *sc_pb; +X object *element; +X struct sc_ProcessBlock *sc_pb; X{ X -X if (sc_pb->sp >= STKSIZE) { -X err_scerr(StackOverflow); -X return -1; -X } -X if (element == NULL) { -X err_scerr(ElementIsNull); -X return -1; -X } -X INCREF(element); +X if (sc_pb->sp >= STKSIZE) { +X err_scerr(StackOverflow); +X return -1; +X } +X if (element == NULL) { +X err_scerr(ElementIsNull); +X return -1; +X } +X INCREF(element); X#ifdef STACK_TRACE -X printf("pushed :"); -X printobject(element, stdout, 0); -X printf("\n"); +X printf("pushed :"); +X printobject(element, stdout, 0); +X printf("\n"); X#endif -X sc_pb->stack[sc_pb->sp++] = element; -X return 0; +X sc_pb->stack[sc_pb->sp++] = element; +X return 0; X} X X/* -X * Perform the RPC. +X * Perform the RPC. X */ Xstatic int XxTrans(self,cmd, sc_pb) -X object *self; -X TscOperand cmd; -X struct sc_ProcessBlock *sc_pb; +X object *self; +X TscOperand cmd; +X struct sc_ProcessBlock *sc_pb; X{ -X short ret; -X capability cap; -X object *capobj; -X -X if ((capobj = gettupleitem(self, CAP)) == NULL) -X return -1; -X if (getcapability(capobj, &cap) == -1) -X return -1; -X sc_pb->hdr.h_port = cap.cap_port; -X sc_pb->hdr.h_priv = cap.cap_priv; -X sc_pb->hdr.h_command = (command)cmd; +X short ret; +X capability cap; +X object *capobj; +X +X if ((capobj = gettupleitem(self, CAP)) == NULL) +X return -1; +X if (getcapability(capobj, &cap) == -1) +X return -1; +X sc_pb->hdr.h_port = cap.cap_port; +X sc_pb->hdr.h_priv = cap.cap_priv; +X sc_pb->hdr.h_command = (command)cmd; X#ifdef SCDEBUG -X printf("bp = %d maxbufsize = %d\n",sc_pb->bp, sc_pb->maxbufsize); -X { -X int i; -X -X for (i = 0; i < sc_pb->bp; i++) { -X printf("%x ", sc_pb->buffer[i]); -X } -X } -X printf("\n"); +X printf("bp = %d maxbufsize = %d\n",sc_pb->bp, sc_pb->maxbufsize); +X { +X int i; +X +X for (i = 0; i < sc_pb->bp; i++) { +X printf("%x ", sc_pb->buffer[i]); +X } +X } +X printf("\n"); X#endif -X ret = trans(&sc_pb->hdr, sc_pb->buffer, (bufsize) sc_pb->bp, -X &sc_pb->hdr, sc_pb->buffer, (bufsize)sc_pb->maxbufsize); +X ret = trans(&sc_pb->hdr, sc_pb->buffer, (bufsize) sc_pb->bp, +X &sc_pb->hdr, sc_pb->buffer, (bufsize)sc_pb->maxbufsize); X#ifdef SCDEBUG -X printf("after Trans:ret = %d\n",ret); -X { -X int i; -X -X for (i = 0; i < ret; i++) { -X printf("%x ", sc_pb->buffer[i]); -X } -X } -X printf("\n"); +X printf("after Trans:ret = %d\n",ret); +X { +X int i; +X +X for (i = 0; i < ret; i++) { +X printf("%x ", sc_pb->buffer[i]); +X } +X } +X printf("\n"); X#endif -X if (ERR_STATUS(ret)) { -X amoeba_error(ERR_CONVERT(ret)); -X return -1; -X } -X if (sc_pb->hdr.h_status != 0) { -X object *v; -X -X if ((v = newintobject(sc_pb->hdr.h_status)) == NULL) -X return -1; -X err_scerrset(TransError, v, "Trans"); -X DECREF(v); -X return -1; -X } -X reinit(sc_pb); -X return 0; +X if (ERR_STATUS(ret)) { +X amoeba_error(ERR_CONVERT(ret)); +X return -1; +X } +X if (sc_pb->hdr.h_status != 0) { +X object *v; +X +X if ((v = newintobject(sc_pb->hdr.h_status)) == NULL) +X return -1; +X err_scerrset(TransError, v, "Trans"); +X DECREF(v); +X return -1; +X } +X reinit(sc_pb); +X return 0; X} X X/* -X * Test the tuple size. +X * Test the tuple size. X */ Xstatic int XxTTupleS(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *tuple; -X -X if ((tuple = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_tupleobject(tuple)) -X return err_scerrset(TypeFailure, tuple, "TTupleS"); -X if (gettuplesize(tuple) != (unsigned int)size) -X return err_scerrset(SizeError, tuple, "TTupleS"); -X return 0; +X object *tuple; +X +X if ((tuple = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_tupleobject(tuple)) +X return err_scerrset(TypeFailure, tuple, "TTupleS"); +X if (gettuplesize(tuple) != (unsigned int)size) +X return err_scerrset(SizeError, tuple, "TTupleS"); +X return 0; X} X X/* -X * Unpack a tuple +X * Unpack a tuple X */ Xstatic int XxUnpack(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *tuple, *element; -X int i; -X -X if (size < (TscOperand)2) { -X element = newintobject(size); -X if (element == NULL) -X return -1; -X return err_scerrset(SizeError, element, "Unpack"); -X } -X if ((tuple = stacktop(sc_pb)) == NULL) -X return -1; -X INCREF(tuple); -X if (xPop((TscOperand) 1, sc_pb) != 0) { -X DECREF(tuple); -X return -1; -X } -X for (i = 0; i < (int)size; i++) { -X if ((element = gettupleitem(tuple, i)) == NULL) { -X DECREF(tuple); -X return -1; -X } -X if (xPush(element, sc_pb) != 0) { -X DECREF(tuple); -X return -1; -X } -X } -X DECREF(tuple); -X return 0; +X object *tuple, *element; +X int i; +X +X if (size < (TscOperand)2) { +X element = newintobject(size); +X if (element == NULL) +X return -1; +X return err_scerrset(SizeError, element, "Unpack"); +X } +X if ((tuple = stacktop(sc_pb)) == NULL) +X return -1; +X INCREF(tuple); +X if (xPop((TscOperand) 1, sc_pb) != 0) { +X DECREF(tuple); +X return -1; +X } +X for (i = 0; i < (int)size; i++) { +X if ((element = gettupleitem(tuple, i)) == NULL) { +X DECREF(tuple); +X return -1; +X } +X if (xPush(element, sc_pb) != 0) { +X DECREF(tuple); +X return -1; +X } +X } +X DECREF(tuple); +X return 0; X} X X/* -X * Marshal the Ailword to a headerfiels. +X * Marshal the Ailword to a headerfiels. X */ Xstatic int XxAilword(headerfield, sc_pb) -X TscOperand headerfield; -X struct sc_ProcessBlock *sc_pb; +X TscOperand headerfield; +X struct sc_ProcessBlock *sc_pb; X{ X -X switch(headerfield) { -X -X case H_EXTRA: -X sc_pb->hdr.h_extra = (uint16)_ailword; -X return 0; -X -X case H_SIZE: -X sc_pb->hdr.h_size = (bufsize)_ailword; -X return 0; -X -X case H_OFFSET: -X sc_pb->hdr.h_offset = (int32)_ailword; -X return 0; -X -X default: -X { -X object *v; -X -X if ((v = newintobject(headerfield)) == NULL) -X return -1; -X return err_scerrset(FlagError, v, "Ailword"); -X } -X } +X switch(headerfield) { +X +X case H_EXTRA: +X sc_pb->hdr.h_extra = (uint16)_ailword; +X return 0; +X +X case H_SIZE: +X sc_pb->hdr.h_size = (bufsize)_ailword; +X return 0; +X +X case H_OFFSET: +X sc_pb->hdr.h_offset = (int32)_ailword; +X return 0; +X +X default: +X { +X object *v; +X +X if ((v = newintobject(headerfield)) == NULL) +X return -1; +X return err_scerrset(FlagError, v, "Ailword"); +X } +X } X} X Xstatic int XxStringS(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X object *size, *string; -X int s; -X -X if ((string = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_stringobject(string)) -X return err_scerrset(TypeFailure, string, "StringS"); -X if ((s = getstringsize(string)) < 0) -X return -1; -X if (xPop((TscOperand) 1, sc_pb) != 0) -X return -1; -X if ((size = newintobject(s)) == NULL) -X return -1; -X if (xPush(size, sc_pb) != 0) { -X DECREF(size); -X return -1; -X } -X DECREF(size); -X return 0; +X object *size, *string; +X int s; +X +X if ((string = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_stringobject(string)) +X return err_scerrset(TypeFailure, string, "StringS"); +X if ((s = getstringsize(string)) < 0) +X return -1; +X if (xPop((TscOperand) 1, sc_pb) != 0) +X return -1; +X if ((size = newintobject(s)) == NULL) +X return -1; +X if (xPush(size, sc_pb) != 0) { +X DECREF(size); +X return -1; +X } +X DECREF(size); +X return 0; X} X X/* @@ -1608,27 +1608,27 @@ X * X */ Xstatic int XxListS(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X object *size, *list; -X int s; -X -X if ((list = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_listobject(list)) -X return err_scerrset(TypeFailure, list, "ListS"); -X if ((s = getlistsize(list)) < 0) -X return -1; -X if (xPop((TscOperand) 1, sc_pb) != 0) -X return -1; -X if ((size = newintobject(s)) == NULL) -X return -1; -X if (xPush(size, sc_pb) != 0) { -X DECREF(size); -X return -1; -X } -X DECREF(size); -X return 0; +X object *size, *list; +X int s; +X +X if ((list = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_listobject(list)) +X return err_scerrset(TypeFailure, list, "ListS"); +X if ((s = getlistsize(list)) < 0) +X return -1; +X if (xPop((TscOperand) 1, sc_pb) != 0) +X return -1; +X if ((size = newintobject(s)) == NULL) +X return -1; +X if (xPush(size, sc_pb) != 0) { +X DECREF(size); +X return -1; +X } +X DECREF(size); +X return 0; X} X X/* @@ -1636,657 +1636,657 @@ X * Marshal a fixed string to the buffer. X */ Xstatic int XxPutFS(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *string; -X char *str; -X -X if ((string = stacktop(sc_pb)) == NULL) { -X return -1; -X } -X if (!is_stringobject(string)) -X return err_scerrset(TypeFailure, string, "PutFS"); -X if (getstringsize(string) != size) -X return err_scerrset(SizeError, string, "PutFS"); -X if ((str = getstringvalue(string)) == NULL) -X return -1; -X if ((size + sc_pb->bp) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&sc_pb->buffer[sc_pb->bp], str, (int)size); -X sc_pb->bp += size; -X return xPop((TscOperand) 1, sc_pb); +X object *string; +X char *str; +X +X if ((string = stacktop(sc_pb)) == NULL) { +X return -1; +X } +X if (!is_stringobject(string)) +X return err_scerrset(TypeFailure, string, "PutFS"); +X if (getstringsize(string) != size) +X return err_scerrset(SizeError, string, "PutFS"); +X if ((str = getstringvalue(string)) == NULL) +X return -1; +X if ((size + sc_pb->bp) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&sc_pb->buffer[sc_pb->bp], str, (int)size); +X sc_pb->bp += size; +X return xPop((TscOperand) 1, sc_pb); X} X X X/* -X * Test the size of a string or list +X * Test the size of a string or list X */ Xstatic int XxTStringSeq(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *string; -X -X if ((string = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_stringobject(string)) -X return err_scerrset(TypeFailure, string, "TStringSeq"); -X if (getstringsize(string) != size) -X return err_scerrset(SizeError, string, "TStringSeq"); -X return 0; +X object *string; +X +X if ((string = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_stringobject(string)) +X return err_scerrset(TypeFailure, string, "TStringSeq"); +X if (getstringsize(string) != size) +X return err_scerrset(SizeError, string, "TStringSeq"); +X return 0; X} X Xstatic int XxTStringSlt(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *string; -X -X if ((string = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_stringobject(string)) -X return err_scerrset(TypeFailure, string, "TStringSlt"); -X if (getstringsize(string) > size) -X return err_scerrset(SizeError, string, "TStringSlt"); -X return 0; +X object *string; +X +X if ((string = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_stringobject(string)) +X return err_scerrset(TypeFailure, string, "TStringSlt"); +X if (getstringsize(string) > size) +X return err_scerrset(SizeError, string, "TStringSlt"); +X return 0; X} X Xstatic int XxTListSeq(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *list; -X -X if ((list = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_listobject(list)) -X return err_scerrset(TypeFailure, list, "TListSeq"); -X if (getlistsize(list) != size) -X return err_scerrset(SizeError, list, "TListSeq"); -X return 0; +X object *list; +X +X if ((list = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_listobject(list)) +X return err_scerrset(TypeFailure, list, "TListSeq"); +X if (getlistsize(list) != size) +X return err_scerrset(SizeError, list, "TListSeq"); +X return 0; X} X Xstatic int XxTListSlt(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *list; -X -X if ((list = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_listobject(list)) -X return err_scerrset(TypeFailure, list, "TListSlt"); -X if (getlistsize(list) > size) -X return err_scerrset(SizeError, list, "TListSlt"); -X return 0; +X object *list; +X +X if ((list = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_listobject(list)) +X return err_scerrset(TypeFailure, list, "TListSlt"); +X if (getlistsize(list) > size) +X return err_scerrset(SizeError, list, "TListSlt"); +X return 0; X} X Xstatic int XxPutVS(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X object *string; -X char *str; -X int size; -X -X if ((string = stacktop(sc_pb)) == NULL) -X return -1; -X if ((size = getstringsize(string)) < 0) -X return (size == -1 ? -1 : err_scerrset(SizeError, string, "PutVS")); -X if ((str = getstringvalue(string)) == NULL) -X return -1; -X if (sc_pb->bp + size > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&sc_pb->buffer[sc_pb->bp], str, size); -X sc_pb->bp += size; -X return xPop((TscOperand) 1, sc_pb); +X object *string; +X char *str; +X int size; +X +X if ((string = stacktop(sc_pb)) == NULL) +X return -1; +X if ((size = getstringsize(string)) < 0) +X return (size == -1 ? -1 : err_scerrset(SizeError, string, "PutVS")); +X if ((str = getstringvalue(string)) == NULL) +X return -1; +X if (sc_pb->bp + size > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&sc_pb->buffer[sc_pb->bp], str, size); +X sc_pb->bp += size; +X return xPop((TscOperand) 1, sc_pb); X} X X/* -X * The loop instructions. +X * The loop instructions. X */ Xstatic int XxLoopPut(label, sc_pb) -X TscOperand label; -X struct sc_ProcessBlock *sc_pb; +X TscOperand label; +X struct sc_ProcessBlock *sc_pb; X{ -X TpsLoop this; -X object *list, *element; -X -X if (findloop(&this, label, sc_pb) < 0) -X return -1; -X if ((list = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_listobject(list)) -X return err_scerrset(TypeFailure, list, "LoopPut"); -X if (this->l_index >= getlistsize(list)) { -X sc_pb->pc = this->l_endaddr; -X /* -X ** Pop the list from the stack -X */ -X return xPop((TscOperand)1, sc_pb); -X } -X if ((element = getlistitem(list, this->l_index)) == NULL) -X return -1; -X return xPush(element, sc_pb); +X TpsLoop this; +X object *list, *element; +X +X if (findloop(&this, label, sc_pb) < 0) +X return -1; +X if ((list = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_listobject(list)) +X return err_scerrset(TypeFailure, list, "LoopPut"); +X if (this->l_index >= getlistsize(list)) { +X sc_pb->pc = this->l_endaddr; +X /* +X ** Pop the list from the stack +X */ +X return xPop((TscOperand)1, sc_pb); +X } +X if ((element = getlistitem(list, this->l_index)) == NULL) +X return -1; +X return xPush(element, sc_pb); X} X Xstatic int XxLoopGet(label, sc_pb) -X TscOperand label; -X struct sc_ProcessBlock *sc_pb; +X TscOperand label; +X struct sc_ProcessBlock *sc_pb; X{ -X TpsLoop this; -X object *element, *integer; -X int i; -X -X if ((i = findloop(&this, label, sc_pb)) < 0) -X return -1; -X else if (i == 1) { -X /* -X * It is the first time we enter LoopGet label -X */ -X if ((this->l_list = newlistobject(0)) == NULL) -X return -1; -X if ((integer = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_intobject(integer)) -X return err_scerrset(TypeFailure, integer, "LoopGet"); -X this->l_size = getintvalue(integer); -X if (xPop((TscOperand) 1, sc_pb) != 0) -X return -1; -X } else { -X if ((element = stacktop(sc_pb)) == NULL) -X return -1; -X if (addlistitem(this->l_list, element) != 0) -X return -1; -X if (xPop((TscOperand) 1, sc_pb) != 0) -X return -1; -X } -X if (this->l_index >= this->l_size) { -X int ret; -X -X sc_pb->pc = this->l_endaddr; -X ret = xPush(this->l_list, sc_pb); -X DECREF(this->l_list); -X return ret; -X } -X return 0; +X TpsLoop this; +X object *element, *integer; +X int i; +X +X if ((i = findloop(&this, label, sc_pb)) < 0) +X return -1; +X else if (i == 1) { +X /* +X * It is the first time we enter LoopGet label +X */ +X if ((this->l_list = newlistobject(0)) == NULL) +X return -1; +X if ((integer = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_intobject(integer)) +X return err_scerrset(TypeFailure, integer, "LoopGet"); +X this->l_size = getintvalue(integer); +X if (xPop((TscOperand) 1, sc_pb) != 0) +X return -1; +X } else { +X if ((element = stacktop(sc_pb)) == NULL) +X return -1; +X if (addlistitem(this->l_list, element) != 0) +X return -1; +X if (xPop((TscOperand) 1, sc_pb) != 0) +X return -1; +X } +X if (this->l_index >= this->l_size) { +X int ret; +X +X sc_pb->pc = this->l_endaddr; +X ret = xPush(this->l_list, sc_pb); +X DECREF(this->l_list); +X return ret; +X } +X return 0; X} X Xstatic int XxEndLoop(label, sc_pb) -X TscOperand label; -X struct sc_ProcessBlock *sc_pb; +X TscOperand label; +X struct sc_ProcessBlock *sc_pb; X{ -X TpsLoop this; +X TpsLoop this; X -X if (findloop(&this, label, sc_pb) < 0) -X return -1; -X this ->l_index += 1; -X sc_pb->pc = this->l_retaddr; -X return 0; +X if (findloop(&this, label, sc_pb) < 0) +X return -1; +X this ->l_index += 1; +X sc_pb->pc = this->l_retaddr; +X return 0; X} X Xstatic int XxPutI(flags, sc_pb) -X TscOperand flags; -X struct sc_ProcessBlock *sc_pb; +X TscOperand flags; +X struct sc_ProcessBlock *sc_pb; X{ -X object *integer; -X -X if ((integer = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_intobject(integer)) -X return err_scerrset(TypeFailure, integer, "PutI"); -X if (flags & ALL_FIELDS) { -X long i; -X -X /* -X * The integer must be marshalles in the header. -X * No type casting according to the type flag because -X * we have to cast to the headerfield types. -X */ -X i = getintvalue(integer); -X switch(flags & ALL_FIELDS) { -X -X case H_EXTRA: -X sc_pb->hdr.h_extra = (uint16)i; -X break; -X -X case H_SIZE: -X sc_pb->hdr.h_size = (bufsize)i; -X break; -X -X case H_OFFSET: -X sc_pb->hdr.h_offset = (int32)i; -X break; -X -X default: -X if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) -X return -1; -X err_scerrset(FlagError, integer, "Ailword"); -X DECREF(integer); -X return -1; -X } -X } else { -X long i; -X -X i = getintvalue(integer); -X switch(flags & ALLTYPES) { -X -X case 0: -X { -X int16 x; -X -X x = (int16)i; -X if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int16)); -X sc_pb->bp += sizeof(int16); -X break; -X } -X -X case NOSIGN: -X { -X uint16 x; -X -X x = (uint16)i; -X if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint16)); -X sc_pb->bp += sizeof(uint16); -X break; -X } -X -X case INT32: -X { -X int32 x; -X -X x = (int32)i; -X if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int32)); -X sc_pb->bp += sizeof(int32); -X break; -X } -X -X case INT32 | NOSIGN: -X { -X uint32 x; -X -X x = (uint32)i; -X if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint32)); -X sc_pb->bp += sizeof(uint32); -X break; -X } -X default: -X { -X object *x; -X -X if ((x = newintobject(flags)) == NULL) -X return -1; -X err_scerrset(FlagError, x, "PutI"); -X DECREF(x); -X return -1; -X } -X } -X } -X return xPop((TscOperand)1, sc_pb); +X object *integer; +X +X if ((integer = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_intobject(integer)) +X return err_scerrset(TypeFailure, integer, "PutI"); +X if (flags & ALL_FIELDS) { +X long i; +X +X /* +X * The integer must be marshalles in the header. +X * No type casting according to the type flag because +X * we have to cast to the headerfield types. +X */ +X i = getintvalue(integer); +X switch(flags & ALL_FIELDS) { +X +X case H_EXTRA: +X sc_pb->hdr.h_extra = (uint16)i; +X break; +X +X case H_SIZE: +X sc_pb->hdr.h_size = (bufsize)i; +X break; +X +X case H_OFFSET: +X sc_pb->hdr.h_offset = (int32)i; +X break; +X +X default: +X if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) +X return -1; +X err_scerrset(FlagError, integer, "Ailword"); +X DECREF(integer); +X return -1; +X } +X } else { +X long i; +X +X i = getintvalue(integer); +X switch(flags & ALLTYPES) { +X +X case 0: +X { +X int16 x; +X +X x = (int16)i; +X if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int16)); +X sc_pb->bp += sizeof(int16); +X break; +X } +X +X case NOSIGN: +X { +X uint16 x; +X +X x = (uint16)i; +X if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint16)); +X sc_pb->bp += sizeof(uint16); +X break; +X } +X +X case INT32: +X { +X int32 x; +X +X x = (int32)i; +X if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(int32)); +X sc_pb->bp += sizeof(int32); +X break; +X } +X +X case INT32 | NOSIGN: +X { +X uint32 x; +X +X x = (uint32)i; +X if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&sc_pb->buffer[sc_pb->bp], &x, sizeof(uint32)); +X sc_pb->bp += sizeof(uint32); +X break; +X } +X default: +X { +X object *x; +X +X if ((x = newintobject(flags)) == NULL) +X return -1; +X err_scerrset(FlagError, x, "PutI"); +X DECREF(x); +X return -1; +X } +X } +X } +X return xPop((TscOperand)1, sc_pb); X} X Xstatic int XxPutC(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X capability cap; -X object *capobj; -X -X if ((capobj = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_capobj(capobj)) -X return err_scerrset(TypeFailure, capobj, "xPutC"); -X if (getcapability(capobj, &cap) != 0) -X return -1; -X if ((sc_pb->bp + CAPSIZE) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&sc_pb->buffer[sc_pb->bp], &cap, CAPSIZE); -X sc_pb->bp += CAPSIZE; -X return xPop((TscOperand) 1, sc_pb); +X capability cap; +X object *capobj; +X +X if ((capobj = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_capobj(capobj)) +X return err_scerrset(TypeFailure, capobj, "xPutC"); +X if (getcapability(capobj, &cap) != 0) +X return -1; +X if ((sc_pb->bp + CAPSIZE) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&sc_pb->buffer[sc_pb->bp], &cap, CAPSIZE); +X sc_pb->bp += CAPSIZE; +X return xPop((TscOperand) 1, sc_pb); X} X Xstatic int XxDup(n, sc_pb) -X TscOperand n; -X struct sc_ProcessBlock *sc_pb; +X TscOperand n; +X struct sc_ProcessBlock *sc_pb; X{ X -X if ((int)n > sc_pb->sp) { -X object *i; +X if ((int)n > sc_pb->sp) { +X object *i; X -X if ((i = newintobject((long)n)) == NULL) -X return -1; -X err_scerrset(RangeError, i, "Dup"); -X DECREF(i); -X return -1; -X } -X return xPush(sc_pb->stack[sc_pb->sp - n], sc_pb); +X if ((i = newintobject((long)n)) == NULL) +X return -1; +X err_scerrset(RangeError, i, "Dup"); +X DECREF(i); +X return -1; +X } +X return xPush(sc_pb->stack[sc_pb->sp - n], sc_pb); X} X Xstatic int XxPop(n, sc_pb) -X TscOperand n; -X struct sc_ProcessBlock *sc_pb; +X TscOperand n; +X struct sc_ProcessBlock *sc_pb; X{ -X int i; -X -X if ((sc_pb->sp - (int)n) < 0) { -X err_scerr(StackUnderflow); -X return -1; -X } -X for (i = 0; i < (int)n; i++) { -X sc_pb->sp--; +X int i; +X +X if ((sc_pb->sp - (int)n) < 0) { +X err_scerr(StackUnderflow); +X return -1; +X } +X for (i = 0; i < (int)n; i++) { +X sc_pb->sp--; X#ifdef STACK_TRACE -X printf("popped :"); -X printobject(sc_pb->stack[sc_pb->sp], stdout, 0); -X printf("\n"); +X printf("popped :"); +X printobject(sc_pb->stack[sc_pb->sp], stdout, 0); +X printf("\n"); X#endif -X DECREF(sc_pb->stack[sc_pb->sp]); -X } -X return 0; +X DECREF(sc_pb->stack[sc_pb->sp]); +X } +X return 0; X} X Xstatic int XxAlign(n, sc_pb) -X TscOperand n; -X struct sc_ProcessBlock *sc_pb; +X TscOperand n; +X struct sc_ProcessBlock *sc_pb; X{ -X int align = sc_pb->bp % (int)n; +X int align = sc_pb->bp % (int)n; X X#ifdef SCDEBUG -X printf("Old bp = %d\n", sc_pb->bp); +X printf("Old bp = %d\n", sc_pb->bp); X#endif -X sc_pb->bp += (align == 0) ? 0 : ((int)n - align); +X sc_pb->bp += (align == 0) ? 0 : ((int)n - align); X#ifdef SCDEBUG -X printf("New bp = %d\n", sc_pb->bp); +X printf("New bp = %d\n", sc_pb->bp); X#endif -X return 0; +X return 0; X} X Xstatic int XxPack(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *element, *tuple; -X int i, ret; -X -X if ((tuple = newtupleobject((int)size)) == NULL) -X return -1; -X for (i = 0; i < (int)size; i++) { -X if ((element = stacktop(sc_pb)) == NULL) -X return -1; -X if (settupleitem(tuple, (int)size - i - 1, element) != 0) -X return -1; -X INCREF(element); -X if (xPop((TscOperand) 1, sc_pb) != 0) -X return -1; -X } -X ret = xPush(tuple, sc_pb); -X DECREF(tuple); -X return ret; +X object *element, *tuple; +X int i, ret; +X +X if ((tuple = newtupleobject((int)size)) == NULL) +X return -1; +X for (i = 0; i < (int)size; i++) { +X if ((element = stacktop(sc_pb)) == NULL) +X return -1; +X if (settupleitem(tuple, (int)size - i - 1, element) != 0) +X return -1; +X INCREF(element); +X if (xPop((TscOperand) 1, sc_pb) != 0) +X return -1; +X } +X ret = xPush(tuple, sc_pb); +X DECREF(tuple); +X return ret; X} X Xstatic int XxGetVS(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X object *string, *integer; -X int size; -X -X if ((integer = stacktop(sc_pb)) == NULL) -X return -1; -X if (!is_intobject(integer)) -X return err_scerrset(TypeFailure, integer, "GetVS"); -X size = getintvalue(integer); -X if ((sc_pb->bp + size) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], size)) == NULL) -X return -1; -X sc_pb->bp += size; -X if (xPop((TscOperand) 1, sc_pb) != 0) -X return -1; -X if (xPush(string, sc_pb) != 0) { -X return -1; -X } -X DECREF(string); -X return 0; +X object *string, *integer; +X int size; +X +X if ((integer = stacktop(sc_pb)) == NULL) +X return -1; +X if (!is_intobject(integer)) +X return err_scerrset(TypeFailure, integer, "GetVS"); +X size = getintvalue(integer); +X if ((sc_pb->bp + size) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], size)) == NULL) +X return -1; +X sc_pb->bp += size; +X if (xPop((TscOperand) 1, sc_pb) != 0) +X return -1; +X if (xPush(string, sc_pb) != 0) { +X return -1; +X } +X DECREF(string); +X return 0; X} X Xstatic int XxGetFS(size, sc_pb) -X TscOperand size; -X struct sc_ProcessBlock *sc_pb; +X TscOperand size; +X struct sc_ProcessBlock *sc_pb; X{ -X object *string; -X -X if ((sc_pb->bp + (int)size) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], (int)size)) == NULL) -X return -1; -X sc_pb->bp += (int)size; -X if(xPush(string, sc_pb) != 0) { -X return -1; -X } -X DECREF(string); -X return 0; +X object *string; +X +X if ((sc_pb->bp + (int)size) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X if ((string = newsizedstringobject(&sc_pb->buffer[sc_pb->bp], (int)size)) == NULL) +X return -1; +X sc_pb->bp += (int)size; +X if(xPush(string, sc_pb) != 0) { +X return -1; +X } +X DECREF(string); +X return 0; X} X Xstatic int XxGetI(flags, sc_pb) -X TscOperand flags; -X struct sc_ProcessBlock *sc_pb; +X TscOperand flags; +X struct sc_ProcessBlock *sc_pb; X{ -X object *integer; -X long i; -X -X if (flags & ALL_FIELDS) { -X -X switch(flags & ALL_FIELDS) { -X -X case H_EXTRA: -X i = (long)sc_pb->hdr.h_extra; -X break; -X -X case H_SIZE: -X i = (long)sc_pb->hdr.h_size; -X break; -X -X case H_OFFSET: -X i = (long)sc_pb->hdr.h_offset; -X break; -X -X default: -X if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) -X return -1; -X err_scerrset(FlagError, integer, "Ailword"); -X DECREF(integer); -X return -1; -X } -X } else { -X switch(flags & ALLTYPES) { -X -X case 0: -X { -X int16 x; -X -X if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int16)); -X sc_pb->bp += sizeof(int16); -X i = (long)x; -X break; -X } -X -X case NOSIGN: -X { -X uint16 x; -X -X if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint16)); -X sc_pb->bp += sizeof(uint16); -X i = (long)x; -X break; -X } -X -X case INT32: -X { -X int32 x; -X -X if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int32)); -X sc_pb->bp += sizeof(int32); -X i = (long)x; -X break; -X } -X -X case INT32 | NOSIGN: -X { -X uint32 x; -X -X if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint32)); -X sc_pb->bp += sizeof(uint32); -X i = (long)x; -X break; -X } -X default: -X { -X if ((integer = newintobject(flags)) == NULL) -X return -1; -X err_scerrset(FlagError, integer, "GetI"); -X DECREF(integer); -X return -1; -X } -X } -X } -X if ((integer = newintobject(i)) == NULL) -X return -1; -X if (xPush(integer, sc_pb) != 0) { -X DECREF(integer); -X return -1; -X } -X DECREF(integer); -X return 0; +X object *integer; +X long i; +X +X if (flags & ALL_FIELDS) { +X +X switch(flags & ALL_FIELDS) { +X +X case H_EXTRA: +X i = (long)sc_pb->hdr.h_extra; +X break; +X +X case H_SIZE: +X i = (long)sc_pb->hdr.h_size; +X break; +X +X case H_OFFSET: +X i = (long)sc_pb->hdr.h_offset; +X break; +X +X default: +X if ((integer = newintobject(flags & ALL_FIELDS)) == NULL) +X return -1; +X err_scerrset(FlagError, integer, "Ailword"); +X DECREF(integer); +X return -1; +X } +X } else { +X switch(flags & ALLTYPES) { +X +X case 0: +X { +X int16 x; +X +X if ((sc_pb->bp + sizeof(int16)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int16)); +X sc_pb->bp += sizeof(int16); +X i = (long)x; +X break; +X } +X +X case NOSIGN: +X { +X uint16 x; +X +X if ((sc_pb->bp + sizeof(uint16)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint16)); +X sc_pb->bp += sizeof(uint16); +X i = (long)x; +X break; +X } +X +X case INT32: +X { +X int32 x; +X +X if ((sc_pb->bp + sizeof(int32)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(int32)); +X sc_pb->bp += sizeof(int32); +X i = (long)x; +X break; +X } +X +X case INT32 | NOSIGN: +X { +X uint32 x; +X +X if ((sc_pb->bp + sizeof(uint32)) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&x, &sc_pb->buffer[sc_pb->bp], sizeof(uint32)); +X sc_pb->bp += sizeof(uint32); +X i = (long)x; +X break; +X } +X default: +X { +X if ((integer = newintobject(flags)) == NULL) +X return -1; +X err_scerrset(FlagError, integer, "GetI"); +X DECREF(integer); +X return -1; +X } +X } +X } +X if ((integer = newintobject(i)) == NULL) +X return -1; +X if (xPush(integer, sc_pb) != 0) { +X DECREF(integer); +X return -1; +X } +X DECREF(integer); +X return 0; X} X Xstatic int XxGetC(flags, sc_pb) -X TscOperand flags; -X struct sc_ProcessBlock *sc_pb; +X TscOperand flags; +X struct sc_ProcessBlock *sc_pb; X{ -X extern object *newcapobject(); -X object *capobj; -X capability cap; -X -X if ((int)flags != 0) { -X switch ((int)flags) { -X -X case PSEUDOFIELD: -X cap.cap_port = sc_pb->hdr.h_port; -X cap.cap_priv = sc_pb->hdr.h_priv; -X break; -X } -X } else { -X if ((CAPSIZE + sc_pb->bp) > sc_pb->maxbufsize) { -X err_scerr(BufferOverflow); -X return -1; -X } -X memcpy(&cap, &sc_pb->buffer[sc_pb->bp], CAPSIZE); -X } -X if ((capobj = newcapobject(&cap)) == NULL) -X return -1; -X return xPush(capobj, sc_pb); +X extern object *newcapobject(); +X object *capobj; +X capability cap; +X +X if ((int)flags != 0) { +X switch ((int)flags) { +X +X case PSEUDOFIELD: +X cap.cap_port = sc_pb->hdr.h_port; +X cap.cap_priv = sc_pb->hdr.h_priv; +X break; +X } +X } else { +X if ((CAPSIZE + sc_pb->bp) > sc_pb->maxbufsize) { +X err_scerr(BufferOverflow); +X return -1; +X } +X memcpy(&cap, &sc_pb->buffer[sc_pb->bp], CAPSIZE); +X } +X if ((capobj = newcapobject(&cap)) == NULL) +X return -1; +X return xPush(capobj, sc_pb); X} X Xstatic int XxEqual(sc_pb) -X struct sc_ProcessBlock *sc_pb; +X struct sc_ProcessBlock *sc_pb; X{ -X object *int1, *int2; -X -X if (sc_pb->sp < 2) { -X err_scerr(StackUnderflow); -X return -1; -X } -X int1 = sc_pb->stack[sc_pb->sp - 1]; -X int2 = sc_pb->stack[sc_pb->sp - 2]; -X if ((int1 == NULL) || (int2 == NULL)) -X return -1; -X if (!is_intobject(int1)) -X return err_scerrset(TypeFailure, int1, "Equal"); -X if (!is_intobject(int2)) -X return err_scerrset(TypeFailure, int2, "Equal"); -X if (getintvalue(int1) != getintvalue(int2)) { -X object *tmptuple; -X -X if ((tmptuple = newtupleobject(2)) == NULL) -X return -1; -X INCREF(int1); -X if (settupleitem(tmptuple, 0, int1) != 0) { -X DECREF(tmptuple); -X DECREF(int1); -X return -1; -X } -X if (settupleitem(tmptuple, 1, int2) != 0) { -X DECREF(tmptuple); -X DECREF(int2); -X return -1; -X } -X return err_scerrset(SizeError, tmptuple, "Equal"); -X } -X return 0; +X object *int1, *int2; +X +X if (sc_pb->sp < 2) { +X err_scerr(StackUnderflow); +X return -1; +X } +X int1 = sc_pb->stack[sc_pb->sp - 1]; +X int2 = sc_pb->stack[sc_pb->sp - 2]; +X if ((int1 == NULL) || (int2 == NULL)) +X return -1; +X if (!is_intobject(int1)) +X return err_scerrset(TypeFailure, int1, "Equal"); +X if (!is_intobject(int2)) +X return err_scerrset(TypeFailure, int2, "Equal"); +X if (getintvalue(int1) != getintvalue(int2)) { +X object *tmptuple; +X +X if ((tmptuple = newtupleobject(2)) == NULL) +X return -1; +X INCREF(int1); +X if (settupleitem(tmptuple, 0, int1) != 0) { +X DECREF(tmptuple); +X DECREF(int1); +X return -1; +X } +X if (settupleitem(tmptuple, 1, int2) != 0) { +X DECREF(tmptuple); +X DECREF(int2); +X return -1; +X } +X return err_scerrset(SizeError, tmptuple, "Equal"); +X } +X return 0; X} X Xobject * Xsc_interpreter(self, args) -X object *self, *args; +X object *self, *args; X{ XTscOpcode opcode; XTscOperand operand; @@ -2294,217 +2294,217 @@ Xint datasize, ret; Xobject *returnobject; Xstruct sc_ProcessBlock sc_pb; X -X if ((datasize = init(self, &sc_pb)) < 0) -X return NULL; -X memcpy(&opcode, sc_pb.data, sizeof(TscOpcode)); -X sc_pb.datsize = datasize; -X sc_pb.pc += sizeof(TscOpcode); -X if (opcode != BufSize) { -X free((char *)sc_pb.stack); -X return err_scerr(NoBufSize); -X } -X memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); -X sc_pb.pc += sizeof(TscOperand); -X sc_pb.buffer = (unsigned char *)malloc(operand); -X sc_pb.maxbufsize = (int)operand; -X if (sc_pb.buffer == NULL) { -X free((char *)sc_pb.stack); -X return err_nomem(); -X } -X memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); -X if (opcode != NoArgs) { -X if (xPush(args, &sc_pb) != 0) { -X UnInit(self, &sc_pb); -X return NULL; -X } -X } -X while (sc_pb.pc < datasize) { -X memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); -X sc_pb.pc += sizeof(TscOpcode); -X if (opcode & (OPERAND | FLAGS)) { -X memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); -X sc_pb.pc += sizeof(TscOperand); -X } +X if ((datasize = init(self, &sc_pb)) < 0) +X return NULL; +X memcpy(&opcode, sc_pb.data, sizeof(TscOpcode)); +X sc_pb.datsize = datasize; +X sc_pb.pc += sizeof(TscOpcode); +X if (opcode != BufSize) { +X free((char *)sc_pb.stack); +X return err_scerr(NoBufSize); +X } +X memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); +X sc_pb.pc += sizeof(TscOperand); +X sc_pb.buffer = (unsigned char *)malloc(operand); +X sc_pb.maxbufsize = (int)operand; +X if (sc_pb.buffer == NULL) { +X free((char *)sc_pb.stack); +X return err_nomem(); +X } +X memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); +X if (opcode != NoArgs) { +X if (xPush(args, &sc_pb) != 0) { +X UnInit(self, &sc_pb); +X return NULL; +X } +X } +X while (sc_pb.pc < datasize) { +X memcpy(&opcode, &sc_pb.data[sc_pb.pc], sizeof(TscOpcode)); +X sc_pb.pc += sizeof(TscOpcode); +X if (opcode & (OPERAND | FLAGS)) { +X memcpy(&operand, &sc_pb.data[sc_pb.pc], sizeof(TscOperand)); +X sc_pb.pc += sizeof(TscOperand); +X } X#ifdef SCDEBUG -X xPrintCode(opcode); -X if ((opcode & FLAGS) && (opcode & OPERAND)) -X xPrintFlags(operand); -X else if (opcode & OPERAND) -X xPrintNum(operand); -X printf("\n"); -X fflush(stdout); +X xPrintCode(opcode); +X if ((opcode & FLAGS) && (opcode & OPERAND)) +X xPrintFlags(operand); +X else if (opcode & OPERAND) +X xPrintNum(operand); +X printf("\n"); +X fflush(stdout); X#endif X#ifdef STACK_TRACE -X { -X register i; -X -X printf("Stack trace :\n"); -X for(i = 0; i < sc_pb.sp; i++) { -X printobject(sc_pb.stack[i], stdout, 0); -X printf("\n"); -X } -X } +X { +X register i; +X +X printf("Stack trace :\n"); +X for(i = 0; i < sc_pb.sp; i++) { +X printobject(sc_pb.stack[i], stdout, 0); +X printf("\n"); +X } +X } X#endif -X switch(opcode) { -X -X case NoArgs: -X ret = 0; -X if (args != NULL) { -X err_scerrset(TypeFailure, args, "NoArgs"); -X ret = -1; -X } -X break; -X -X case BufSize: -X UnInit(self, &sc_pb); -X return err_scerr(TwoBufSize); -X -X case Trans: -X ret = xTrans(self, operand, &sc_pb); -X break; -X -X case TTupleS: -X ret = xTTupleS(operand, &sc_pb); -X break; -X -X case Unpack: -X ret = xUnpack(operand, &sc_pb); -X break; -X -X case AilWord: -X ret = xAilword(operand, &sc_pb); -X break; -X -X case StringS: -X ret = xStringS(&sc_pb); -X break; -X -X case ListS: -X ret = xListS(&sc_pb); -X break; -X -X case PutFS: -X ret = xPutFS(operand, &sc_pb); -X break; -X -X case TStringSeq: -X ret = xTStringSeq(operand, &sc_pb); -X break; -X -X case TStringSlt: -X ret = xTStringSlt(operand, &sc_pb); -X break; -X -X case PutVS: -X ret = xPutVS(&sc_pb); -X break; -X -X case TListSeq: -X ret = xTListSeq(operand, &sc_pb); -X break; -X -X case TListSlt: -X -ret = xTListSlt(operand, &sc_pb); -X break; -X -X case LoopPut: -X ret = xLoopPut(operand, &sc_pb); -X break; -X -X case EndLoop: -X ret = xEndLoop(operand, &sc_pb); -X break; -X -X case PutI: -X ret = xPutI(operand, &sc_pb); -X break; -X -X case PutC: -X ret = xPutC(&sc_pb); -X break; -X -X case Dup: -X ret = xDup(operand, &sc_pb); -X break; -X -X case Pop: -X ret = xPop(operand, &sc_pb); -X break; -X -X case Align: -X ret = xAlign(operand, &sc_pb); -X break; -X -X case Pack: -X ret = xPack(operand, &sc_pb); -X break; -X -X case GetVS: -X ret = xGetVS(&sc_pb); -X break; -X -X case LoopGet: -X ret = xLoopGet(operand, &sc_pb); -X break; -X -X case GetFS: -X ret = xGetFS(operand, &sc_pb); -X break; -X -X case GetI: -X ret = xGetI(operand, &sc_pb); -X break; -X -X case GetC: -X ret = xGetC(operand, &sc_pb); -X break; -X -X case PushI: -X { -X object *element; -X -X element = newintobject((long)operand); -X if (element == NULL) { -X UnInit(self, &sc_pb); -X return NULL; -X } -X ret = xPush(element, &sc_pb); -X if (ret == 0) -X DECREF(element); -X } -X break; -X -X case Equal: -X ret = xEqual(&sc_pb); -X break; -X -X default: -X { -X char errstr[256]; -X -X UnInit(self, &sc_pb); -X sprintf(errstr, "Unknow stubcode %d", opcode); -X err_setstr(RuntimeError, errstr); -X return NULL; -X } -X } -X if (ret != 0) { -X UnInit(self, &sc_pb); -X return NULL; -X } -X } -X if (sc_pb.sp > 0) { -X INCREF(sc_pb.stack[sc_pb.sp - 1]); -X returnobject = sc_pb.stack[sc_pb.sp - 1]; -X } else { -X INCREF(None); -X returnobject = None; -X } -X UnInit(self, &sc_pb); -X return returnobject; +X switch(opcode) { +X +X case NoArgs: +X ret = 0; +X if (args != NULL) { +X err_scerrset(TypeFailure, args, "NoArgs"); +X ret = -1; +X } +X break; +X +X case BufSize: +X UnInit(self, &sc_pb); +X return err_scerr(TwoBufSize); +X +X case Trans: +X ret = xTrans(self, operand, &sc_pb); +X break; +X +X case TTupleS: +X ret = xTTupleS(operand, &sc_pb); +X break; +X +X case Unpack: +X ret = xUnpack(operand, &sc_pb); +X break; +X +X case AilWord: +X ret = xAilword(operand, &sc_pb); +X break; +X +X case StringS: +X ret = xStringS(&sc_pb); +X break; +X +X case ListS: +X ret = xListS(&sc_pb); +X break; +X +X case PutFS: +X ret = xPutFS(operand, &sc_pb); +X break; +X +X case TStringSeq: +X ret = xTStringSeq(operand, &sc_pb); +X break; +X +X case TStringSlt: +X ret = xTStringSlt(operand, &sc_pb); +X break; +X +X case PutVS: +X ret = xPutVS(&sc_pb); +X break; +X +X case TListSeq: +X ret = xTListSeq(operand, &sc_pb); +X break; +X +X case TListSlt: +X + ret = xTListSlt(operand, &sc_pb); +X break; +X +X case LoopPut: +X ret = xLoopPut(operand, &sc_pb); +X break; +X +X case EndLoop: +X ret = xEndLoop(operand, &sc_pb); +X break; +X +X case PutI: +X ret = xPutI(operand, &sc_pb); +X break; +X +X case PutC: +X ret = xPutC(&sc_pb); +X break; +X +X case Dup: +X ret = xDup(operand, &sc_pb); +X break; +X +X case Pop: +X ret = xPop(operand, &sc_pb); +X break; +X +X case Align: +X ret = xAlign(operand, &sc_pb); +X break; +X +X case Pack: +X ret = xPack(operand, &sc_pb); +X break; +X +X case GetVS: +X ret = xGetVS(&sc_pb); +X break; +X +X case LoopGet: +X ret = xLoopGet(operand, &sc_pb); +X break; +X +X case GetFS: +X ret = xGetFS(operand, &sc_pb); +X break; +X +X case GetI: +X ret = xGetI(operand, &sc_pb); +X break; +X +X case GetC: +X ret = xGetC(operand, &sc_pb); +X break; +X +X case PushI: +X { +X object *element; +X +X element = newintobject((long)operand); +X if (element == NULL) { +X UnInit(self, &sc_pb); +X return NULL; +X } +X ret = xPush(element, &sc_pb); +X if (ret == 0) +X DECREF(element); +X } +X break; +X +X case Equal: +X ret = xEqual(&sc_pb); +X break; +X +X default: +X { +X char errstr[256]; +X +X UnInit(self, &sc_pb); +X sprintf(errstr, "Unknow stubcode %d", opcode); +X err_setstr(RuntimeError, errstr); +X return NULL; +X } +X } +X if (ret != 0) { +X UnInit(self, &sc_pb); +X return NULL; +X } +X } +X if (sc_pb.sp > 0) { +X INCREF(sc_pb.stack[sc_pb.sp - 1]); +X returnobject = sc_pb.stack[sc_pb.sp - 1]; +X } else { +X INCREF(None); +X returnobject = None; +X } +X UnInit(self, &sc_pb); +X return returnobject; X} EOF fi echo 'Part 06 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-07-21.shar b/shar/python-0.9.1-07-21.shar index e242423..87928a4 100644 --- a/shar/python-0.9.1-07-21.shar +++ b/shar/python-0.9.1-07-21.shar @@ -39,702 +39,702 @@ Xfrom math import pi Ximport math Ximport posix X -XFULLC = 3600 # Full circle in 1/10-ths of a degree -XMIDN = 900 # Angle of the 12 o'clock position -XR, G, B = 0, 1, 2 # Indices of colors in RGB list +XFULLC = 3600 # Full circle in 1/10-ths of a degree +XMIDN = 900 # Angle of the 12 o'clock position +XR, G, B = 0, 1, 2 # Indices of colors in RGB list X -XHOUR = 3600 # Number of seconds per hour -XMINUTE = 60 # Number of seconds per minute +XHOUR = 3600 # Number of seconds per hour +XMINUTE = 60 # Number of seconds per minute X -Xclass struct(): pass # Class to define featureless structures -XGl = struct() # Object to hold writable global variables +Xclass struct(): pass # Class to define featureless structures +XGl = struct() # Object to hold writable global variables X X# Default constants (used in multiple places) X XSCREENBG = 127, 156, 191 XNPARTS = 9 XTITLE = 'M Clock' -XTZDIFF = -1*HOUR # <--- change this to reflect your local time zone +XTZDIFF = -1*HOUR # <--- change this to reflect your local time zone X X# Default parameters X -XGl.foreground = 0 # If set, run in the foreground -XGl.fullscreen = 0 # If set, run on full screen -XGl.tzdiff = TZDIFF # Seconds west of Greenwich (winter time) -XGl.nparts = NPARTS # Number of parts each circle is divided in (>= 2) -XGl.debug = 0 # If set, print debug output -XGl.doublebuffer = 1 # If set, use double buffering -XGl.update = 0 # Update interval; seconds hand is suppressed if > 1 -XGl.colorsubset = 0 # If set, display only a subset of the colors -XGl.cyan = 0 # If set, display cyan overlay (big hand) -XGl.magenta = 0 # If set, display magenta overlay (little hand) -XGl.yellow = 0 # If set, display yellow overlay (fixed background) -XGl.black = 0 # If set, display black overlay (hands) -XGl.colormap = 0 # If set, use colormap mode instead of RGB mode -XGl.warnings = 0 # If set, print warnings -XGl.title = '- - ' # Window title (default set later) -XGl.border = 1 # If set, use a window border (and title) -XGl.bg = 0, 0, 0 # Background color R, G, B value -XGl.iconic = 0 # Set in iconic state -XGl.fg = 255, 0, 0 # Alarm background RGB (either normal or alarm) -XGl.ox,Gl.oy = 0,0 # Window origin -XGl.cx,Gl.cy = 0,0 # Window size -XGl.alarm_set = 0 # Alarm on or off -XGl.alarm_on = 0 # Alarm is ringing -XGl.alarm_time = 0 # Alarm time in seconds after midnight -XGl.alarm_hours = 0 # Alarm hour setting, 24 hour clock -XGl.alarm_minutes = 0 # Alarm minutes setting -XGl.alarm_rgb = 0,0,0 # Alarm display RGB colors -XGl.alarm_cmd = '' # Command to execute when alarm goes off -XGl.mouse2down = 0 # Mouse button state -XGl.mouse3down = 0 # Mouse button state -XGl.gong_cmd = '' # Command to execute when chimes go off -XGl.gong_int = 3600 # Gong interval -XGl.indices = R, G, B # Colors (permuted when alarm is on) +XGl.foreground = 0 # If set, run in the foreground +XGl.fullscreen = 0 # If set, run on full screen +XGl.tzdiff = TZDIFF # Seconds west of Greenwich (winter time) +XGl.nparts = NPARTS # Number of parts each circle is divided in (>= 2) +XGl.debug = 0 # If set, print debug output +XGl.doublebuffer = 1 # If set, use double buffering +XGl.update = 0 # Update interval; seconds hand is suppressed if > 1 +XGl.colorsubset = 0 # If set, display only a subset of the colors +XGl.cyan = 0 # If set, display cyan overlay (big hand) +XGl.magenta = 0 # If set, display magenta overlay (little hand) +XGl.yellow = 0 # If set, display yellow overlay (fixed background) +XGl.black = 0 # If set, display black overlay (hands) +XGl.colormap = 0 # If set, use colormap mode instead of RGB mode +XGl.warnings = 0 # If set, print warnings +XGl.title = '- - ' # Window title (default set later) +XGl.border = 1 # If set, use a window border (and title) +XGl.bg = 0, 0, 0 # Background color R, G, B value +XGl.iconic = 0 # Set in iconic state +XGl.fg = 255, 0, 0 # Alarm background RGB (either normal or alarm) +XGl.ox,Gl.oy = 0,0 # Window origin +XGl.cx,Gl.cy = 0,0 # Window size +XGl.alarm_set = 0 # Alarm on or off +XGl.alarm_on = 0 # Alarm is ringing +XGl.alarm_time = 0 # Alarm time in seconds after midnight +XGl.alarm_hours = 0 # Alarm hour setting, 24 hour clock +XGl.alarm_minutes = 0 # Alarm minutes setting +XGl.alarm_rgb = 0,0,0 # Alarm display RGB colors +XGl.alarm_cmd = '' # Command to execute when alarm goes off +XGl.mouse2down = 0 # Mouse button state +XGl.mouse3down = 0 # Mouse button state +XGl.gong_cmd = '' # Command to execute when chimes go off +XGl.gong_int = 3600 # Gong interval +XGl.indices = R, G, B # Colors (permuted when alarm is on) X Xdef main(): -X # -X sys.stdout = sys.stderr # All output is errors/warnings etc. -X # -X try: -X args = getoptions() -X except string.atoi_error, value: -X usage(string.atoi_error, value) -X except getopt.error, msg: -X usage(getopt.error, msg) -X # -X if args: -X realtime = 0 -X hours = string.atoi(args[0]) -X minutes = seconds = 0 -X if args[1:]: minutes = string.atoi(args[1]) -X if args[2:]: seconds = string.atoi(args[2]) -X localtime = ((hours*60)+minutes)*60+seconds -X else: -X realtime = 1 -X # -X if Gl.title = '- - ': -X if realtime: -X Gl.title = TITLE -X else: -X title = '' -X for arg in args: title = title + ' ' + arg -X Gl.title = title[1:] -X del title -X # -X wid = makewindow() -X Gl.ox,Gl.oy = getorigin() -X Gl.cx,Gl.cy = getsize() -X initmenu() -X clearall() -X # -X if not Gl.update: -X Gl.update = 60 -X # -X if Gl.update <= 1: -X Gl.timernoise = 6 -X else: -X Gl.timernoise = 60 -X noise(TIMER0, Gl.timernoise) -X # -X qdevice(WINSHUT) -X qdevice(WINQUIT) -X qdevice(ESCKEY) -X if realtime: -X qdevice(TIMER0) -X qdevice(REDRAW) -X qdevice(WINFREEZE) -X qdevice(WINTHAW) -X qdevice(MENUBUTTON) # MOUSE1 -X qdevice(MOUSE3) # Left button -X qdevice(MOUSE2) # Middle button -X unqdevice(INPUTCHANGE) -X # -X lasttime = 0 -X Gl.change = 1 -X while 1: -X if realtime: -X localtime = time.time() - Gl.tzdiff -X if Gl.alarm_set: -X if localtime%(24*HOUR) = Gl.alarm_time: -X # Ring the alarm! -X if Gl.debug: -X print 'Rrrringg!' -X Gl.alarm_on = 1 -X if Gl.alarm_cmd <> '': -X d = posix.system(Gl.alarm_cmd+' '+`Gl.alarm_time/3600`+' '+`(Gl.alarm_time/60)%60` + ' &') -X Gl.change = 1 -X clearall() -X if Gl.alarm_on: -X if (localtime - Gl.alarm_time) % (24*HOUR) > 300: -X # More than 5 minutes away from alarm -X Gl.alarm_on = 0 -X if Gl.debug: -X print 'Alarm turned off' -X Gl.change = 1 -X clearall() -X Gl.indices = R, G, B -X else: -X if localtime % 2 = 0: -X # Permute color indices -X Gl.indices = Gl.indices[2:] + Gl.indices[:2] -X Gl.change = 1 -X if Gl.gong_cmd <> '' and localtime%Gl.gong_int = 0: -X d = posix.system(Gl.gong_cmd+' '+`(localtime/3600)%24`+' '+`(localtime/60)%60` + ' &') -X if localtime/Gl.update <> lasttime/Gl.update: -X if Gl.debug: print 'new time' -X Gl.change = 1 -X if Gl.change: -X if Gl.debug: print 'drawing' -X doit(localtime) -X lasttime = localtime -X Gl.change = 0 -X dev, data = qread() -X if Gl.debug and dev <> TIMER0: -X print dev, data -X if dev = TIMER0: -X if Gl.debug > 1: -X print dev, data -X elif dev = MOUSE3: -X mousex = getvaluator(MOUSEX) -X mousey = getvaluator(MOUSEY) -X if mouseclick(3, data, mousex, mousey): -X Gl.change = 1 -X elif dev = MOUSE2: -X mousex = getvaluator(MOUSEX) -X mousey = getvaluator(MOUSEY) -X if mouseclick(2, data, mousex, mousey): -X Gl.change = 1 -X elif dev = MOUSEX: -X mousex = data -X if Gl.mouse2down: -X mouse2track(mousex, mousey) -X if Gl.mouse3down: -X mouse3track(mousex, mousey) -X elif dev = MOUSEY: -X mousey = data -X if Gl.mouse2down: -X mouse2track(mousex, mousey) -X if Gl.mouse3down: -X mouse3track(mousex, mousey) -X elif dev = REDRAW or dev = REDRAWICONIC: -X if Gl.debug: -X if dev = REDRAW: print 'REDRAW' -X else: print 'REDRAWICONIC' -X reshapeviewport() -X Gl.ox,Gl.oy = getorigin() -X Gl.cx,Gl.cy = getsize() -X Gl.change = 1 -X clearall() -X elif dev = MENUBUTTON: -X if Gl.debug: print 'MENUBUTTON' -X handlemenu() -X elif dev = WINFREEZE: -X if Gl.debug: print 'WINFREEZE' -X Gl.iconic = 1 -X noise(TIMER0, 60*60) # Redraw every 60 seconds only -X elif dev = WINTHAW: -X if Gl.debug: print 'WINTHAW' -X Gl.iconic = 0 -X noise(TIMER0, Gl.timernoise) -X Gl.change = 1 -X elif dev = ESCKEY or dev = WINSHUT or dev = WINQUIT: -X if Gl.debug: print 'Exit' -X sys.exit(0) +X # +X sys.stdout = sys.stderr # All output is errors/warnings etc. +X # +X try: +X args = getoptions() +X except string.atoi_error, value: +X usage(string.atoi_error, value) +X except getopt.error, msg: +X usage(getopt.error, msg) +X # +X if args: +X realtime = 0 +X hours = string.atoi(args[0]) +X minutes = seconds = 0 +X if args[1:]: minutes = string.atoi(args[1]) +X if args[2:]: seconds = string.atoi(args[2]) +X localtime = ((hours*60)+minutes)*60+seconds +X else: +X realtime = 1 +X # +X if Gl.title = '- - ': +X if realtime: +X Gl.title = TITLE +X else: +X title = '' +X for arg in args: title = title + ' ' + arg +X Gl.title = title[1:] +X del title +X # +X wid = makewindow() +X Gl.ox,Gl.oy = getorigin() +X Gl.cx,Gl.cy = getsize() +X initmenu() +X clearall() +X # +X if not Gl.update: +X Gl.update = 60 +X # +X if Gl.update <= 1: +X Gl.timernoise = 6 +X else: +X Gl.timernoise = 60 +X noise(TIMER0, Gl.timernoise) +X # +X qdevice(WINSHUT) +X qdevice(WINQUIT) +X qdevice(ESCKEY) +X if realtime: +X qdevice(TIMER0) +X qdevice(REDRAW) +X qdevice(WINFREEZE) +X qdevice(WINTHAW) +X qdevice(MENUBUTTON) # MOUSE1 +X qdevice(MOUSE3) # Left button +X qdevice(MOUSE2) # Middle button +X unqdevice(INPUTCHANGE) +X # +X lasttime = 0 +X Gl.change = 1 +X while 1: +X if realtime: +X localtime = time.time() - Gl.tzdiff +X if Gl.alarm_set: +X if localtime%(24*HOUR) = Gl.alarm_time: +X # Ring the alarm! +X if Gl.debug: +X print 'Rrrringg!' +X Gl.alarm_on = 1 +X if Gl.alarm_cmd <> '': +X d = posix.system(Gl.alarm_cmd+' '+`Gl.alarm_time/3600`+' '+`(Gl.alarm_time/60)%60` + ' &') +X Gl.change = 1 +X clearall() +X if Gl.alarm_on: +X if (localtime - Gl.alarm_time) % (24*HOUR) > 300: +X # More than 5 minutes away from alarm +X Gl.alarm_on = 0 +X if Gl.debug: +X print 'Alarm turned off' +X Gl.change = 1 +X clearall() +X Gl.indices = R, G, B +X else: +X if localtime % 2 = 0: +X # Permute color indices +X Gl.indices = Gl.indices[2:] + Gl.indices[:2] +X Gl.change = 1 +X if Gl.gong_cmd <> '' and localtime%Gl.gong_int = 0: +X d = posix.system(Gl.gong_cmd+' '+`(localtime/3600)%24`+' '+`(localtime/60)%60` + ' &') +X if localtime/Gl.update <> lasttime/Gl.update: +X if Gl.debug: print 'new time' +X Gl.change = 1 +X if Gl.change: +X if Gl.debug: print 'drawing' +X doit(localtime) +X lasttime = localtime +X Gl.change = 0 +X dev, data = qread() +X if Gl.debug and dev <> TIMER0: +X print dev, data +X if dev = TIMER0: +X if Gl.debug > 1: +X print dev, data +X elif dev = MOUSE3: +X mousex = getvaluator(MOUSEX) +X mousey = getvaluator(MOUSEY) +X if mouseclick(3, data, mousex, mousey): +X Gl.change = 1 +X elif dev = MOUSE2: +X mousex = getvaluator(MOUSEX) +X mousey = getvaluator(MOUSEY) +X if mouseclick(2, data, mousex, mousey): +X Gl.change = 1 +X elif dev = MOUSEX: +X mousex = data +X if Gl.mouse2down: +X mouse2track(mousex, mousey) +X if Gl.mouse3down: +X mouse3track(mousex, mousey) +X elif dev = MOUSEY: +X mousey = data +X if Gl.mouse2down: +X mouse2track(mousex, mousey) +X if Gl.mouse3down: +X mouse3track(mousex, mousey) +X elif dev = REDRAW or dev = REDRAWICONIC: +X if Gl.debug: +X if dev = REDRAW: print 'REDRAW' +X else: print 'REDRAWICONIC' +X reshapeviewport() +X Gl.ox,Gl.oy = getorigin() +X Gl.cx,Gl.cy = getsize() +X Gl.change = 1 +X clearall() +X elif dev = MENUBUTTON: +X if Gl.debug: print 'MENUBUTTON' +X handlemenu() +X elif dev = WINFREEZE: +X if Gl.debug: print 'WINFREEZE' +X Gl.iconic = 1 +X noise(TIMER0, 60*60) # Redraw every 60 seconds only +X elif dev = WINTHAW: +X if Gl.debug: print 'WINTHAW' +X Gl.iconic = 0 +X noise(TIMER0, Gl.timernoise) +X Gl.change = 1 +X elif dev = ESCKEY or dev = WINSHUT or dev = WINQUIT: +X if Gl.debug: print 'Exit' +X sys.exit(0) X Xdef getoptions(): -X optlist, args = getopt.getopt(sys.argv[1:], 'A:a:B:bc:dFfG:g:n:sT:t:u:wCMYK') -X for optname, optarg in optlist: -X if optname = '-A': -X Gl.fg = eval(optarg) # Should be (r,g,b) -X elif optname = '-a': -X Gl.alarm_cmd = optarg -X elif optname = '-B': -X Gl.bg = eval(optarg) # Should be (r,g,b) -X elif optname = '-b': -X Gl.border = 0 -X elif optname = '-c': -X Gl.colormap = string.atoi(optarg) -X elif optname = '-d': -X Gl.debug = Gl.debug + 1 -X Gl.warnings = 1 -X elif optname = '-F': -X Gl.foreground = 1 -X elif optname = '-f': -X Gl.fullscreen = 1 -X elif optname = '-G': -X Gl.gong_int = 60*string.atoi(optarg) -X elif optname = '-g': -X Gl.gong_cmd = optarg -X elif optname = '-n': -X Gl.nparts = string.atoi(optarg) -X elif optname = '-s': -X Gl.doublebuffer = 0 -X elif optname = '-T': -X Gl.title = optarg -X elif optname = '-t': -X Gl.tzdiff = string.atoi(optarg) -X elif optname = '-u': -X Gl.update = string.atoi(optarg) -X elif optname = '-w': -X Gl.warnings = 1 -X elif optname = '-C': -X Gl.cyan = Gl.colorsubset = 1 -X elif optname = '-M': -X Gl.magenta = Gl.colorsubset = 1 -X elif optname = '-Y': -X Gl.yellow = Gl.colorsubset = 1 -X elif optname = '-K': -X Gl.black = Gl.colorsubset = 1 -X else: -X print 'Unsupported option', optname -X return args +X optlist, args = getopt.getopt(sys.argv[1:], 'A:a:B:bc:dFfG:g:n:sT:t:u:wCMYK') +X for optname, optarg in optlist: +X if optname = '-A': +X Gl.fg = eval(optarg) # Should be (r,g,b) +X elif optname = '-a': +X Gl.alarm_cmd = optarg +X elif optname = '-B': +X Gl.bg = eval(optarg) # Should be (r,g,b) +X elif optname = '-b': +X Gl.border = 0 +X elif optname = '-c': +X Gl.colormap = string.atoi(optarg) +X elif optname = '-d': +X Gl.debug = Gl.debug + 1 +X Gl.warnings = 1 +X elif optname = '-F': +X Gl.foreground = 1 +X elif optname = '-f': +X Gl.fullscreen = 1 +X elif optname = '-G': +X Gl.gong_int = 60*string.atoi(optarg) +X elif optname = '-g': +X Gl.gong_cmd = optarg +X elif optname = '-n': +X Gl.nparts = string.atoi(optarg) +X elif optname = '-s': +X Gl.doublebuffer = 0 +X elif optname = '-T': +X Gl.title = optarg +X elif optname = '-t': +X Gl.tzdiff = string.atoi(optarg) +X elif optname = '-u': +X Gl.update = string.atoi(optarg) +X elif optname = '-w': +X Gl.warnings = 1 +X elif optname = '-C': +X Gl.cyan = Gl.colorsubset = 1 +X elif optname = '-M': +X Gl.magenta = Gl.colorsubset = 1 +X elif optname = '-Y': +X Gl.yellow = Gl.colorsubset = 1 +X elif optname = '-K': +X Gl.black = Gl.colorsubset = 1 +X else: +X print 'Unsupported option', optname +X return args X Xdef usage(exc, msg): -X if sys.argv: -X progname = path.basename(sys.argv[0]) -X else: -X progname = 'mclock' -X # -X print progname + ':', -X if exc = string.atoi_error: -X print 'non-numeric argument:', -X print msg -X # -X print 'usage:', progname, '[options] [hh [mm [ss]]]' -X # -X print '-A r,g,b : alarm background red,green,blue [255,0,0]' -X print '-a cmd : shell command executed when alarm goes off' -X print '-B r,g,b : background red,green,blue [0,0,0]' -X print ' (-B SCREENBG uses the default screen background)' -X print '-b : suppress window border and title' -X print '-c cmapid : select explicit colormap' -X print '-d : more debug output (implies -F, -w)' -X print '-F : run in foreground' -X print '-f : use full screen' -X print '-G intrvl : interval between chimes in minutes [60]' -X print '-g cmd : shell command executed when chimes go off' -X print '-s : single buffer mode' -X print '-w : print various warnings' -X print '-n nparts : number of parts [' + `NPARTS` + ']' -X print '-T title : alternate window title [\'' + TITLE + '\']' -X print '-t tzdiff : time zone difference [' + `TZDIFF` + ']' -X print '-u update : update interval [60]' -X print '-CMYK : Cyan, Magenta, Yellow or blacK overlay only' -X print 'if hh [mm [ss]] is specified, display that time statically' -X print 'on machines with < 12 bitplanes, -c and -s are forced on' -X # -X sys.exit(2) +X if sys.argv: +X progname = path.basename(sys.argv[0]) +X else: +X progname = 'mclock' +X # +X print progname + ':', +X if exc = string.atoi_error: +X print 'non-numeric argument:', +X print msg +X # +X print 'usage:', progname, '[options] [hh [mm [ss]]]' +X # +X print '-A r,g,b : alarm background red,green,blue [255,0,0]' +X print '-a cmd : shell command executed when alarm goes off' +X print '-B r,g,b : background red,green,blue [0,0,0]' +X print ' (-B SCREENBG uses the default screen background)' +X print '-b : suppress window border and title' +X print '-c cmapid : select explicit colormap' +X print '-d : more debug output (implies -F, -w)' +X print '-F : run in foreground' +X print '-f : use full screen' +X print '-G intrvl : interval between chimes in minutes [60]' +X print '-g cmd : shell command executed when chimes go off' +X print '-s : single buffer mode' +X print '-w : print various warnings' +X print '-n nparts : number of parts [' + `NPARTS` + ']' +X print '-T title : alternate window title [\'' + TITLE + '\']' +X print '-t tzdiff : time zone difference [' + `TZDIFF` + ']' +X print '-u update : update interval [60]' +X print '-CMYK : Cyan, Magenta, Yellow or blacK overlay only' +X print 'if hh [mm [ss]] is specified, display that time statically' +X print 'on machines with < 12 bitplanes, -c and -s are forced on' +X # +X sys.exit(2) X Xdef doit(localtime): -X hands = makehands(localtime) -X list = makelist(hands) -X render(list, hands) +X hands = makehands(localtime) +X list = makelist(hands) +X render(list, hands) X Xdef makehands(localtime): -X localtime = localtime % (12*HOUR) -X seconds_hand = MIDN + FULLC - (localtime*60) % FULLC -X big_hand = (MIDN + FULLC - (localtime%HOUR)) % FULLC -X little_hand = (MIDN + FULLC - ((localtime/12) % HOUR)) % FULLC -X return little_hand, big_hand, seconds_hand +X localtime = localtime % (12*HOUR) +X seconds_hand = MIDN + FULLC - (localtime*60) % FULLC +X big_hand = (MIDN + FULLC - (localtime%HOUR)) % FULLC +X little_hand = (MIDN + FULLC - ((localtime/12) % HOUR)) % FULLC +X return little_hand, big_hand, seconds_hand X Xdef makelist(little_hand, big_hand, seconds_hand): -X total = [] -X if Gl.cyan or not Gl.colorsubset: -X total = total + makesublist(big_hand, Gl.indices[0]) -X if Gl.magenta or not Gl.colorsubset: -X total = total + makesublist(little_hand, Gl.indices[1]) -X if Gl.yellow or not Gl.colorsubset: -X total = total + makesublist(MIDN, Gl.indices[2]) -X total.sort() -X return total +X total = [] +X if Gl.cyan or not Gl.colorsubset: +X total = total + makesublist(big_hand, Gl.indices[0]) +X if Gl.magenta or not Gl.colorsubset: +X total = total + makesublist(little_hand, Gl.indices[1]) +X if Gl.yellow or not Gl.colorsubset: +X total = total + makesublist(MIDN, Gl.indices[2]) +X total.sort() +X return total X Xdef makesublist(first, icolor): -X list = [] -X alpha = FULLC/Gl.nparts -X a = first - alpha/2 -X for i in range(Gl.nparts): -X angle = (a + i*alpha + FULLC) % FULLC -X value = 255*(Gl.nparts-1-i)/(Gl.nparts-1) -X list.append(angle, icolor, value) -X list.sort() -X a, icolor, value = list[0] -X if a <> 0: -X a, icolor, value = list[len(list)-1] -X t = 0, icolor, value -X list.insert(0, t) -X return list +X list = [] +X alpha = FULLC/Gl.nparts +X a = first - alpha/2 +X for i in range(Gl.nparts): +X angle = (a + i*alpha + FULLC) % FULLC +X value = 255*(Gl.nparts-1-i)/(Gl.nparts-1) +X list.append(angle, icolor, value) +X list.sort() +X a, icolor, value = list[0] +X if a <> 0: +X a, icolor, value = list[len(list)-1] +X t = 0, icolor, value +X list.insert(0, t) +X return list X Xdef rgb_fg(): -X return Gl.fg -X # Obsolete code: -X if Gl.alarm_on: -X return Gl.bg -X else: -X return Gl.fg +X return Gl.fg +X # Obsolete code: +X if Gl.alarm_on: +X return Gl.bg +X else: +X return Gl.fg X Xdef rgb_bg(): -X return Gl.bg -X # Obsolete code: -X if Gl.alarm_on: -X return Gl.fg -X else: -X return Gl.bg +X return Gl.bg +X # Obsolete code: +X if Gl.alarm_on: +X return Gl.fg +X else: +X return Gl.bg X Xdef clearall(): -X Gl.c3i(rgb_bg()) -X clear() -X if Gl.doublebuffer: -X swapbuffers() -X clear() +X Gl.c3i(rgb_bg()) +X clear() +X if Gl.doublebuffer: +X swapbuffers() +X clear() X Xdef draw_alarm(color): -X frontbuffer(TRUE) -X Gl.c3i(color) -X pushmatrix() -X rotate(-((Gl.alarm_time/12)%3600), 'z') -X bgnpolygon() -X v2f( 0.00,1.00) -X v2f( 0.04,1.05) -X v2f(-0.04,1.05) -X endpolygon() -X popmatrix() -X # -X pushmatrix() -X rotate(-((Gl.alarm_time)%3600), 'z') -X bgnpolygon() -X v2f( 0.00,1.05) -X v2f( 0.07,1.10) -X v2f(-0.07,1.10) -X endpolygon() -X popmatrix() -X # -X cmov2(-1.06, -1.06) -X charstr(string.rjust(`Gl.alarm_time/3600`,2)) -X charstr(':') -X charstr(string.zfill((Gl.alarm_time/60)%60,2)) -X frontbuffer(FALSE) +X frontbuffer(TRUE) +X Gl.c3i(color) +X pushmatrix() +X rotate(-((Gl.alarm_time/12)%3600), 'z') +X bgnpolygon() +X v2f( 0.00,1.00) +X v2f( 0.04,1.05) +X v2f(-0.04,1.05) +X endpolygon() +X popmatrix() +X # +X pushmatrix() +X rotate(-((Gl.alarm_time)%3600), 'z') +X bgnpolygon() +X v2f( 0.00,1.05) +X v2f( 0.07,1.10) +X v2f(-0.07,1.10) +X endpolygon() +X popmatrix() +X # +X cmov2(-1.06, -1.06) +X charstr(string.rjust(`Gl.alarm_time/3600`,2)) +X charstr(':') +X charstr(string.zfill((Gl.alarm_time/60)%60,2)) +X frontbuffer(FALSE) X Xdef render(list, (little_hand, big_hand, seconds_hand)): -X # -X if Gl.colormap: -X resetindex() -X # -X if not list: -X Gl.c3i(255, 255, 255) # White -X circf(0.0, 0.0, 1.0) -X else: -X list.append(3600, 0, 255) # Sentinel -X # -X rgb = [255, 255, 255] -X a_prev = 0 -X for a, icolor, value in list: -X if a <> a_prev: -X [r, g, b] = rgb -X if Gl.debug > 1: -X print rgb, a_prev, a -X Gl.c3i(r, g, b) -X arcf(0.0, 0.0, 1.0, a_prev, a) -X rgb[icolor] = value -X a_prev = a -X # -X if Gl.black or not Gl.colorsubset: -X # -X # Draw the hands -- in black -X # -X Gl.c3i(0, 0, 0) -X # -X if Gl.update = 1 and not Gl.iconic: -X # Seconds hand is only drawn if we update every second -X pushmatrix() -X rotate(seconds_hand, 'z') -X bgnline() -X v2f(0.0, 0.0) -X v2f(1.0, 0.0) -X endline() -X popmatrix() -X # -X pushmatrix() -X rotate(big_hand, 'z') -X rectf(0.0, -0.01, 0.97, 0.01) -X circf(0.0, 0.0, 0.01) -X circf(0.97, 0.0, 0.01) -X popmatrix() -X # -X pushmatrix() -X rotate(little_hand, 'z') -X rectf(0.04, -0.02, 0.63, 0.02) -X circf(0.04, 0.0, 0.02) -X circf(0.63, 0.0, 0.02) -X popmatrix() -X # -X # Draw the alarm time, if set or being set -X # -X if Gl.alarm_set: -X draw_alarm(rgb_fg()) -X # -X if Gl.doublebuffer: swapbuffers() +X # +X if Gl.colormap: +X resetindex() +X # +X if not list: +X Gl.c3i(255, 255, 255) # White +X circf(0.0, 0.0, 1.0) +X else: +X list.append(3600, 0, 255) # Sentinel +X # +X rgb = [255, 255, 255] +X a_prev = 0 +X for a, icolor, value in list: +X if a <> a_prev: +X [r, g, b] = rgb +X if Gl.debug > 1: +X print rgb, a_prev, a +X Gl.c3i(r, g, b) +X arcf(0.0, 0.0, 1.0, a_prev, a) +X rgb[icolor] = value +X a_prev = a +X # +X if Gl.black or not Gl.colorsubset: +X # +X # Draw the hands -- in black +X # +X Gl.c3i(0, 0, 0) +X # +X if Gl.update = 1 and not Gl.iconic: +X # Seconds hand is only drawn if we update every second +X pushmatrix() +X rotate(seconds_hand, 'z') +X bgnline() +X v2f(0.0, 0.0) +X v2f(1.0, 0.0) +X endline() +X popmatrix() +X # +X pushmatrix() +X rotate(big_hand, 'z') +X rectf(0.0, -0.01, 0.97, 0.01) +X circf(0.0, 0.0, 0.01) +X circf(0.97, 0.0, 0.01) +X popmatrix() +X # +X pushmatrix() +X rotate(little_hand, 'z') +X rectf(0.04, -0.02, 0.63, 0.02) +X circf(0.04, 0.0, 0.02) +X circf(0.63, 0.0, 0.02) +X popmatrix() +X # +X # Draw the alarm time, if set or being set +X # +X if Gl.alarm_set: +X draw_alarm(rgb_fg()) +X # +X if Gl.doublebuffer: swapbuffers() X Xdef makewindow(): -X # -X if Gl.debug or Gl.foreground: -X foreground() -X # -X if Gl.fullscreen: -X # XXX Should find out true screen size using getgdesc() -X prefposition(0, 1279, 0, 1023) -X else: -X keepaspect(1, 1) -X minsize(64, 64) -X # -X if not Gl.border: -X noborder() -X wid = winopen(Gl.title) -X # -X if not Gl.fullscreen: -X keepaspect(1, 1) -X minsize(10, 10) -X maxsize(2000, 2000) -X iconsize(66, 66) -X winconstraints() -X # -X nplanes = getplanes() -X nmaps = getgdesc(GD_NMMAPS) -X if Gl.warnings: -X print nplanes, 'color planes,', nmaps, 'color maps' -X # -X if nplanes < 12 or Gl.colormap: -X if not Gl.colormap: -X Gl.colormap = nmaps - 1 -X if Gl.warnings: -X print 'not enough color planes available', -X print 'for RGB mode; forcing colormap mode' -X print 'using color map number', Gl.colormap -X if not Gl.colorsubset: -X needed = 3 -X else: -X needed = Gl.cyan + Gl.magenta + Gl.yellow -X needed = needed*Gl.nparts -X if Gl.bg <> (0, 0, 0): -X needed = needed+1 -X if Gl.fg <> (0, 0, 0): -X needed = needed+1 -X if Gl.doublebuffer: -X if needed > available(nplanes/2): -X Gl.doublebuffer = 0 -X if Gl.warnings: -X print 'not enough colors available', -X print 'for double buffer mode;', -X print 'forcing single buffer mode' -X else: -X nplanes = nplanes/2 -X if needed > available(nplanes): -X # Do this warning always -X print 'still not enough colors available;', -X print 'parts will be left white' -X print '(needed', needed, 'but have only', -X print available(nplanes), 'colors available)' -X # -X if Gl.doublebuffer: -X doublebuffer() -X gconfig() -X # -X if Gl.colormap: -X Gl.c3i = pseudo_c3i -X fixcolormap() -X else: -X Gl.c3i = c3i -X RGBmode() -X gconfig() -X # -X if Gl.fullscreen: -X # XXX Should find out true screen size using getgdesc() -X ortho2(-1.1*1.280, 1.1*1.280, -1.1*1.024, 1.1*1.024) -X else: -X ortho2(-1.1, 1.1, -1.1, 1.1) -X # -X return wid +X # +X if Gl.debug or Gl.foreground: +X foreground() +X # +X if Gl.fullscreen: +X # XXX Should find out true screen size using getgdesc() +X prefposition(0, 1279, 0, 1023) +X else: +X keepaspect(1, 1) +X minsize(64, 64) +X # +X if not Gl.border: +X noborder() +X wid = winopen(Gl.title) +X # +X if not Gl.fullscreen: +X keepaspect(1, 1) +X minsize(10, 10) +X maxsize(2000, 2000) +X iconsize(66, 66) +X winconstraints() +X # +X nplanes = getplanes() +X nmaps = getgdesc(GD_NMMAPS) +X if Gl.warnings: +X print nplanes, 'color planes,', nmaps, 'color maps' +X # +X if nplanes < 12 or Gl.colormap: +X if not Gl.colormap: +X Gl.colormap = nmaps - 1 +X if Gl.warnings: +X print 'not enough color planes available', +X print 'for RGB mode; forcing colormap mode' +X print 'using color map number', Gl.colormap +X if not Gl.colorsubset: +X needed = 3 +X else: +X needed = Gl.cyan + Gl.magenta + Gl.yellow +X needed = needed*Gl.nparts +X if Gl.bg <> (0, 0, 0): +X needed = needed+1 +X if Gl.fg <> (0, 0, 0): +X needed = needed+1 +X if Gl.doublebuffer: +X if needed > available(nplanes/2): +X Gl.doublebuffer = 0 +X if Gl.warnings: +X print 'not enough colors available', +X print 'for double buffer mode;', +X print 'forcing single buffer mode' +X else: +X nplanes = nplanes/2 +X if needed > available(nplanes): +X # Do this warning always +X print 'still not enough colors available;', +X print 'parts will be left white' +X print '(needed', needed, 'but have only', +X print available(nplanes), 'colors available)' +X # +X if Gl.doublebuffer: +X doublebuffer() +X gconfig() +X # +X if Gl.colormap: +X Gl.c3i = pseudo_c3i +X fixcolormap() +X else: +X Gl.c3i = c3i +X RGBmode() +X gconfig() +X # +X if Gl.fullscreen: +X # XXX Should find out true screen size using getgdesc() +X ortho2(-1.1*1.280, 1.1*1.280, -1.1*1.024, 1.1*1.024) +X else: +X ortho2(-1.1, 1.1, -1.1, 1.1) +X # +X return wid X Xdef available(nplanes): -X return pow(2, nplanes) - 1 # Reserve one pixel for black +X return pow(2, nplanes) - 1 # Reserve one pixel for black X Xdef fixcolormap(): -X multimap() -X gconfig() -X nplanes = getplanes() -X if Gl.warnings: -X print 'multimap mode has', nplanes, 'color planes' -X imap = Gl.colormap -X Gl.startindex = pow(2, nplanes) - 1 -X Gl.stopindex = 1 -X setmap(imap) -X mapcolor(0, 0, 0, 0) # Fixed entry for black -X if Gl.bg <> (0, 0, 0): -X r, g, b = Gl.bg -X mapcolor(1, r, g, b) # Fixed entry for Gl.bg -X Gl.stopindex = 2 -X if Gl.fg <> (0, 0, 0): -X r, g, b = Gl.fg -X mapcolor(2, r, g, b) # Fixed entry for Gl.fg -X Gl.stopindex = 3 -X Gl.overflow_seen = 0 -X resetindex() +X multimap() +X gconfig() +X nplanes = getplanes() +X if Gl.warnings: +X print 'multimap mode has', nplanes, 'color planes' +X imap = Gl.colormap +X Gl.startindex = pow(2, nplanes) - 1 +X Gl.stopindex = 1 +X setmap(imap) +X mapcolor(0, 0, 0, 0) # Fixed entry for black +X if Gl.bg <> (0, 0, 0): +X r, g, b = Gl.bg +X mapcolor(1, r, g, b) # Fixed entry for Gl.bg +X Gl.stopindex = 2 +X if Gl.fg <> (0, 0, 0): +X r, g, b = Gl.fg +X mapcolor(2, r, g, b) # Fixed entry for Gl.fg +X Gl.stopindex = 3 +X Gl.overflow_seen = 0 +X resetindex() X Xdef resetindex(): -X Gl.index = Gl.startindex +X Gl.index = Gl.startindex X Xr0g0b0 = (0, 0, 0) X Xdef pseudo_c3i(rgb): -X if rgb = r0g0b0: -X index = 0 -X elif rgb = Gl.bg: -X index = 1 -X elif rgb = Gl.fg: -X index = 2 -X else: -X index = definecolor(rgb) -X color(index) +X if rgb = r0g0b0: +X index = 0 +X elif rgb = Gl.bg: +X index = 1 +X elif rgb = Gl.fg: +X index = 2 +X else: +X index = definecolor(rgb) +X color(index) X Xdef definecolor(rgb): -X index = Gl.index -X if index < Gl.stopindex: -X if Gl.debug: print 'definecolor hard case', rgb -X # First see if we already have this one... -X for index in range(Gl.stopindex, Gl.startindex+1): -X if rgb = getmcolor(index): -X if Gl.debug: print 'return', index -X return index -X # Don't clobber reserverd colormap entries -X if not Gl.overflow_seen: -X # Shouldn't happen any more, hence no Gl.warnings test -X print 'mclock: out of colormap entries' -X Gl.overflow_seen = 1 -X return Gl.stopindex -X r, g, b = rgb -X if Gl.debug > 1: print 'mapcolor', (index, r, g, b) -X mapcolor(index, r, g, b) -X Gl.index = index - 1 -X return index +X index = Gl.index +X if index < Gl.stopindex: +X if Gl.debug: print 'definecolor hard case', rgb +X # First see if we already have this one... +X for index in range(Gl.stopindex, Gl.startindex+1): +X if rgb = getmcolor(index): +X if Gl.debug: print 'return', index +X return index +X # Don't clobber reserverd colormap entries +X if not Gl.overflow_seen: +X # Shouldn't happen any more, hence no Gl.warnings test +X print 'mclock: out of colormap entries' +X Gl.overflow_seen = 1 +X return Gl.stopindex +X r, g, b = rgb +X if Gl.debug > 1: print 'mapcolor', (index, r, g, b) +X mapcolor(index, r, g, b) +X Gl.index = index - 1 +X return index X X# Compute n**i Xdef pow(n, i): -X x = 1 -X for j in range(i): x = x*n -X return x +X x = 1 +X for j in range(i): x = x*n +X return x X Xdef mouseclick(mouse, updown, x, y): -X if updown = 1: -X # mouse button came down, start tracking -X if Gl.debug: -X print 'mouse', mouse, 'down at', x, y -X if mouse = 2: -X Gl.mouse2down = 1 -X mouse2track(x, y) -X elif mouse = 3: -X Gl.mouse3down = 1 -X mouse3track(x, y) -X else: -X print 'fatal error' -X qdevice(MOUSEX) -X qdevice(MOUSEY) -X return 0 -X else: -X # mouse button came up, stop tracking -X if Gl.debug: -X print 'mouse', mouse, 'up at', x, y -X unqdevice(MOUSEX) -X unqdevice(MOUSEY) -X if mouse = 2: -X mouse2track(x, y) -X Gl.mouse2down = 0 -X elif mouse = 3: -X mouse3track(x, y) -X Gl.mouse3down = 0 -X else: -X print 'fatal error' -X Gl.alarm_set = 1 -X return 1 +X if updown = 1: +X # mouse button came down, start tracking +X if Gl.debug: +X print 'mouse', mouse, 'down at', x, y +X if mouse = 2: +X Gl.mouse2down = 1 +X mouse2track(x, y) +X elif mouse = 3: +X Gl.mouse3down = 1 +X mouse3track(x, y) +X else: +X print 'fatal error' +X qdevice(MOUSEX) +X qdevice(MOUSEY) +X return 0 +X else: +X # mouse button came up, stop tracking +X if Gl.debug: +X print 'mouse', mouse, 'up at', x, y +X unqdevice(MOUSEX) +X unqdevice(MOUSEY) +X if mouse = 2: +X mouse2track(x, y) +X Gl.mouse2down = 0 +X elif mouse = 3: +X mouse3track(x, y) +X Gl.mouse3down = 0 +X else: +X print 'fatal error' +X Gl.alarm_set = 1 +X return 1 X Xdef mouse3track(x, y): -X # first compute polar coordinates from x and y -X cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 -X x, y = x - cx, y - cy -X if (x, y) = (0, 0): return # would cause an exception -X minutes = int(30.5 + 30.0*math.atan2(float(-x), float(-y))/pi) -X if minutes = 60: minutes = 0 -X a,b = Gl.alarm_minutes/15, minutes/15 -X if (a,b) = (0,3): -X # Moved backward through 12 o'clock: -X Gl.alarm_hours = Gl.alarm_hours - 1 -X if Gl.alarm_hours < 0: Gl.alarm_hours = Gl.alarm_hours + 24 -X if (a,b) = (3,0): -X # Moved forward through 12 o'clock: -X Gl.alarm_hours = Gl.alarm_hours + 1 -X if Gl.alarm_hours >= 24: Gl.alarm_hours = Gl.alarm_hours - 24 -X Gl.alarm_minutes = minutes -X seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE -X if seconds <> Gl.alarm_time: -X draw_alarm(rgb_bg()) -X Gl.alarm_time = seconds -X draw_alarm(rgb_fg()) +X # first compute polar coordinates from x and y +X cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 +X x, y = x - cx, y - cy +X if (x, y) = (0, 0): return # would cause an exception +X minutes = int(30.5 + 30.0*math.atan2(float(-x), float(-y))/pi) +X if minutes = 60: minutes = 0 +X a,b = Gl.alarm_minutes/15, minutes/15 +X if (a,b) = (0,3): +X # Moved backward through 12 o'clock: +X Gl.alarm_hours = Gl.alarm_hours - 1 +X if Gl.alarm_hours < 0: Gl.alarm_hours = Gl.alarm_hours + 24 +X if (a,b) = (3,0): +X # Moved forward through 12 o'clock: +X Gl.alarm_hours = Gl.alarm_hours + 1 +X if Gl.alarm_hours >= 24: Gl.alarm_hours = Gl.alarm_hours - 24 +X Gl.alarm_minutes = minutes +X seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE +X if seconds <> Gl.alarm_time: +X draw_alarm(rgb_bg()) +X Gl.alarm_time = seconds +X draw_alarm(rgb_fg()) X Xdef mouse2track(x, y): -X # first compute polar coordinates from x and y -X cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 -X x, y = x - cx, y - cy -X if (x, y) = (0, 0): return # would cause an exception -X hours = int(6.5 - float(Gl.alarm_minutes)/60.0 + 6.0*math.atan2(float(-x), float(-y))/pi) -X if hours = 12: hours = 0 -X if (Gl.alarm_hours,hours) = (0,11): -X # Moved backward through midnight: -X Gl.alarm_hours = 23 -X elif (Gl.alarm_hours,hours) = (12,11): -X # Moved backward through noon: -X Gl.alarm_hours = 11 -X elif (Gl.alarm_hours,hours) = (11,0): -X # Moved forward through noon: -X Gl.alarm_hours = 12 -X elif (Gl.alarm_hours,hours) = (23,0): -X # Moved forward through midnight: -X Gl.alarm_hours = 0 -X elif Gl.alarm_hours < 12: -X Gl.alarm_hours = hours -X else: -X Gl.alarm_hours = hours + 12 -X seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE -X if seconds <> Gl.alarm_time: -X draw_alarm(rgb_bg()) -X Gl.alarm_time = seconds -X draw_alarm(rgb_fg()) +X # first compute polar coordinates from x and y +X cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 +X x, y = x - cx, y - cy +X if (x, y) = (0, 0): return # would cause an exception +X hours = int(6.5 - float(Gl.alarm_minutes)/60.0 + 6.0*math.atan2(float(-x), float(-y))/pi) +X if hours = 12: hours = 0 +X if (Gl.alarm_hours,hours) = (0,11): +X # Moved backward through midnight: +X Gl.alarm_hours = 23 +X elif (Gl.alarm_hours,hours) = (12,11): +X # Moved backward through noon: +X Gl.alarm_hours = 11 +X elif (Gl.alarm_hours,hours) = (11,0): +X # Moved forward through noon: +X Gl.alarm_hours = 12 +X elif (Gl.alarm_hours,hours) = (23,0): +X # Moved forward through midnight: +X Gl.alarm_hours = 0 +X elif Gl.alarm_hours < 12: +X Gl.alarm_hours = hours +X else: +X Gl.alarm_hours = hours + 12 +X seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE +X if seconds <> Gl.alarm_time: +X draw_alarm(rgb_bg()) +X Gl.alarm_time = seconds +X draw_alarm(rgb_fg()) X Xdef initmenu(): -X Gl.pup = pup = newpup() -X addtopup(pup, 'M Clock%t|Alarm On/Off|Seconds Hand On/Off|Quit', 0) +X Gl.pup = pup = newpup() +X addtopup(pup, 'M Clock%t|Alarm On/Off|Seconds Hand On/Off|Quit', 0) X Xdef handlemenu(): -X item = dopup(Gl.pup) -X if item = 1: -X # Toggle alarm -X if Gl.alarm_set: -X Gl.alarm_set = 0 -X Gl.alarm_on = 0 -X else: -X Gl.alarm_set = 1 -X Gl.change = 1 -X clearall() -X elif item = 2: -X # Toggle Seconds Hand -X if Gl.update = 1: -X Gl.update = 60 -X Gl.timernoise = 60 -X else: -X Gl.update = 1 -X Gl.timernoise = 6 -X Gl.change = 1 -X elif item = 3: -X if Gl.debug: print 'Exit' -X sys.exit(0) +X item = dopup(Gl.pup) +X if item = 1: +X # Toggle alarm +X if Gl.alarm_set: +X Gl.alarm_set = 0 +X Gl.alarm_on = 0 +X else: +X Gl.alarm_set = 1 +X Gl.change = 1 +X clearall() +X elif item = 2: +X # Toggle Seconds Hand +X if Gl.update = 1: +X Gl.update = 60 +X Gl.timernoise = 60 +X else: +X Gl.update = 1 +X Gl.timernoise = 6 +X Gl.change = 1 +X elif item = 3: +X if Gl.debug: print 'Exit' +X sys.exit(0) X Xmain() EOF @@ -749,12 +749,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -789,12 +789,12 @@ X X#ifdef TRACE Xstatic int Xprtrace(v, str) -X object *v; -X char *str; +X object *v; +X char *str; X{ -X printf("%s ", str); -X printobject(v, stdout, 0); -X printf("\n"); +X printf("%s ", str); +X printobject(v, stdout, 0); +X printf("\n"); X} X#endif X @@ -803,48 +803,48 @@ X Xobject * Xgetlocals() X{ -X if (current_frame == NULL) -X return NULL; -X else -X return current_frame->f_locals; +X if (current_frame == NULL) +X return NULL; +X else +X return current_frame->f_locals; X} X Xobject * Xgetglobals() X{ -X if (current_frame == NULL) -X return NULL; -X else -X return current_frame->f_globals; +X if (current_frame == NULL) +X return NULL; +X else +X return current_frame->f_globals; X} X Xvoid Xprinttraceback(fp) -X FILE *fp; +X FILE *fp; X{ -X object *v = tb_fetch(); -X if (v != NULL) { -X fprintf(fp, "Stack backtrace (innermost last):\n"); -X tb_print(v, fp); -X DECREF(v); -X } +X object *v = tb_fetch(); +X if (v != NULL) { +X fprintf(fp, "Stack backtrace (innermost last):\n"); +X tb_print(v, fp); +X DECREF(v); +X } X} X X X/* XXX Mixing "print ...," and direct file I/O on stdin/stdout -X XXX has some bad consequences. The needspace flag should -X XXX really be part of the file object. */ +X XXX has some bad consequences. The needspace flag should +X XXX really be part of the file object. */ X Xstatic int needspace; X Xvoid Xflushline() X{ -X FILE *fp = sysgetfile("stdout", stdout); -X if (needspace) { -X fprintf(fp, "\n"); -X needspace = 0; -X } +X FILE *fp = sysgetfile("stdout", stdout); +X if (needspace) { +X fprintf(fp, "\n"); +X needspace = 0; +X } X} X X @@ -852,1334 +852,1334 @@ X/* Test a value used as condition, e.g., in a for or if statement */ X Xstatic int Xtestbool(v) -X object *v; +X object *v; X{ -X if (is_intobject(v)) -X return getintvalue(v) != 0; -X if (is_floatobject(v)) -X return getfloatvalue(v) != 0.0; -X if (v->ob_type->tp_as_sequence != NULL) -X return (*v->ob_type->tp_as_sequence->sq_length)(v) != 0; -X if (v->ob_type->tp_as_mapping != NULL) -X return (*v->ob_type->tp_as_mapping->mp_length)(v) != 0; -X if (v == None) -X return 0; -X /* All other objects are 'true' */ -X return 1; +X if (is_intobject(v)) +X return getintvalue(v) != 0; +X if (is_floatobject(v)) +X return getfloatvalue(v) != 0.0; +X if (v->ob_type->tp_as_sequence != NULL) +X return (*v->ob_type->tp_as_sequence->sq_length)(v) != 0; +X if (v->ob_type->tp_as_mapping != NULL) +X return (*v->ob_type->tp_as_mapping->mp_length)(v) != 0; +X if (v == None) +X return 0; +X /* All other objects are 'true' */ +X return 1; X} X Xstatic object * Xadd(v, w) -X object *v, *w; +X object *v, *w; X{ -X if (v->ob_type->tp_as_number != NULL) -X v = (*v->ob_type->tp_as_number->nb_add)(v, w); -X else if (v->ob_type->tp_as_sequence != NULL) -X v = (*v->ob_type->tp_as_sequence->sq_concat)(v, w); -X else { -X err_setstr(TypeError, "+ not supported by operands"); -X return NULL; -X } -X return v; +X if (v->ob_type->tp_as_number != NULL) +X v = (*v->ob_type->tp_as_number->nb_add)(v, w); +X else if (v->ob_type->tp_as_sequence != NULL) +X v = (*v->ob_type->tp_as_sequence->sq_concat)(v, w); +X else { +X err_setstr(TypeError, "+ not supported by operands"); +X return NULL; +X } +X return v; X} X Xstatic object * Xsub(v, w) -X object *v, *w; +X object *v, *w; X{ -X if (v->ob_type->tp_as_number != NULL) -X return (*v->ob_type->tp_as_number->nb_subtract)(v, w); -X err_setstr(TypeError, "bad operand type(s) for -"); -X return NULL; +X if (v->ob_type->tp_as_number != NULL) +X return (*v->ob_type->tp_as_number->nb_subtract)(v, w); +X err_setstr(TypeError, "bad operand type(s) for -"); +X return NULL; X} X Xstatic object * Xmul(v, w) -X object *v, *w; +X object *v, *w; X{ -X typeobject *tp; -X if (is_intobject(v) && w->ob_type->tp_as_sequence != NULL) { -X /* int*sequence -- swap v and w */ -X object *tmp = v; -X v = w; -X w = tmp; -X } -X tp = v->ob_type; -X if (tp->tp_as_number != NULL) -X return (*tp->tp_as_number->nb_multiply)(v, w); -X if (tp->tp_as_sequence != NULL) { -X if (!is_intobject(w)) { -X err_setstr(TypeError, -X "can't multiply sequence with non-int"); -X return NULL; -X } -X if (tp->tp_as_sequence->sq_repeat == NULL) { -X err_setstr(TypeError, "sequence does not support *"); -X return NULL; -X } -X return (*tp->tp_as_sequence->sq_repeat) -X (v, (int)getintvalue(w)); -X } -X err_setstr(TypeError, "bad operand type(s) for *"); -X return NULL; +X typeobject *tp; +X if (is_intobject(v) && w->ob_type->tp_as_sequence != NULL) { +X /* int*sequence -- swap v and w */ +X object *tmp = v; +X v = w; +X w = tmp; +X } +X tp = v->ob_type; +X if (tp->tp_as_number != NULL) +X return (*tp->tp_as_number->nb_multiply)(v, w); +X if (tp->tp_as_sequence != NULL) { +X if (!is_intobject(w)) { +X err_setstr(TypeError, +X "can't multiply sequence with non-int"); +X return NULL; +X } +X if (tp->tp_as_sequence->sq_repeat == NULL) { +X err_setstr(TypeError, "sequence does not support *"); +X return NULL; +X } +X return (*tp->tp_as_sequence->sq_repeat) +X (v, (int)getintvalue(w)); +X } +X err_setstr(TypeError, "bad operand type(s) for *"); +X return NULL; X} X Xstatic object * Xdivide(v, w) -X object *v, *w; +X object *v, *w; X{ -X if (v->ob_type->tp_as_number != NULL) -X return (*v->ob_type->tp_as_number->nb_divide)(v, w); -X err_setstr(TypeError, "bad operand type(s) for /"); -X return NULL; +X if (v->ob_type->tp_as_number != NULL) +X return (*v->ob_type->tp_as_number->nb_divide)(v, w); +X err_setstr(TypeError, "bad operand type(s) for /"); +X return NULL; X} X Xstatic object * Xrem(v, w) -X object *v, *w; +X object *v, *w; X{ -X if (v->ob_type->tp_as_number != NULL) -X return (*v->ob_type->tp_as_number->nb_remainder)(v, w); -X err_setstr(TypeError, "bad operand type(s) for %"); -X return NULL; +X if (v->ob_type->tp_as_number != NULL) +X return (*v->ob_type->tp_as_number->nb_remainder)(v, w); +X err_setstr(TypeError, "bad operand type(s) for %"); +X return NULL; X} X Xstatic object * Xneg(v) -X object *v; +X object *v; X{ -X if (v->ob_type->tp_as_number != NULL) -X return (*v->ob_type->tp_as_number->nb_negative)(v); -X err_setstr(TypeError, "bad operand type(s) for unary -"); -X return NULL; +X if (v->ob_type->tp_as_number != NULL) +X return (*v->ob_type->tp_as_number->nb_negative)(v); +X err_setstr(TypeError, "bad operand type(s) for unary -"); +X return NULL; X} X Xstatic object * Xpos(v) -X object *v; +X object *v; X{ -X if (v->ob_type->tp_as_number != NULL) -X return (*v->ob_type->tp_as_number->nb_positive)(v); -X err_setstr(TypeError, "bad operand type(s) for unary +"); -X return NULL; +X if (v->ob_type->tp_as_number != NULL) +X return (*v->ob_type->tp_as_number->nb_positive)(v); +X err_setstr(TypeError, "bad operand type(s) for unary +"); +X return NULL; X} X Xstatic object * Xnot(v) -X object *v; +X object *v; X{ -X int outcome = testbool(v); -X object *w = outcome == 0 ? True : False; -X INCREF(w); -X return w; +X int outcome = testbool(v); +X object *w = outcome == 0 ? True : False; +X INCREF(w); +X return w; X} X Xstatic object * Xcall_builtin(func, arg) -X object *func; -X object *arg; +X object *func; +X object *arg; X{ -X if (is_methodobject(func)) { -X method meth = getmethod(func); -X object *self = getself(func); -X return (*meth)(self, arg); -X } -X if (is_classobject(func)) { -X if (arg != NULL) { -X err_setstr(TypeError, -X "classobject() allows no arguments"); -X return NULL; -X } -X return newclassmemberobject(func); -X } -X err_setstr(TypeError, "call of non-function"); -X return NULL; +X if (is_methodobject(func)) { +X method meth = getmethod(func); +X object *self = getself(func); +X return (*meth)(self, arg); +X } +X if (is_classobject(func)) { +X if (arg != NULL) { +X err_setstr(TypeError, +X "classobject() allows no arguments"); +X return NULL; +X } +X return newclassmemberobject(func); +X } +X err_setstr(TypeError, "call of non-function"); +X return NULL; X} X Xstatic object * Xcall_function(func, arg) -X object *func; -X object *arg; +X object *func; +X object *arg; X{ -X object *newarg = NULL; -X object *newlocals, *newglobals; -X object *co, *v; -X -X if (is_classmethodobject(func)) { -X object *self = classmethodgetself(func); -X func = classmethodgetfunc(func); -X if (arg == NULL) { -X arg = self; -X } -X else { -X newarg = newtupleobject(2); -X if (newarg == NULL) -X return NULL; -X INCREF(self); -X INCREF(arg); -X settupleitem(newarg, 0, self); -X settupleitem(newarg, 1, arg); -X arg = newarg; -X } -X } -X else { -X if (!is_funcobject(func)) { -X err_setstr(TypeError, "call of non-function"); -X return NULL; -X } -X } -X -X co = getfunccode(func); -X if (co == NULL) { -X XDECREF(newarg); -X return NULL; -X } -X if (!is_codeobject(co)) { -X fprintf(stderr, "XXX Bad code\n"); -X abort(); -X } -X newlocals = newdictobject(); -X if (newlocals == NULL) { -X XDECREF(newarg); -X return NULL; -X } -X -X newglobals = getfuncglobals(func); -X INCREF(newglobals); -X -X v = eval_code((codeobject *)co, newglobals, newlocals, arg); -X -X DECREF(newlocals); -X DECREF(newglobals); -X -X XDECREF(newarg); -X -X return v; +X object *newarg = NULL; +X object *newlocals, *newglobals; +X object *co, *v; +X +X if (is_classmethodobject(func)) { +X object *self = classmethodgetself(func); +X func = classmethodgetfunc(func); +X if (arg == NULL) { +X arg = self; +X } +X else { +X newarg = newtupleobject(2); +X if (newarg == NULL) +X return NULL; +X INCREF(self); +X INCREF(arg); +X settupleitem(newarg, 0, self); +X settupleitem(newarg, 1, arg); +X arg = newarg; +X } +X } +X else { +X if (!is_funcobject(func)) { +X err_setstr(TypeError, "call of non-function"); +X return NULL; +X } +X } +X +X co = getfunccode(func); +X if (co == NULL) { +X XDECREF(newarg); +X return NULL; +X } +X if (!is_codeobject(co)) { +X fprintf(stderr, "XXX Bad code\n"); +X abort(); +X } +X newlocals = newdictobject(); +X if (newlocals == NULL) { +X XDECREF(newarg); +X return NULL; +X } +X +X newglobals = getfuncglobals(func); +X INCREF(newglobals); +X +X v = eval_code((codeobject *)co, newglobals, newlocals, arg); +X +X DECREF(newlocals); +X DECREF(newglobals); +X +X XDECREF(newarg); +X +X return v; X} X Xstatic object * Xapply_subscript(v, w) -X object *v, *w; +X object *v, *w; X{ -X typeobject *tp = v->ob_type; -X if (tp->tp_as_sequence == NULL && tp->tp_as_mapping == NULL) { -X err_setstr(TypeError, "unsubscriptable object"); -X return NULL; -X } -X if (tp->tp_as_sequence != NULL) { -X int i; -X if (!is_intobject(w)) { -X err_setstr(TypeError, "sequence subscript not int"); -X return NULL; -X } -X i = getintvalue(w); -X return (*tp->tp_as_sequence->sq_item)(v, i); -X } -X return (*tp->tp_as_mapping->mp_subscript)(v, w); +X typeobject *tp = v->ob_type; +X if (tp->tp_as_sequence == NULL && tp->tp_as_mapping == NULL) { +X err_setstr(TypeError, "unsubscriptable object"); +X return NULL; +X } +X if (tp->tp_as_sequence != NULL) { +X int i; +X if (!is_intobject(w)) { +X err_setstr(TypeError, "sequence subscript not int"); +X return NULL; +X } +X i = getintvalue(w); +X return (*tp->tp_as_sequence->sq_item)(v, i); +X } +X return (*tp->tp_as_mapping->mp_subscript)(v, w); X} X Xstatic object * Xloop_subscript(v, w) -X object *v, *w; +X object *v, *w; X{ -X sequence_methods *sq = v->ob_type->tp_as_sequence; -X int i, n; -X if (sq == NULL) { -X err_setstr(TypeError, "loop over non-sequence"); -X return NULL; -X } -X i = getintvalue(w); -X n = (*sq->sq_length)(v); -X if (i >= n) -X return NULL; /* End of loop */ -X return (*sq->sq_item)(v, i); +X sequence_methods *sq = v->ob_type->tp_as_sequence; +X int i, n; +X if (sq == NULL) { +X err_setstr(TypeError, "loop over non-sequence"); +X return NULL; +X } +X i = getintvalue(w); +X n = (*sq->sq_length)(v); +X if (i >= n) +X return NULL; /* End of loop */ +X return (*sq->sq_item)(v, i); X} X Xstatic int Xslice_index(v, isize, pi) -X object *v; -X int isize; -X int *pi; +X object *v; +X int isize; +X int *pi; X{ -X if (v != NULL) { -X if (!is_intobject(v)) { -X err_setstr(TypeError, "slice index must be int"); -X return -1; -X } -X *pi = getintvalue(v); -X if (*pi < 0) -X *pi += isize; -X } -X return 0; +X if (v != NULL) { +X if (!is_intobject(v)) { +X err_setstr(TypeError, "slice index must be int"); +X return -1; +X } +X *pi = getintvalue(v); +X if (*pi < 0) +X *pi += isize; +X } +X return 0; X} X Xstatic object * Xapply_slice(u, v, w) /* return u[v:w] */ -X object *u, *v, *w; +X object *u, *v, *w; X{ -X typeobject *tp = u->ob_type; -X int ilow, ihigh, isize; -X if (tp->tp_as_sequence == NULL) { -X err_setstr(TypeError, "only sequences can be sliced"); -X return NULL; -X } -X ilow = 0; -X isize = ihigh = (*tp->tp_as_sequence->sq_length)(u); -X if (slice_index(v, isize, &ilow) != 0) -X return NULL; -X if (slice_index(w, isize, &ihigh) != 0) -X return NULL; -X return (*tp->tp_as_sequence->sq_slice)(u, ilow, ihigh); +X typeobject *tp = u->ob_type; +X int ilow, ihigh, isize; +X if (tp->tp_as_sequence == NULL) { +X err_setstr(TypeError, "only sequences can be sliced"); +X return NULL; +X } +X ilow = 0; +X isize = ihigh = (*tp->tp_as_sequence->sq_length)(u); +X if (slice_index(v, isize, &ilow) != 0) +X return NULL; +X if (slice_index(w, isize, &ihigh) != 0) +X return NULL; +X return (*tp->tp_as_sequence->sq_slice)(u, ilow, ihigh); X} X Xstatic int Xassign_subscript(w, key, v) /* w[key] = v */ -X object *w; -X object *key; -X object *v; +X object *w; +X object *key; +X object *v; X{ -X typeobject *tp = w->ob_type; -X sequence_methods *sq; -X mapping_methods *mp; -X int (*func)(); -X if ((sq = tp->tp_as_sequence) != NULL && -X (func = sq->sq_ass_item) != NULL) { -X if (!is_intobject(key)) { -X err_setstr(TypeError, -X "sequence subscript must be integer"); -X return -1; -X } -X else -X return (*func)(w, (int)getintvalue(key), v); -X } -X else if ((mp = tp->tp_as_mapping) != NULL && -X (func = mp->mp_ass_subscript) != NULL) { -X return (*func)(w, key, v); -X } -X else { -X err_setstr(TypeError, -X "can't assign to this subscripted object"); -X return -1; -X } +X typeobject *tp = w->ob_type; +X sequence_methods *sq; +X mapping_methods *mp; +X int (*func)(); +X if ((sq = tp->tp_as_sequence) != NULL && +X (func = sq->sq_ass_item) != NULL) { +X if (!is_intobject(key)) { +X err_setstr(TypeError, +X "sequence subscript must be integer"); +X return -1; +X } +X else +X return (*func)(w, (int)getintvalue(key), v); +X } +X else if ((mp = tp->tp_as_mapping) != NULL && +X (func = mp->mp_ass_subscript) != NULL) { +X return (*func)(w, key, v); +X } +X else { +X err_setstr(TypeError, +X "can't assign to this subscripted object"); +X return -1; +X } X} X Xstatic int Xassign_slice(u, v, w, x) /* u[v:w] = x */ -X object *u, *v, *w, *x; +X object *u, *v, *w, *x; X{ -X sequence_methods *sq = u->ob_type->tp_as_sequence; -X int ilow, ihigh, isize; -X if (sq == NULL) { -X err_setstr(TypeError, "assign to slice of non-sequence"); -X return -1; -X } -X if (sq == NULL || sq->sq_ass_slice == NULL) { -X err_setstr(TypeError, "unassignable slice"); -X return -1; -X } -X ilow = 0; -X isize = ihigh = (*sq->sq_length)(u); -X if (slice_index(v, isize, &ilow) != 0) -X return -1; -X if (slice_index(w, isize, &ihigh) != 0) -X return -1; -X return (*sq->sq_ass_slice)(u, ilow, ihigh, x); +X sequence_methods *sq = u->ob_type->tp_as_sequence; +X int ilow, ihigh, isize; +X if (sq == NULL) { +X err_setstr(TypeError, "assign to slice of non-sequence"); +X return -1; +X } +X if (sq == NULL || sq->sq_ass_slice == NULL) { +X err_setstr(TypeError, "unassignable slice"); +X return -1; +X } +X ilow = 0; +X isize = ihigh = (*sq->sq_length)(u); +X if (slice_index(v, isize, &ilow) != 0) +X return -1; +X if (slice_index(w, isize, &ihigh) != 0) +X return -1; +X return (*sq->sq_ass_slice)(u, ilow, ihigh, x); X} X Xstatic int Xcmp_exception(err, v) -X object *err, *v; +X object *err, *v; X{ -X if (is_tupleobject(v)) { -X int i, n; -X n = gettuplesize(v); -X for (i = 0; i < n; i++) { -X if (err == gettupleitem(v, i)) -X return 1; -X } -X return 0; -X } -X return err == v; +X if (is_tupleobject(v)) { +X int i, n; +X n = gettuplesize(v); +X for (i = 0; i < n; i++) { +X if (err == gettupleitem(v, i)) +X return 1; +X } +X return 0; +X } +X return err == v; X} X Xstatic int Xcmp_member(v, w) -X object *v, *w; +X object *v, *w; X{ -X int i, n, cmp; -X object *x; -X sequence_methods *sq; -X /* Special case for char in string */ -X if (is_stringobject(w)) { -X register char *s, *end; -X register char c; -X if (!is_stringobject(v) || getstringsize(v) != 1) { -X err_setstr(TypeError, -X "string member test needs char left operand"); -X return -1; -X } -X c = getstringvalue(v)[0]; -X s = getstringvalue(w); -X end = s + getstringsize(w); -X while (s < end) { -X if (c == *s++) -X return 1; -X } -X return 0; -X } -X sq = w->ob_type->tp_as_sequence; -X if (sq == NULL) { -X err_setstr(TypeError, -X "'in' or 'not in' needs sequence right argument"); -X return -1; -X } -X n = (*sq->sq_length)(w); -X for (i = 0; i < n; i++) { -X x = (*sq->sq_item)(w, i); -X cmp = cmpobject(v, x); -X XDECREF(x); -X if (cmp == 0) -X return 1; -X } -X return 0; +X int i, n, cmp; +X object *x; +X sequence_methods *sq; +X /* Special case for char in string */ +X if (is_stringobject(w)) { +X register char *s, *end; +X register char c; +X if (!is_stringobject(v) || getstringsize(v) != 1) { +X err_setstr(TypeError, +X "string member test needs char left operand"); +X return -1; +X } +X c = getstringvalue(v)[0]; +X s = getstringvalue(w); +X end = s + getstringsize(w); +X while (s < end) { +X if (c == *s++) +X return 1; +X } +X return 0; +X } +X sq = w->ob_type->tp_as_sequence; +X if (sq == NULL) { +X err_setstr(TypeError, +X "'in' or 'not in' needs sequence right argument"); +X return -1; +X } +X n = (*sq->sq_length)(w); +X for (i = 0; i < n; i++) { +X x = (*sq->sq_item)(w, i); +X cmp = cmpobject(v, x); +X XDECREF(x); +X if (cmp == 0) +X return 1; +X } +X return 0; X} X Xstatic object * Xcmp_outcome(op, v, w) -X enum cmp_op op; -X register object *v; -X register object *w; +X enum cmp_op op; +X register object *v; +X register object *w; X{ -X register int cmp; -X register int res = 0; -X switch (op) { -X case IS: -X case IS_NOT: -X res = (v == w); -X if (op == IS_NOT) -X res = !res; -X break; -X case IN: -X case NOT_IN: -X res = cmp_member(v, w); -X if (res < 0) -X return NULL; -X if (op == NOT_IN) -X res = !res; -X break; -X case EXC_MATCH: -X res = cmp_exception(v, w); -X break; -X default: -X cmp = cmpobject(v, w); -X switch (op) { -X case LT: res = cmp < 0; break; -X case LE: res = cmp <= 0; break; -X case EQ: res = cmp == 0; break; -X case NE: res = cmp != 0; break; -X case GT: res = cmp > 0; break; -X case GE: res = cmp >= 0; break; -X /* XXX no default? (res is initialized to 0 though) */ -X } -X } -X v = res ? True : False; -X INCREF(v); -X return v; +X register int cmp; +X register int res = 0; +X switch (op) { +X case IS: +X case IS_NOT: +X res = (v == w); +X if (op == IS_NOT) +X res = !res; +X break; +X case IN: +X case NOT_IN: +X res = cmp_member(v, w); +X if (res < 0) +X return NULL; +X if (op == NOT_IN) +X res = !res; +X break; +X case EXC_MATCH: +X res = cmp_exception(v, w); +X break; +X default: +X cmp = cmpobject(v, w); +X switch (op) { +X case LT: res = cmp < 0; break; +X case LE: res = cmp <= 0; break; +X case EQ: res = cmp == 0; break; +X case NE: res = cmp != 0; break; +X case GT: res = cmp > 0; break; +X case GE: res = cmp >= 0; break; +X /* XXX no default? (res is initialized to 0 though) */ +X } +X } +X v = res ? True : False; +X INCREF(v); +X return v; X} X Xstatic int Ximport_from(locals, v, name) -X object *locals; -X object *v; -X char *name; +X object *locals; +X object *v; +X char *name; X{ -X object *w, *x; -X w = getmoduledict(v); -X if (name[0] == '*') { -X int i; -X int n = getdictsize(w); -X for (i = 0; i < n; i++) { -X name = getdictkey(w, i); -X if (name == NULL || name[0] == '_') -X continue; -X x = dictlookup(w, name); -X if (x == NULL) { -X /* XXX can't happen? */ -X err_setstr(NameError, name); -X return -1; -X } -X if (dictinsert(locals, name, x) != 0) -X return -1; -X } -X return 0; -X } -X else { -X x = dictlookup(w, name); -X if (x == NULL) { -X err_setstr(NameError, name); -X return -1; -X } -X else -X return dictinsert(locals, name, x); -X } +X object *w, *x; +X w = getmoduledict(v); +X if (name[0] == '*') { +X int i; +X int n = getdictsize(w); +X for (i = 0; i < n; i++) { +X name = getdictkey(w, i); +X if (name == NULL || name[0] == '_') +X continue; +X x = dictlookup(w, name); +X if (x == NULL) { +X /* XXX can't happen? */ +X err_setstr(NameError, name); +X return -1; +X } +X if (dictinsert(locals, name, x) != 0) +X return -1; +X } +X return 0; +X } +X else { +X x = dictlookup(w, name); +X if (x == NULL) { +X err_setstr(NameError, name); +X return -1; +X } +X else +X return dictinsert(locals, name, x); +X } X} X Xstatic object * Xbuild_class(v, w) -X object *v; /* None or tuple containing base classes */ -X object *w; /* dictionary */ +X object *v; /* None or tuple containing base classes */ +X object *w; /* dictionary */ X{ -X if (is_tupleobject(v)) { -X int i; -X for (i = gettuplesize(v); --i >= 0; ) { -X object *x = gettupleitem(v, i); -X if (!is_classobject(x)) { -X err_setstr(TypeError, -X "base is not a class object"); -X return NULL; -X } -X } -X } -X else { -X v = NULL; -X } -X if (!is_dictobject(w)) { -X err_setstr(SystemError, "build_class with non-dictionary"); -X return NULL; -X } -X return newclassobject(v, w); +X if (is_tupleobject(v)) { +X int i; +X for (i = gettuplesize(v); --i >= 0; ) { +X object *x = gettupleitem(v, i); +X if (!is_classobject(x)) { +X err_setstr(TypeError, +X "base is not a class object"); +X return NULL; +X } +X } +X } +X else { +X v = NULL; +X } +X if (!is_dictobject(w)) { +X err_setstr(SystemError, "build_class with non-dictionary"); +X return NULL; +X } +X return newclassobject(v, w); X} X X X/* Status code for main loop (reason for stack unwind) */ X Xenum why_code { -X WHY_NOT, /* No error */ -X WHY_EXCEPTION, /* Exception occurred */ -X WHY_RERAISE, /* Exception re-raised by 'finally' */ -X WHY_RETURN, /* 'return' statement */ -X WHY_BREAK /* 'break' statement */ +X WHY_NOT, /* No error */ +X WHY_EXCEPTION, /* Exception occurred */ +X WHY_RERAISE, /* Exception re-raised by 'finally' */ +X WHY_RETURN, /* 'return' statement */ +X WHY_BREAK /* 'break' statement */ X}; X X/* Interpreter main loop */ X Xobject * Xeval_code(co, globals, locals, arg) -X codeobject *co; -X object *globals; -X object *locals; -X object *arg; +X codeobject *co; +X object *globals; +X object *locals; +X object *arg; X{ -X register unsigned char *next_instr; -X register int opcode; /* Current opcode */ -X register int oparg; /* Current opcode argument, if any */ -X register object **stack_pointer; -X register enum why_code why; /* Reason for block stack unwind */ -X register int err; /* Error status -- nonzero if error */ -X register object *x; /* Result object -- NULL if error */ -X register object *v; /* Temporary objects popped off stack */ -X register object *w; -X register object *u; -X register object *t; -X register frameobject *f; /* Current frame */ -X int lineno; /* Current line number */ -X object *retval; /* Return value iff why == WHY_RETURN */ -X char *name; /* Name used by some instructions */ -X FILE *fp; /* Used by print operations */ +X register unsigned char *next_instr; +X register int opcode; /* Current opcode */ +X register int oparg; /* Current opcode argument, if any */ +X register object **stack_pointer; +X register enum why_code why; /* Reason for block stack unwind */ +X register int err; /* Error status -- nonzero if error */ +X register object *x; /* Result object -- NULL if error */ +X register object *v; /* Temporary objects popped off stack */ +X register object *w; +X register object *u; +X register object *t; +X register frameobject *f; /* Current frame */ +X int lineno; /* Current line number */ +X object *retval; /* Return value iff why == WHY_RETURN */ +X char *name; /* Name used by some instructions */ +X FILE *fp; /* Used by print operations */ X#ifdef TRACE -X int trace = dictlookup(globals, "__trace__") != NULL; +X int trace = dictlookup(globals, "__trace__") != NULL; X#endif X X/* Code access macros */ X -X#define GETCONST(i) Getconst(f, i) -X#define GETNAME(i) Getname(f, i) -X#define FIRST_INSTR() (GETUSTRINGVALUE(f->f_code->co_code)) -X#define INSTR_OFFSET() (next_instr - FIRST_INSTR()) -X#define NEXTOP() (*next_instr++) -X#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) -X#define JUMPTO(x) (next_instr = FIRST_INSTR() + (x)) -X#define JUMPBY(x) (next_instr += (x)) +X#define GETCONST(i) Getconst(f, i) +X#define GETNAME(i) Getname(f, i) +X#define FIRST_INSTR() (GETUSTRINGVALUE(f->f_code->co_code)) +X#define INSTR_OFFSET() (next_instr - FIRST_INSTR()) +X#define NEXTOP() (*next_instr++) +X#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) +X#define JUMPTO(x) (next_instr = FIRST_INSTR() + (x)) +X#define JUMPBY(x) (next_instr += (x)) X X/* Stack manipulation macros */ X -X#define STACK_LEVEL() (stack_pointer - f->f_valuestack) -X#define EMPTY() (STACK_LEVEL() == 0) -X#define TOP() (stack_pointer[-1]) -X#define BASIC_PUSH(v) (*stack_pointer++ = (v)) -X#define BASIC_POP() (*--stack_pointer) +X#define STACK_LEVEL() (stack_pointer - f->f_valuestack) +X#define EMPTY() (STACK_LEVEL() == 0) +X#define TOP() (stack_pointer[-1]) +X#define BASIC_PUSH(v) (*stack_pointer++ = (v)) +X#define BASIC_POP() (*--stack_pointer) X X#ifdef TRACE -X#define PUSH(v) (BASIC_PUSH(v), trace && prtrace(TOP(), "push")) -X#define POP() (trace && prtrace(TOP(), "pop"), BASIC_POP()) +X#define PUSH(v) (BASIC_PUSH(v), trace && prtrace(TOP(), "push")) +X#define POP() (trace && prtrace(TOP(), "pop"), BASIC_POP()) X#else -X#define PUSH(v) BASIC_PUSH(v) -X#define POP() BASIC_POP() +X#define PUSH(v) BASIC_PUSH(v) +X#define POP() BASIC_POP() X#endif X -X f = newframeobject( -X current_frame, /*back*/ -X co, /*code*/ -X globals, /*globals*/ -X locals, /*locals*/ -X 50, /*nvalues*/ -X 20); /*nblocks*/ -X if (f == NULL) -X return NULL; -X -X current_frame = f; -X -X next_instr = GETUSTRINGVALUE(f->f_code->co_code); -X -X stack_pointer = f->f_valuestack; -X -X if (arg != NULL) { -X INCREF(arg); -X PUSH(arg); -X } -X -X why = WHY_NOT; -X err = 0; -X x = None; /* Not a reference, just anything non-NULL */ -X lineno = -1; -X -X for (;;) { -X static ticker; -X -X /* Do periodic things */ -X -X if (--ticker < 0) { -X ticker = 100; -X if (intrcheck()) { -X err_set(KeyboardInterrupt); -X why = WHY_EXCEPTION; -X tb_here(f, INSTR_OFFSET(), lineno); -X break; -X } -X } -X -X /* Extract opcode and argument */ -X -X opcode = NEXTOP(); -X if (HAS_ARG(opcode)) -X oparg = NEXTARG(); +X f = newframeobject( +X current_frame, /*back*/ +X co, /*code*/ +X globals, /*globals*/ +X locals, /*locals*/ +X 50, /*nvalues*/ +X 20); /*nblocks*/ +X if (f == NULL) +X return NULL; +X +X current_frame = f; +X +X next_instr = GETUSTRINGVALUE(f->f_code->co_code); +X +X stack_pointer = f->f_valuestack; +X +X if (arg != NULL) { +X INCREF(arg); +X PUSH(arg); +X } +X +X why = WHY_NOT; +X err = 0; +X x = None; /* Not a reference, just anything non-NULL */ +X lineno = -1; +X +X for (;;) { +X static ticker; +X +X /* Do periodic things */ +X +X if (--ticker < 0) { +X ticker = 100; +X if (intrcheck()) { +X err_set(KeyboardInterrupt); +X why = WHY_EXCEPTION; +X tb_here(f, INSTR_OFFSET(), lineno); +X break; +X } +X } +X +X /* Extract opcode and argument */ +X +X opcode = NEXTOP(); +X if (HAS_ARG(opcode)) +X oparg = NEXTARG(); X X#ifdef TRACE -X /* Instruction tracing */ -X -X if (trace) { -X if (HAS_ARG(opcode)) { -X printf("%d: %d, %d\n", -X (int) (INSTR_OFFSET() - 3), -X opcode, oparg); -X } -X else { -X printf("%d: %d\n", -X (int) (INSTR_OFFSET() - 1), opcode); -X } -X } +X /* Instruction tracing */ +X +X if (trace) { +X if (HAS_ARG(opcode)) { +X printf("%d: %d, %d\n", +X (int) (INSTR_OFFSET() - 3), +X opcode, oparg); +X } +X else { +X printf("%d: %d\n", +X (int) (INSTR_OFFSET() - 1), opcode); +X } +X } X#endif X -X /* Main switch on opcode */ -X -X switch (opcode) { -X -X /* BEWARE! -X It is essential that any operation that fails sets either -X x to NULL, err to nonzero, or why to anything but WHY_NOT, -X and that no operation that succeeds does this! */ -X -X /* case STOP_CODE: this is an error! */ -X -X case POP_TOP: -X v = POP(); -X DECREF(v); -X break; -X -X case ROT_TWO: -X v = POP(); -X w = POP(); -X PUSH(v); -X PUSH(w); -X break; -X -X case ROT_THREE: -X v = POP(); -X w = POP(); -X x = POP(); -X PUSH(v); -X PUSH(x); -X PUSH(w); -X break; -X -X case DUP_TOP: -X v = TOP(); -X INCREF(v); -X PUSH(v); -X break; -X -X case UNARY_POSITIVE: -X v = POP(); -X x = pos(v); -X DECREF(v); -X PUSH(x); -X break; -X -X case UNARY_NEGATIVE: -X v = POP(); -X x = neg(v); -X DECREF(v); -X PUSH(x); -X break; -X -X case UNARY_NOT: -X v = POP(); -X x = not(v); -X DECREF(v); -X PUSH(x); -X break; -X -X case UNARY_CONVERT: -X v = POP(); -X x = reprobject(v); -X DECREF(v); -X PUSH(x); -X break; -X -X case UNARY_CALL: -X v = POP(); -X if (is_classmethodobject(v) || is_funcobject(v)) -X x = call_function(v, (object *)NULL); -X else -X x = call_builtin(v, (object *)NULL); -X DECREF(v); -X PUSH(x); -X break; -X -X case BINARY_MULTIPLY: -X w = POP(); -X v = POP(); -X x = mul(v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case BINARY_DIVIDE: -X w = POP(); -X v = POP(); -X x = divide(v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case BINARY_MODULO: -X w = POP(); -X v = POP(); -X x = rem(v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case BINARY_ADD: -X w = POP(); -X v = POP(); -X x = add(v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case BINARY_SUBTRACT: -X w = POP(); -X v = POP(); -X x = sub(v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case BINARY_SUBSCR: -X w = POP(); -X v = POP(); -X x = apply_subscript(v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case BINARY_CALL: -X w = POP(); -X v = POP(); -X if (is_classmethodobject(v) || is_funcobject(v)) -X x = call_function(v, w); -X else -X x = call_builtin(v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case SLICE+0: -X case SLICE+1: -X case SLICE+2: -X case SLICE+3: -X if ((opcode-SLICE) & 2) -X w = POP(); -X else -X w = NULL; -X if ((opcode-SLICE) & 1) -X v = POP(); -X else -X v = NULL; -X u = POP(); -X x = apply_slice(u, v, w); -X DECREF(u); -X XDECREF(v); -X XDECREF(w); -X PUSH(x); -X break; -X -X case STORE_SLICE+0: -X case STORE_SLICE+1: -X case STORE_SLICE+2: -X case STORE_SLICE+3: -X if ((opcode-STORE_SLICE) & 2) -X w = POP(); -X else -X w = NULL; -X if ((opcode-STORE_SLICE) & 1) -X v = POP(); -X else -X v = NULL; -X u = POP(); -X t = POP(); -X err = assign_slice(u, v, w, t); /* u[v:w] = t */ -X DECREF(t); -X DECREF(u); -X XDECREF(v); -X XDECREF(w); -X break; -X -X case DELETE_SLICE+0: -X case DELETE_SLICE+1: -X case DELETE_SLICE+2: -X case DELETE_SLICE+3: -X if ((opcode-DELETE_SLICE) & 2) -X w = POP(); -X else -X w = NULL; -X if ((opcode-DELETE_SLICE) & 1) -X v = POP(); -X else -X v = NULL; -X u = POP(); -X err = assign_slice(u, v, w, (object *)NULL); -X /* del u[v:w] */ -X DECREF(u); -X XDECREF(v); -X XDECREF(w); -X break; -X -X case STORE_SUBSCR: -X w = POP(); -X v = POP(); -X u = POP(); -X /* v[w] = u */ -X err = assign_subscript(v, w, u); -X DECREF(u); -X DECREF(v); -X DECREF(w); -X break; -X -X case DELETE_SUBSCR: -X w = POP(); -X v = POP(); -X /* del v[w] */ -X err = assign_subscript(v, w, (object *)NULL); -X DECREF(v); -X DECREF(w); -X break; -X -X case PRINT_EXPR: -X v = POP(); -X fp = sysgetfile("stdout", stdout); -X /* Print value except if procedure result */ -X if (v != None) { -X flushline(); -X printobject(v, fp, 0); -X fprintf(fp, "\n"); -X } -X DECREF(v); -X break; -X -X case PRINT_ITEM: -X v = POP(); -X fp = sysgetfile("stdout", stdout); -X if (needspace) -X fprintf(fp, " "); -X if (is_stringobject(v)) { -X char *s = getstringvalue(v); -X int len = getstringsize(v); -X fwrite(s, 1, len, fp); -X if (len > 0 && s[len-1] == '\n') -X needspace = 0; -X else -X needspace = 1; -X } -X else { -X printobject(v, fp, 0); -X needspace = 1; -X } -X DECREF(v); -X break; -X -X case PRINT_NEWLINE: -X fp = sysgetfile("stdout", stdout); -X fprintf(fp, "\n"); -X needspace = 0; -X break; -X -X case BREAK_LOOP: -X why = WHY_BREAK; -X break; -X -X case RAISE_EXCEPTION: -X v = POP(); -X w = POP(); -X if (!is_stringobject(w)) -X err_setstr(TypeError, -X "exceptions must be strings"); -X else -X err_setval(w, v); -X DECREF(v); -X DECREF(w); -X why = WHY_EXCEPTION; -X break; -X -X case LOAD_LOCALS: -X v = f->f_locals; -X INCREF(v); -X PUSH(v); -X break; -X -X case RETURN_VALUE: -X retval = POP(); -X why = WHY_RETURN; -X break; -X -X case REQUIRE_ARGS: -X if (EMPTY()) { -X err_setstr(TypeError, -X "function expects argument(s)"); -X why = WHY_EXCEPTION; -X } -X break; -X -X case REFUSE_ARGS: -X if (!EMPTY()) { -X err_setstr(TypeError, -X "function expects no argument(s)"); -X why = WHY_EXCEPTION; -X } -X break; -X -X case BUILD_FUNCTION: -X v = POP(); -X x = newfuncobject(v, f->f_globals); -X DECREF(v); -X PUSH(x); -X break; -X -X case POP_BLOCK: -X { -X block *b = pop_block(f); -X while (STACK_LEVEL() > b->b_level) { -X v = POP(); -X DECREF(v); -X } -X } -X break; -X -X case END_FINALLY: -X v = POP(); -X if (is_intobject(v)) { -X why = (enum why_code) getintvalue(v); -X if (why == WHY_RETURN) -X retval = POP(); -X } -X else if (is_stringobject(v)) { -X w = POP(); -X err_setval(v, w); -X DECREF(w); -X w = POP(); -X tb_store(w); -X DECREF(w); -X why = WHY_RERAISE; -X } -X else if (v != None) { -X err_setstr(SystemError, -X "'finally' pops bad exception"); -X why = WHY_EXCEPTION; -X } -X DECREF(v); -X break; -X -X case BUILD_CLASS: -X w = POP(); -X v = POP(); -X x = build_class(v, w); -X PUSH(x); -X DECREF(v); -X DECREF(w); -X break; -X -X case STORE_NAME: -X name = GETNAME(oparg); -X v = POP(); -X err = dictinsert(f->f_locals, name, v); -X DECREF(v); -X break; -X -X case DELETE_NAME: -X name = GETNAME(oparg); -X if ((err = dictremove(f->f_locals, name)) != 0) -X err_setstr(NameError, name); -X break; -X -X case UNPACK_TUPLE: -X v = POP(); -X if (!is_tupleobject(v)) { -X err_setstr(TypeError, "unpack non-tuple"); -X why = WHY_EXCEPTION; -X } -X else if (gettuplesize(v) != oparg) { -X err_setstr(RuntimeError, -X "unpack tuple of wrong size"); -X why = WHY_EXCEPTION; -X } -X else { -X for (; --oparg >= 0; ) { -X w = gettupleitem(v, oparg); -X INCREF(w); -X PUSH(w); -X } -X } -X DECREF(v); -X break; -X -X case UNPACK_LIST: -X v = POP(); -X if (!is_listobject(v)) { -X err_setstr(TypeError, "unpack non-list"); -X why = WHY_EXCEPTION; -X } -X else if (getlistsize(v) != oparg) { -X err_setstr(RuntimeError, -X "unpack list of wrong size"); -X why = WHY_EXCEPTION; -X } -X else { -X for (; --oparg >= 0; ) { -X w = getlistitem(v, oparg); -X INCREF(w); -X PUSH(w); -X } -X } -X DECREF(v); -X break; -X -X case STORE_ATTR: -X name = GETNAME(oparg); -X v = POP(); -X u = POP(); -X err = setattr(v, name, u); /* v.name = u */ -X DECREF(v); -X DECREF(u); -X break; -X -X case DELETE_ATTR: -X name = GETNAME(oparg); -X v = POP(); -X err = setattr(v, name, (object *)NULL); -X /* del v.name */ -X DECREF(v); -X break; -X -X case LOAD_CONST: -X x = GETCONST(oparg); -X INCREF(x); -X PUSH(x); -X break; -X -X case LOAD_NAME: -X name = GETNAME(oparg); -X x = dictlookup(f->f_locals, name); -X if (x == NULL) { -X x = dictlookup(f->f_globals, name); -X if (x == NULL) -X x = getbuiltin(name); -X } -X if (x == NULL) -X err_setstr(NameError, name); -X else -X INCREF(x); -X PUSH(x); -X break; -X -X case BUILD_TUPLE: -X x = newtupleobject(oparg); -X if (x != NULL) { -X for (; --oparg >= 0;) { -X w = POP(); -X err = settupleitem(x, oparg, w); -X if (err != 0) -X break; -X } -X PUSH(x); -X } -X break; -X -X case BUILD_LIST: -X x = newlistobject(oparg); -X if (x != NULL) { -X for (; --oparg >= 0;) { -X w = POP(); -X err = setlistitem(x, oparg, w); -X if (err != 0) -X break; -X } -X PUSH(x); -X } -X break; -X -X case BUILD_MAP: -X x = newdictobject(); -X PUSH(x); -X break; -X -X case LOAD_ATTR: -X name = GETNAME(oparg); -X v = POP(); -X x = getattr(v, name); -X DECREF(v); -X PUSH(x); -X break; -X -X case COMPARE_OP: -X w = POP(); -X v = POP(); -X x = cmp_outcome((enum cmp_op)oparg, v, w); -X DECREF(v); -X DECREF(w); -X PUSH(x); -X break; -X -X case IMPORT_NAME: -X name = GETNAME(oparg); -X x = import_module(name); -X XINCREF(x); -X PUSH(x); -X break; -X -X case IMPORT_FROM: -X name = GETNAME(oparg); -X v = TOP(); -X err = import_from(f->f_locals, v, name); -X break; -X -X case JUMP_FORWARD: -X JUMPBY(oparg); -X break; -X -X case JUMP_IF_FALSE: -X if (!testbool(TOP())) -X JUMPBY(oparg); -X break; -X -X case JUMP_IF_TRUE: -X if (testbool(TOP())) -X JUMPBY(oparg); -X break; -X -X case JUMP_ABSOLUTE: -X JUMPTO(oparg); -X break; -X -X case FOR_LOOP: -X /* for v in s: ... -X On entry: stack contains s, i. -X On exit: stack contains s, i+1, s[i]; -X but if loop exhausted: -X s, i are popped, and we jump */ -X w = POP(); /* Loop index */ -X v = POP(); /* Sequence object */ -X u = loop_subscript(v, w); -X if (u != NULL) { -X PUSH(v); -X x = newintobject(getintvalue(w)+1); -X PUSH(x); -X DECREF(w); -X PUSH(u); -X } -X else { -X DECREF(v); -X DECREF(w); -X /* A NULL can mean "s exhausted" -X but also an error: */ -X if (err_occurred()) -X why = WHY_EXCEPTION; -X else -X JUMPBY(oparg); -X } -X break; -X -X case SETUP_LOOP: -X case SETUP_EXCEPT: -X case SETUP_FINALLY: -X setup_block(f, opcode, INSTR_OFFSET() + oparg, -X STACK_LEVEL()); -X break; -X -X case SET_LINENO: +X /* Main switch on opcode */ +X +X switch (opcode) { +X +X /* BEWARE! +X It is essential that any operation that fails sets either +X x to NULL, err to nonzero, or why to anything but WHY_NOT, +X and that no operation that succeeds does this! */ +X +X /* case STOP_CODE: this is an error! */ +X +X case POP_TOP: +X v = POP(); +X DECREF(v); +X break; +X +X case ROT_TWO: +X v = POP(); +X w = POP(); +X PUSH(v); +X PUSH(w); +X break; +X +X case ROT_THREE: +X v = POP(); +X w = POP(); +X x = POP(); +X PUSH(v); +X PUSH(x); +X PUSH(w); +X break; +X +X case DUP_TOP: +X v = TOP(); +X INCREF(v); +X PUSH(v); +X break; +X +X case UNARY_POSITIVE: +X v = POP(); +X x = pos(v); +X DECREF(v); +X PUSH(x); +X break; +X +X case UNARY_NEGATIVE: +X v = POP(); +X x = neg(v); +X DECREF(v); +X PUSH(x); +X break; +X +X case UNARY_NOT: +X v = POP(); +X x = not(v); +X DECREF(v); +X PUSH(x); +X break; +X +X case UNARY_CONVERT: +X v = POP(); +X x = reprobject(v); +X DECREF(v); +X PUSH(x); +X break; +X +X case UNARY_CALL: +X v = POP(); +X if (is_classmethodobject(v) || is_funcobject(v)) +X x = call_function(v, (object *)NULL); +X else +X x = call_builtin(v, (object *)NULL); +X DECREF(v); +X PUSH(x); +X break; +X +X case BINARY_MULTIPLY: +X w = POP(); +X v = POP(); +X x = mul(v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case BINARY_DIVIDE: +X w = POP(); +X v = POP(); +X x = divide(v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case BINARY_MODULO: +X w = POP(); +X v = POP(); +X x = rem(v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case BINARY_ADD: +X w = POP(); +X v = POP(); +X x = add(v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case BINARY_SUBTRACT: +X w = POP(); +X v = POP(); +X x = sub(v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case BINARY_SUBSCR: +X w = POP(); +X v = POP(); +X x = apply_subscript(v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case BINARY_CALL: +X w = POP(); +X v = POP(); +X if (is_classmethodobject(v) || is_funcobject(v)) +X x = call_function(v, w); +X else +X x = call_builtin(v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case SLICE+0: +X case SLICE+1: +X case SLICE+2: +X case SLICE+3: +X if ((opcode-SLICE) & 2) +X w = POP(); +X else +X w = NULL; +X if ((opcode-SLICE) & 1) +X v = POP(); +X else +X v = NULL; +X u = POP(); +X x = apply_slice(u, v, w); +X DECREF(u); +X XDECREF(v); +X XDECREF(w); +X PUSH(x); +X break; +X +X case STORE_SLICE+0: +X case STORE_SLICE+1: +X case STORE_SLICE+2: +X case STORE_SLICE+3: +X if ((opcode-STORE_SLICE) & 2) +X w = POP(); +X else +X w = NULL; +X if ((opcode-STORE_SLICE) & 1) +X v = POP(); +X else +X v = NULL; +X u = POP(); +X t = POP(); +X err = assign_slice(u, v, w, t); /* u[v:w] = t */ +X DECREF(t); +X DECREF(u); +X XDECREF(v); +X XDECREF(w); +X break; +X +X case DELETE_SLICE+0: +X case DELETE_SLICE+1: +X case DELETE_SLICE+2: +X case DELETE_SLICE+3: +X if ((opcode-DELETE_SLICE) & 2) +X w = POP(); +X else +X w = NULL; +X if ((opcode-DELETE_SLICE) & 1) +X v = POP(); +X else +X v = NULL; +X u = POP(); +X err = assign_slice(u, v, w, (object *)NULL); +X /* del u[v:w] */ +X DECREF(u); +X XDECREF(v); +X XDECREF(w); +X break; +X +X case STORE_SUBSCR: +X w = POP(); +X v = POP(); +X u = POP(); +X /* v[w] = u */ +X err = assign_subscript(v, w, u); +X DECREF(u); +X DECREF(v); +X DECREF(w); +X break; +X +X case DELETE_SUBSCR: +X w = POP(); +X v = POP(); +X /* del v[w] */ +X err = assign_subscript(v, w, (object *)NULL); +X DECREF(v); +X DECREF(w); +X break; +X +X case PRINT_EXPR: +X v = POP(); +X fp = sysgetfile("stdout", stdout); +X /* Print value except if procedure result */ +X if (v != None) { +X flushline(); +X printobject(v, fp, 0); +X fprintf(fp, "\n"); +X } +X DECREF(v); +X break; +X +X case PRINT_ITEM: +X v = POP(); +X fp = sysgetfile("stdout", stdout); +X if (needspace) +X fprintf(fp, " "); +X if (is_stringobject(v)) { +X char *s = getstringvalue(v); +X int len = getstringsize(v); +X fwrite(s, 1, len, fp); +X if (len > 0 && s[len-1] == '\n') +X needspace = 0; +X else +X needspace = 1; +X } +X else { +X printobject(v, fp, 0); +X needspace = 1; +X } +X DECREF(v); +X break; +X +X case PRINT_NEWLINE: +X fp = sysgetfile("stdout", stdout); +X fprintf(fp, "\n"); +X needspace = 0; +X break; +X +X case BREAK_LOOP: +X why = WHY_BREAK; +X break; +X +X case RAISE_EXCEPTION: +X v = POP(); +X w = POP(); +X if (!is_stringobject(w)) +X err_setstr(TypeError, +X "exceptions must be strings"); +X else +X err_setval(w, v); +X DECREF(v); +X DECREF(w); +X why = WHY_EXCEPTION; +X break; +X +X case LOAD_LOCALS: +X v = f->f_locals; +X INCREF(v); +X PUSH(v); +X break; +X +X case RETURN_VALUE: +X retval = POP(); +X why = WHY_RETURN; +X break; +X +X case REQUIRE_ARGS: +X if (EMPTY()) { +X err_setstr(TypeError, +X "function expects argument(s)"); +X why = WHY_EXCEPTION; +X } +X break; +X +X case REFUSE_ARGS: +X if (!EMPTY()) { +X err_setstr(TypeError, +X "function expects no argument(s)"); +X why = WHY_EXCEPTION; +X } +X break; +X +X case BUILD_FUNCTION: +X v = POP(); +X x = newfuncobject(v, f->f_globals); +X DECREF(v); +X PUSH(x); +X break; +X +X case POP_BLOCK: +X { +X block *b = pop_block(f); +X while (STACK_LEVEL() > b->b_level) { +X v = POP(); +X DECREF(v); +X } +X } +X break; +X +X case END_FINALLY: +X v = POP(); +X if (is_intobject(v)) { +X why = (enum why_code) getintvalue(v); +X if (why == WHY_RETURN) +X retval = POP(); +X } +X else if (is_stringobject(v)) { +X w = POP(); +X err_setval(v, w); +X DECREF(w); +X w = POP(); +X tb_store(w); +X DECREF(w); +X why = WHY_RERAISE; +X } +X else if (v != None) { +X err_setstr(SystemError, +X "'finally' pops bad exception"); +X why = WHY_EXCEPTION; +X } +X DECREF(v); +X break; +X +X case BUILD_CLASS: +X w = POP(); +X v = POP(); +X x = build_class(v, w); +X PUSH(x); +X DECREF(v); +X DECREF(w); +X break; +X +X case STORE_NAME: +X name = GETNAME(oparg); +X v = POP(); +X err = dictinsert(f->f_locals, name, v); +X DECREF(v); +X break; +X +X case DELETE_NAME: +X name = GETNAME(oparg); +X if ((err = dictremove(f->f_locals, name)) != 0) +X err_setstr(NameError, name); +X break; +X +X case UNPACK_TUPLE: +X v = POP(); +X if (!is_tupleobject(v)) { +X err_setstr(TypeError, "unpack non-tuple"); +X why = WHY_EXCEPTION; +X } +X else if (gettuplesize(v) != oparg) { +X err_setstr(RuntimeError, +X "unpack tuple of wrong size"); +X why = WHY_EXCEPTION; +X } +X else { +X for (; --oparg >= 0; ) { +X w = gettupleitem(v, oparg); +X INCREF(w); +X PUSH(w); +X } +X } +X DECREF(v); +X break; +X +X case UNPACK_LIST: +X v = POP(); +X if (!is_listobject(v)) { +X err_setstr(TypeError, "unpack non-list"); +X why = WHY_EXCEPTION; +X } +X else if (getlistsize(v) != oparg) { +X err_setstr(RuntimeError, +X "unpack list of wrong size"); +X why = WHY_EXCEPTION; +X } +X else { +X for (; --oparg >= 0; ) { +X w = getlistitem(v, oparg); +X INCREF(w); +X PUSH(w); +X } +X } +X DECREF(v); +X break; +X +X case STORE_ATTR: +X name = GETNAME(oparg); +X v = POP(); +X u = POP(); +X err = setattr(v, name, u); /* v.name = u */ +X DECREF(v); +X DECREF(u); +X break; +X +X case DELETE_ATTR: +X name = GETNAME(oparg); +X v = POP(); +X err = setattr(v, name, (object *)NULL); +X /* del v.name */ +X DECREF(v); +X break; +X +X case LOAD_CONST: +X x = GETCONST(oparg); +X INCREF(x); +X PUSH(x); +X break; +X +X case LOAD_NAME: +X name = GETNAME(oparg); +X x = dictlookup(f->f_locals, name); +X if (x == NULL) { +X x = dictlookup(f->f_globals, name); +X if (x == NULL) +X x = getbuiltin(name); +X } +X if (x == NULL) +X err_setstr(NameError, name); +X else +X INCREF(x); +X PUSH(x); +X break; +X +X case BUILD_TUPLE: +X x = newtupleobject(oparg); +X if (x != NULL) { +X for (; --oparg >= 0;) { +X w = POP(); +X err = settupleitem(x, oparg, w); +X if (err != 0) +X break; +X } +X PUSH(x); +X } +X break; +X +X case BUILD_LIST: +X x = newlistobject(oparg); +X if (x != NULL) { +X for (; --oparg >= 0;) { +X w = POP(); +X err = setlistitem(x, oparg, w); +X if (err != 0) +X break; +X } +X PUSH(x); +X } +X break; +X +X case BUILD_MAP: +X x = newdictobject(); +X PUSH(x); +X break; +X +X case LOAD_ATTR: +X name = GETNAME(oparg); +X v = POP(); +X x = getattr(v, name); +X DECREF(v); +X PUSH(x); +X break; +X +X case COMPARE_OP: +X w = POP(); +X v = POP(); +X x = cmp_outcome((enum cmp_op)oparg, v, w); +X DECREF(v); +X DECREF(w); +X PUSH(x); +X break; +X +X case IMPORT_NAME: +X name = GETNAME(oparg); +X x = import_module(name); +X XINCREF(x); +X PUSH(x); +X break; +X +X case IMPORT_FROM: +X name = GETNAME(oparg); +X v = TOP(); +X err = import_from(f->f_locals, v, name); +X break; +X +X case JUMP_FORWARD: +X JUMPBY(oparg); +X break; +X +X case JUMP_IF_FALSE: +X if (!testbool(TOP())) +X JUMPBY(oparg); +X break; +X +X case JUMP_IF_TRUE: +X if (testbool(TOP())) +X JUMPBY(oparg); +X break; +X +X case JUMP_ABSOLUTE: +X JUMPTO(oparg); +X break; +X +X case FOR_LOOP: +X /* for v in s: ... +X On entry: stack contains s, i. +X On exit: stack contains s, i+1, s[i]; +X but if loop exhausted: +X s, i are popped, and we jump */ +X w = POP(); /* Loop index */ +X v = POP(); /* Sequence object */ +X u = loop_subscript(v, w); +X if (u != NULL) { +X PUSH(v); +X x = newintobject(getintvalue(w)+1); +X PUSH(x); +X DECREF(w); +X PUSH(u); +X } +X else { +X DECREF(v); +X DECREF(w); +X /* A NULL can mean "s exhausted" +X but also an error: */ +X if (err_occurred()) +X why = WHY_EXCEPTION; +X else +X JUMPBY(oparg); +X } +X break; +X +X case SETUP_LOOP: +X case SETUP_EXCEPT: +X case SETUP_FINALLY: +X setup_block(f, opcode, INSTR_OFFSET() + oparg, +X STACK_LEVEL()); +X break; +X +X case SET_LINENO: X#ifdef TRACE -X if (trace) -X printf("--- Line %d ---\n", oparg); +X if (trace) +X printf("--- Line %d ---\n", oparg); X#endif -X lineno = oparg; -X break; -X -X default: -X fprintf(stderr, -X "XXX lineno: %d, opcode: %d\n", -X lineno, opcode); -X err_setstr(SystemError, "eval_code: unknown opcode"); -X why = WHY_EXCEPTION; -X break; -X -X } /* switch */ -X -X -X /* Quickly continue if no error occurred */ -X -X if (why == WHY_NOT) { -X if (err == 0 && x != NULL) -X continue; /* Normal, fast path */ -X why = WHY_EXCEPTION; -X x = None; -X err = 0; -X } +X lineno = oparg; +X break; +X +X default: +X fprintf(stderr, +X "XXX lineno: %d, opcode: %d\n", +X lineno, opcode); +X err_setstr(SystemError, "eval_code: unknown opcode"); +X why = WHY_EXCEPTION; +X break; +X +X } /* switch */ +X +X +X /* Quickly continue if no error occurred */ +X +X if (why == WHY_NOT) { +X if (err == 0 && x != NULL) +X continue; /* Normal, fast path */ +X why = WHY_EXCEPTION; +X x = None; +X err = 0; +X } X X#ifndef NDEBUG -X /* Double-check exception status */ -X -X if (why == WHY_EXCEPTION || why == WHY_RERAISE) { -X if (!err_occurred()) { -X fprintf(stderr, "XXX ghost error\n"); -X err_setstr(SystemError, "ghost error"); -X why = WHY_EXCEPTION; -X } -X } -X else { -X if (err_occurred()) { -X fprintf(stderr, "XXX undetected error\n"); -X why = WHY_EXCEPTION; -X } -X } +X /* Double-check exception status */ +X +X if (why == WHY_EXCEPTION || why == WHY_RERAISE) { +X if (!err_occurred()) { +X fprintf(stderr, "XXX ghost error\n"); +X err_setstr(SystemError, "ghost error"); +X why = WHY_EXCEPTION; +X } +X } +X else { +X if (err_occurred()) { +X fprintf(stderr, "XXX undetected error\n"); +X why = WHY_EXCEPTION; +X } +X } X#endif X -X /* Log traceback info if this is a real exception */ -X -X if (why == WHY_EXCEPTION) { -X int lasti = INSTR_OFFSET() - 1; -X if (HAS_ARG(opcode)) -X lasti -= 2; -X tb_here(f, lasti, lineno); -X } -X -X /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ -X -X if (why == WHY_RERAISE) -X why = WHY_EXCEPTION; -X -X /* Unwind stacks if a (pseudo) exception occurred */ -X -X while (why != WHY_NOT && f->f_iblock > 0) { -X block *b = pop_block(f); -X while (STACK_LEVEL() > b->b_level) { -X v = POP(); -X XDECREF(v); -X } -X if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { -X why = WHY_NOT; -X JUMPTO(b->b_handler); -X break; -X } -X if (b->b_type == SETUP_FINALLY || -X b->b_type == SETUP_EXCEPT && -X why == WHY_EXCEPTION) { -X if (why == WHY_EXCEPTION) { -X object *exc, *val; -X err_get(&exc, &val); -X if (val == NULL) { -X val = None; -X INCREF(val); -X } -X v = tb_fetch(); -X /* Make the raw exception data -X available to the handler, -X so a program can emulate the -X Python main loop. Don't do -X this for 'finally'. */ -X if (b->b_type == SETUP_EXCEPT) { +X /* Log traceback info if this is a real exception */ +X +X if (why == WHY_EXCEPTION) { +X int lasti = INSTR_OFFSET() - 1; +X if (HAS_ARG(opcode)) +X lasti -= 2; +X tb_here(f, lasti, lineno); +X } +X +X /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ +X +X if (why == WHY_RERAISE) +X why = WHY_EXCEPTION; +X +X /* Unwind stacks if a (pseudo) exception occurred */ +X +X while (why != WHY_NOT && f->f_iblock > 0) { +X block *b = pop_block(f); +X while (STACK_LEVEL() > b->b_level) { +X v = POP(); +X XDECREF(v); +X } +X if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { +X why = WHY_NOT; +X JUMPTO(b->b_handler); +X break; +X } +X if (b->b_type == SETUP_FINALLY || +X b->b_type == SETUP_EXCEPT && +X why == WHY_EXCEPTION) { +X if (why == WHY_EXCEPTION) { +X object *exc, *val; +X err_get(&exc, &val); +X if (val == NULL) { +X val = None; +X INCREF(val); +X } +X v = tb_fetch(); +X /* Make the raw exception data +X available to the handler, +X so a program can emulate the +X Python main loop. Don't do +X this for 'finally'. */ +X if (b->b_type == SETUP_EXCEPT) { X#if 0 /* Oops, this breaks too many things */ -X sysset("exc_traceback", v); +X sysset("exc_traceback", v); X#endif -X sysset("exc_value", val); -X sysset("exc_type", exc); -X err_clear(); -X } -X PUSH(v); -X PUSH(val); -X PUSH(exc); -X } -X else { -X if (why == WHY_RETURN) -X PUSH(retval); -X v = newintobject((long)why); -X PUSH(v); -X } -X why = WHY_NOT; -X JUMPTO(b->b_handler); -X break; -X } -X } /* unwind stack */ -X -X /* End the loop if we still have an error (or return) */ -X -X if (why != WHY_NOT) -X break; -X -X } /* main loop */ -X -X /* Pop remaining stack entries */ -X -X while (!EMPTY()) { -X v = POP(); -X XDECREF(v); -X } -X -X /* Restore previous frame and release the current one */ -X -X current_frame = f->f_back; -X DECREF(f); -X -X if (why == WHY_RETURN) -X return retval; -X else -X return NULL; +X sysset("exc_value", val); +X sysset("exc_type", exc); +X err_clear(); +X } +X PUSH(v); +X PUSH(val); +X PUSH(exc); +X } +X else { +X if (why == WHY_RETURN) +X PUSH(retval); +X v = newintobject((long)why); +X PUSH(v); +X } +X why = WHY_NOT; +X JUMPTO(b->b_handler); +X break; +X } +X } /* unwind stack */ +X +X /* End the loop if we still have an error (or return) */ +X +X if (why != WHY_NOT) +X break; +X +X } /* main loop */ +X +X /* Pop remaining stack entries */ +X +X while (!EMPTY()) { +X v = POP(); +X XDECREF(v); +X } +X +X /* Restore previous frame and release the current one */ +X +X current_frame = f->f_back; +X DECREF(f); +X +X if (why == WHY_RETURN) +X return retval; +X else +X return NULL; X} EOF fi @@ -2192,12 +2192,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2218,10 +2218,10 @@ X X/* X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 X -XObjects are structures allocated on the heap. Special rules apply to +XObjects are structures allocated on the heap. Special rules apply to Xthe use of objects to ensure they are properly garbage-collected. XObjects are never allocated statically or on the stack; they must be -Xaccessed through special macros and functions only. (Type objects are +Xaccessed through special macros and functions only. (Type objects are Xexceptions to the first rule; the standard types are represented by Xstatically initialized type objects.) X @@ -2231,28 +2231,28 @@ Xreaches zero there are no references to the object left and it can be Xremoved from the heap. X XAn object has a 'type' that determines what it represents and what kind -Xof data it contains. An object's type is fixed when it is created. +Xof data it contains. An object's type is fixed when it is created. XTypes themselves are represented as objects; an object contains a -Xpointer to the corresponding type object. The type itself has a type +Xpointer to the corresponding type object. The type itself has a type Xpointer pointing to the object representing the type 'type', which Xcontains a pointer to itself!). X XObjects do not float around in memory; once allocated an object keeps -Xthe same size and address. Objects that must hold variable-size data -Xcan contain pointers to variable-size parts of the object. Not all +Xthe same size and address. Objects that must hold variable-size data +Xcan contain pointers to variable-size parts of the object. Not all Xobjects of the same type have the same size; but the size cannot change -Xafter allocation. (These restrictions are made so a reference to an +Xafter allocation. (These restrictions are made so a reference to an Xobject can be simply a pointer -- moving an object would require Xupdating all the pointers, and changing an object's size would require Xmoving it if there was another object right next to it.) X XObjects are always accessed through pointers of the type 'object *'. XThe type 'object' is a structure that only contains the reference count -Xand the type pointer. The actual memory allocated for an object +Xand the type pointer. The actual memory allocated for an object Xcontains other data that can only be accessed after casting the pointer -Xto a pointer to a longer structure type. This longer type must start +Xto a pointer to a longer structure type. This longer type must start Xwith the reference count and type fields; the macro OB_HEAD should be -Xused for this (to accomodate for future changes). The implementation +Xused for this (to accomodate for future changes). The implementation Xof a particular object type can cast the object pointer to the proper Xtype and back. X @@ -2274,27 +2274,27 @@ X#endif /* NDEBUG */ X X#ifdef TRACE_REFS X#define OB_HEAD \ -X struct _object *_ob_next, *_ob_prev; \ -X int ob_refcnt; \ -X struct _typeobject *ob_type; +X struct _object *_ob_next, *_ob_prev; \ +X int ob_refcnt; \ +X struct _typeobject *ob_type; X#define OB_HEAD_INIT(type) 0, 0, 1, type, X#else X#define OB_HEAD \ -X unsigned int ob_refcnt; \ -X struct _typeobject *ob_type; +X unsigned int ob_refcnt; \ +X struct _typeobject *ob_type; X#define OB_HEAD_INIT(type) 1, type, X#endif X X#define OB_VARHEAD \ -X OB_HEAD \ -X unsigned int ob_size; /* Number of items in variable part */ -X +X OB_HEAD \ +X unsigned int ob_size; /* Number of items in variable part */ +X Xtypedef struct _object { -X OB_HEAD +X OB_HEAD X} object; X Xtypedef struct { -X OB_VARHEAD +X OB_VARHEAD X} varobject; X X @@ -2303,9 +2303,9 @@ X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 X XType objects contain a string containing the type name (to help somewhat Xin debugging), the allocation parameters (see newobj() and newvarobj()), -Xand methods for accessing objects of the type. Methods are optional,a +Xand methods for accessing objects of the type. Methods are optional,a Xnil pointer meaning that particular kind of access is not available for -Xthis type. The DECREF() macro uses the tp_dealloc method without +Xthis type. The DECREF() macro uses the tp_dealloc method without Xchecking for a nil pointer; it should always be implemented except if Xthe implementation can guarantee that the reference count will never Xreach zero (e.g., for type objects). @@ -2315,51 +2315,51 @@ Xmethod blocks. X*/ X Xtypedef struct { -X object *(*nb_add) FPROTO((object *, object *)); -X object *(*nb_subtract) FPROTO((object *, object *)); -X object *(*nb_multiply) FPROTO((object *, object *)); -X object *(*nb_divide) FPROTO((object *, object *)); -X object *(*nb_remainder) FPROTO((object *, object *)); -X object *(*nb_power) FPROTO((object *, object *)); -X object *(*nb_negative) FPROTO((object *)); -X object *(*nb_positive) FPROTO((object *)); +X object *(*nb_add) FPROTO((object *, object *)); +X object *(*nb_subtract) FPROTO((object *, object *)); +X object *(*nb_multiply) FPROTO((object *, object *)); +X object *(*nb_divide) FPROTO((object *, object *)); +X object *(*nb_remainder) FPROTO((object *, object *)); +X object *(*nb_power) FPROTO((object *, object *)); +X object *(*nb_negative) FPROTO((object *)); +X object *(*nb_positive) FPROTO((object *)); X} number_methods; X Xtypedef struct { -X int (*sq_length) FPROTO((object *)); -X object *(*sq_concat) FPROTO((object *, object *)); -X object *(*sq_repeat) FPROTO((object *, int)); -X object *(*sq_item) FPROTO((object *, int)); -X object *(*sq_slice) FPROTO((object *, int, int)); -X int (*sq_ass_item) FPROTO((object *, int, object *)); -X int (*sq_ass_slice) FPROTO((object *, int, int, object *)); +X int (*sq_length) FPROTO((object *)); +X object *(*sq_concat) FPROTO((object *, object *)); +X object *(*sq_repeat) FPROTO((object *, int)); +X object *(*sq_item) FPROTO((object *, int)); +X object *(*sq_slice) FPROTO((object *, int, int)); +X int (*sq_ass_item) FPROTO((object *, int, object *)); +X int (*sq_ass_slice) FPROTO((object *, int, int, object *)); X} sequence_methods; X Xtypedef struct { -X int (*mp_length) FPROTO((object *)); -X object *(*mp_subscript) FPROTO((object *, object *)); -X int (*mp_ass_subscript) FPROTO((object *, object *, object *)); +X int (*mp_length) FPROTO((object *)); +X object *(*mp_subscript) FPROTO((object *, object *)); +X int (*mp_ass_subscript) FPROTO((object *, object *, object *)); X} mapping_methods; X Xtypedef struct _typeobject { -X OB_VARHEAD -X char *tp_name; /* For printing */ -X unsigned int tp_basicsize, tp_itemsize; /* For allocation */ -X -X /* Methods to implement standard operations */ -X -X void (*tp_dealloc) FPROTO((object *)); -X void (*tp_print) FPROTO((object *, FILE *, int)); -X object *(*tp_getattr) FPROTO((object *, char *)); -X int (*tp_setattr) FPROTO((object *, char *, object *)); -X int (*tp_compare) FPROTO((object *, object *)); -X object *(*tp_repr) FPROTO((object *)); -X -X /* Method suites for standard classes */ -X -X number_methods *tp_as_number; -X sequence_methods *tp_as_sequence; -X mapping_methods *tp_as_mapping; +X OB_VARHEAD +X char *tp_name; /* For printing */ +X unsigned int tp_basicsize, tp_itemsize; /* For allocation */ +X +X /* Methods to implement standard operations */ +X +X void (*tp_dealloc) FPROTO((object *)); +X void (*tp_print) FPROTO((object *, FILE *, int)); +X object *(*tp_getattr) FPROTO((object *, char *)); +X int (*tp_setattr) FPROTO((object *, char *, object *)); +X int (*tp_compare) FPROTO((object *, object *)); +X object *(*tp_repr) FPROTO((object *)); +X +X /* Method suites for standard classes */ +X +X number_methods *tp_as_number; +X sequence_methods *tp_as_sequence; +X mapping_methods *tp_as_mapping; X} typeobject; X Xextern typeobject Typetype; /* The type of type objects */ @@ -2374,32 +2374,32 @@ Xextern object *getattr PROTO((object *, char *)); Xextern int setattr PROTO((object *, char *, object *)); X X/* Flag bits for printing: */ -X#define PRINT_RAW 1 /* No string quotes etc. */ +X#define PRINT_RAW 1 /* No string quotes etc. */ X X/* X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 X XThe macros INCREF(op) and DECREF(op) are used to increment or decrement -Xreference counts. DECREF calls the object's deallocator function; for +Xreference counts. DECREF calls the object's deallocator function; for Xobjects that don't contain references to other objects or heap memory -Xthis can be the standard function free(). Both macros can be used -Xwhereever a void expression is allowed. The argument shouldn't be a -XNIL pointer. The macro NEWREF(op) is used only to initialize reference +Xthis can be the standard function free(). Both macros can be used +Xwhereever a void expression is allowed. The argument shouldn't be a +XNIL pointer. The macro NEWREF(op) is used only to initialize reference Xcounts to 1; it is defined here for convenience. X XWe assume that the reference count field can never overflow; this can Xbe proven when the size of the field is the same as the pointer size Xbut even with a 16-bit reference count field it is pretty unlikely so -Xwe ignore the possibility. (If you are paranoid, make it a long.) +Xwe ignore the possibility. (If you are paranoid, make it a long.) X XType objects should never be deallocated; the type pointer in an object Xis not considered to be a reference to the type object, to save -Xcomplications in the deallocation function. (This is actually a +Xcomplications in the deallocation function. (This is actually a Xdecision that's up to the implementer of each new type so if you want, Xyou can count such references to the type object.) X X*** WARNING*** The DECREF macro must have a side-effect-free argument -Xsince it may evaluate its argument multiple times. (The alternative +Xsince it may evaluate its argument multiple times. (The alternative Xwould be to mace it a proper function or assign it to a global temporary Xvariable first, both of which are slower; and in a multi-threaded Xenvironment the global variable trick is not safe.) @@ -2423,18 +2423,18 @@ X#define NEWREF(op) (ref_total++, (op)->ob_refcnt = 1) X#endif X#define INCREF(op) (ref_total++, (op)->ob_refcnt++) X#define DECREF(op) \ -X if (--ref_total, --(op)->ob_refcnt > 0) \ -X ; \ -X else \ -X DELREF(op) +X if (--ref_total, --(op)->ob_refcnt > 0) \ +X ; \ +X else \ +X DELREF(op) X#else X#define NEWREF(op) ((op)->ob_refcnt = 1) X#define INCREF(op) ((op)->ob_refcnt++) X#define DECREF(op) \ -X if (--(op)->ob_refcnt > 0) \ -X ; \ -X else \ -X DELREF(op) +X if (--(op)->ob_refcnt > 0) \ +X ; \ +X else \ +X DELREF(op) X#endif X X/* Macros to use in case the object pointer may be NULL: */ @@ -2478,7 +2478,7 @@ XFailure Modes X------------- X XFunctions may fail for a variety of reasons, including running out of -Xmemory. This is communicated to the caller in two ways: an error string +Xmemory. This is communicated to the caller in two ways: an error string Xis set (see errors.h), and the function result differs: functions that Xnormally return a pointer return NULL for failure, functions returning Xan integer return -1 (which could be a legal return value too!), and @@ -2494,10 +2494,10 @@ XFunctions that create an object set the reference count to 1; such new Xobjects must be stored somewhere or destroyed again with DECREF(). XFunctions that 'store' objects such as settupleitem() and dictinsert() Xdon't increment the reference count of the object, since the most -Xfrequent use is to store a fresh object. Functions that 'retrieve' +Xfrequent use is to store a fresh object. Functions that 'retrieve' Xobjects such as gettupleitem() and dictlookup() also don't increment Xthe reference count, since most frequently the object is only looked at -Xquickly. Thus, to retrieve an object and store it again, the caller +Xquickly. Thus, to retrieve an object and store it again, the caller Xmust call INCREF() explicitly. X XNOTE: functions that 'consume' a reference count like dictinsert() even @@ -2506,7 +2506,7 @@ Xhandling. X XIt seems attractive to make other functions that take an object as Xargument consume a reference count; however this may quickly get -Xconfusing (even the current practice is already confusing). Consider +Xconfusing (even the current practice is already confusing). Consider Xit carefully, it may safe lots of calls to INCREF() and DECREF() at Xtimes. X @@ -2515,4 +2515,4 @@ X*/ EOF fi echo 'Part 07 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-08-21.shar b/shar/python-0.9.1-08-21.shar index 7ac6f14..d885f95 100644 --- a/shar/python-0.9.1-08-21.shar +++ b/shar/python-0.9.1-08-21.shar @@ -111,15 +111,15 @@ X{\tt len}({\em s}) & length of {\em s} & \\ X{\tt min}({\em s}) & smallest item of {\em s} & \\ X{\tt max}({\em s}) & largest item of {\em s} & \\ X{\em x} {\tt in} {\em s} & -X true if an item of {\em s} is equal to {\em x} & \\ +X true if an item of {\em s} is equal to {\em x} & \\ X{\em x} {\tt not} {\tt in} {\em s} & -X false if an item of {\em s} is equal to {\em x} & \\ +X false if an item of {\em s} is equal to {\em x} & \\ X{\em s}{\tt +}{\em t} & the concatenation of {\em s} and {\em t} & \\ X{\em s}{\tt *}{\em n}, {\em n}*{\em s} & -X {\em n} copies of {\em s} concatenated & (1) \\ +X {\em n} copies of {\em s} concatenated & (1) \\ X{\em s}[{\em i}] & {\em i}'th item of {\em s} & \\ X{\em s}[{\em i}:{\em j}] & -X slice of {\em s} from {\em i} to {\em j} & (2) \\ +X slice of {\em s} from {\em i} to {\em j} & (2) \\ X\hline X\end{tabular} X\end{center} @@ -153,19 +153,19 @@ X\hline XOperation & Result \\ X\hline X{\em s}[{\em i}] = {\em x} & -X item {\em i} of {\em s} is replaced by {\em x} \\ +X item {\em i} of {\em s} is replaced by {\em x} \\ X{\em s}[{\em i}:{\em j}] = {\em t} & -X slice of {\em s} from {\em i} to {\em j} is replaced by {\em t} \\ +X slice of {\em s} from {\em i} to {\em j} is replaced by {\em t} \\ X{\tt del} {\em s}[{\em i}:{\em j}] & -X same as {\em s}[{\em i}:{\em j}] = [] \\ +X same as {\em s}[{\em i}:{\em j}] = [] \\ X{\em s}.{\tt append}({\em x}) & -X same as {\em s}[{\tt len}({\em x}):{\tt len}({\em x})] = [{\em x}] \\ +X same as {\em s}[{\tt len}({\em x}):{\tt len}({\em x})] = [{\em x}] \\ X{\em s}.{\tt insert}({\em i}, {\em x}) & -X same as {\em s}[{\em i}:{\em i}] = [{\em x}] \\ +X same as {\em s}[{\em i}:{\em i}] = [{\em x}] \\ X{\em s}.{\tt sort}() & -X the items of {\em s} are permuted to satisfy \\ -X & -X $s[i] \leq s[j]$ for $i < j$\\ +X the items of {\em s} are permuted to satisfy \\ +X & +X $s[i] \leq s[j]$ for $i < j$\\ X\hline X\end{tabular} X\end{center} @@ -226,7 +226,7 @@ X>>> tel.keys() X['guido', 'irv', 'jack'] X>>> tel.has_key('guido') X1 -X>>> +X>>> X\end{verbatim}\ecode X\subsubsection{Other Built-in Types} X @@ -382,7 +382,7 @@ X>>> dir() X['sys'] X>>> dir(sys) X['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout'] -X>>> +X>>> X\end{verbatim}\ecode X\funcitem{divmod}{a, b} X%.br @@ -408,7 +408,7 @@ X>>> divmod(100, -7) X(-15, -5) X>>> divmod(-100, -7) X(14, -2) -X>>> +X>>> X\end{verbatim}\ecode X\funcitem{eval}{s} XTakes a string as argument and parses and evaluates it as a {\Python} @@ -421,7 +421,7 @@ X\bcode\begin{verbatim} X>>> x = 1 X>>> eval('x+1') X2 -X>>> +X>>> X\end{verbatim}\ecode X\funcitem{exec}{s} XTakes a string as argument and parses and evaluates it as a sequence of @@ -436,7 +436,7 @@ X>>> x = 1 X>>> exec('x = x+1\n') X>>> x X2 -X>>> +X>>> X\end{verbatim}\ecode X\funcitem{float}{x} XConverts a number to floating point. @@ -504,7 +504,7 @@ X>>> range(0) X[] X>>> range(1, 0) X[] -X>>> +X>>> X\end{verbatim}\ecode X\funcitem{raw\_input}{s} X%.br @@ -518,7 +518,7 @@ X\bcode\begin{verbatim} X>>> raw_input('Type anything: ') XType anything: Mutant Teenage Ninja Turtles X'Mutant Teenage Ninja Turtles' -X>>> +X>>> X\end{verbatim}\ecode X\funcitem{reload}{module} XCauses an already imported module to be re-parsed and re-initialized. @@ -539,17 +539,17 @@ sed 's/^X//' > 'src/Makefile' << 'EOF' X# /*********************************************************** X# Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The X# Netherlands. -X# -X# All Rights Reserved -X# -X# Permission to use, copy, modify, and distribute this software and its -X# documentation for any purpose and without fee is hereby granted, +X# +X# All Rights Reserved +X# +X# Permission to use, copy, modify, and distribute this software and its +X# documentation for any purpose and without fee is hereby granted, X# provided that the above copyright notice appear in all copies and that -X# both that copyright notice and this permission notice appear in +X# both that copyright notice and this permission notice appear in X# supporting documentation, and that the names of Stichting Mathematisch X# Centrum or CWI not be used in advertising or publicity pertaining to X# distribution of the software without specific, written prior permission. -X# +X# X# STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO X# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND X# FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE @@ -557,7 +557,7 @@ X# FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES X# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN X# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT X# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -X# +X# X# ******************************************************************/ X X# Makefile for Python @@ -565,17 +565,17 @@ X# =================== X# X# If you are in a hurry, you can just edit this Makefile to choose the X# correct settings for SYSV and RANLIB below, and type "make" in this -X# directory. If you are using a recent version of SunOS (or Ultrix?) +X# directory. If you are using a recent version of SunOS (or Ultrix?) X# you don't even have to edit: the Makefile comes pre-configured for X# such systems with all configurable options turned off, building the X# minimal portable version of the Python interpreter. X# X# If have more time, read the section on configurable options below. X# It may still be wise to begin building the minimal portable Python, -X# to see if it works at all, and select options later. You don't have +X# to see if it works at all, and select options later. You don't have X# to rebuild all objects when you turn on options; all dependencies X# are concentrated in the file "config.c" which is rebuilt whenever -X# the Makefile changes. (Except if you turn on the GNU Readline option +X# the Makefile changes. (Except if you turn on the GNU Readline option X# you may have to toss out the tokenizer.o object.) X X @@ -583,21 +583,21 @@ X# Operating System Defines (ALWAYS READ THIS) X# =========================================== X X# Uncomment the following line if you are using a System V derivative. -X# This must be used, for instance, on an SGI IRIS. Don't use it for -X# SunOS. (This is only needed by posixmodule.c...) +X# This must be used, for instance, on an SGI IRIS. Don't use it for +X# SunOS. (This is only needed by posixmodule.c...) X -X#SYSVDEF= -DSYSV +X#SYSVDEF= -DSYSV X X# Choose one of the following two lines depending on whether your system X# requires the use of 'ranlib' after creating a library, or not. X -X#RANLIB = true # For System V -XRANLIB = ranlib # For BSD +X#RANLIB = true # For System V +XRANLIB = ranlib # For BSD X X# If your system doesn't have symbolic links, uncomment the following X# line. X -X#NOSYMLINKDEF= -DNO_LSTAT +X#NOSYMLINKDEF= -DNO_LSTAT X X X# Installation Options @@ -606,49 +606,49 @@ X X# You may want to change PYTHONPATH to reflect where you install the X# Python module library. X -XPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python +XPYTHONPATH= .:/usr/local/lib/python:/ufs/guido/lib/python X X X# For "Pure" BSD Systems X# ====================== X# X# "Pure" BSD systems (as opposed to enhanced BSD derivatives like SunOS) -X# often miss certain standard library functions. Source for -X# these is provided, you just have to turn it on. This may work for +X# often miss certain standard library functions. Source for +X# these is provided, you just have to turn it on. This may work for X# other systems as well, where these things are needed. X X# If your system does not have a strerror() function in the library, -X# uncomment the following two lines to use one I wrote. (Actually, this +X# uncomment the following two lines to use one I wrote. (Actually, this X# is missing in most systems I have encountered, so it is turned on -X# in the Makefile. Turn it off if your system doesn't have sys_errlist.) +X# in the Makefile. Turn it off if your system doesn't have sys_errlist.) X -XSTRERROR_SRC= strerror.c -XSTRERROR_OBJ= strerror.o +XSTRERROR_SRC= strerror.c +XSTRERROR_OBJ= strerror.o X X# If your BSD system does not have a fmod() function in the library, X# uncomment the following two lines to use one I wrote. X -X#FMOD_SRC= fmod.c -X#FMOD_OBJ= fmod.o +X#FMOD_SRC= fmod.c +X#FMOD_OBJ= fmod.o X X# If your BSD system does not have a strtol() function in the library, X# uncomment the following two lines to use one I wrote. X -X#STRTOL_SRC= strtol.c -X#STRTOL_OBJ= strtol.o +X#STRTOL_SRC= strtol.c +X#STRTOL_OBJ= strtol.o X X# If your BSD system does not have a getcwd() function in the library, X# but it does have a getwd() function, uncomment the following two lines -X# to use one I wrote. (If you don't have getwd() either, turn on the +X# to use one I wrote. (If you don't have getwd() either, turn on the X# NO_GETWD #define in getcwd.c.) X -X#GETCWD_SRC= getcwd.c -X#GETCWD_OBJ= getcwd.o +X#GETCWD_SRC= getcwd.c +X#GETCWD_OBJ= getcwd.o X X# If your signal() function believes signal handlers return int, X# uncomment the following line. X -X#SIGTYPEDEF= -DSIGTYPE=int +X#SIGTYPEDEF= -DSIGTYPE=int X X X# Further porting hints @@ -658,7 +658,7 @@ X# If you don't have the header file <string.h>, but you do have X# <strings.h>, create a file "string.h" in this directory which contains X# the single line "#include <strings.h>", and add "-I." to CFLAGS. X# If you don't have the functions strchr and strrchr, add definitions -X# "-Dstrchr=index -Dstrrchr=rindex" to CFLAGS. (NB: CFLAGS is not +X# "-Dstrchr=index -Dstrrchr=rindex" to CFLAGS. (NB: CFLAGS is not X# defined in this Makefile.) X X @@ -666,14 +666,14 @@ X# Configurable Options X# ==================== X# X# Python can be configured to interface to various system libraries that -X# are not available on all systems. It is also possible to configure +X# are not available on all systems. It is also possible to configure X# the input module to use the GNU Readline library for interactive -X# input. For each configuration choice you must uncomment the relevant -X# section of the Makefile below. Note: you may also have to change a +X# input. For each configuration choice you must uncomment the relevant +X# section of the Makefile below. Note: you may also have to change a X# pathname and/or an architecture identifier that is hardcoded in the X# Makefile. X# -X# Read the comments to determine if you can use the option. (You can +X# Read the comments to determine if you can use the option. (You can X# always leave all options off and build a minimal portable version of X# Python.) X @@ -689,7 +689,7 @@ X# using the BSD system calls select() and gettimeofday(). X# X# Uncomment the following line to select this option. X -X#BSDTIMEDEF= -DBSD_TIME +X#BSDTIMEDEF= -DBSD_TIME X X X# GNU Readline Option @@ -698,7 +698,7 @@ X# X# If you have the sources of the GNU Readline library you can have X# full interactive command line editing and history in Python. X# The GNU Readline library is distributed with the BASH shell -X# (I only know of version 1.05). You must build the GNU Readline +X# (I only know of version 1.05). You must build the GNU Readline X# library and the alloca routine it needs in their own source X# directories (which are subdirectories of the basg source directory), X# and plant a pointer to the BASH source directory in this Makefile. @@ -708,13 +708,13 @@ X# - Edit the definition of BASHDIR to point to the bash source tree. X# You may have to fix the definition of LIBTERMCAP; leave the LIBALLOCA X# definition commented if alloca() is in your C library. X -X#BASHDIR= ../../bash-1.05 -X#LIBREADLINE= $(BASHDIR)/readline/libreadline.a -X#LIBALLOCA= $(BASHDIR)/alloc-files/alloca.o -X#LIBTERMCAP= -ltermcap -X#RL_USE = -DUSE_READLINE -X#RL_LIBS= $(LIBREADLINE) $(LIBALLOCA) $(LIBTERMCAP) -X#RL_LIBDEPS= $(LIBREADLINE) $(LIBALLOCA) +X#BASHDIR= ../../bash-1.05 +X#LIBREADLINE= $(BASHDIR)/readline/libreadline.a +X#LIBALLOCA= $(BASHDIR)/alloc-files/alloca.o +X#LIBTERMCAP= -ltermcap +X#RL_USE = -DUSE_READLINE +X#RL_LIBS= $(LIBREADLINE) $(LIBALLOCA) $(LIBTERMCAP) +X#RL_LIBDEPS= $(LIBREADLINE) $(LIBALLOCA) X X X# STDWIN Option @@ -726,22 +726,22 @@ X# This requires a fairly recent version of STDWIN (dated late 1990). X# X# Uncomment and edit the following block to use the STDWIN option. X# - Edit the STDWINDIR defition to reflect the top of the STDWIN source -X# tree. +X# tree. X# - Edit the ARCH definition to reflect your system's architecture -X# (usually the program 'arch' or 'machine' returns this). +X# (usually the program 'arch' or 'machine' returns this). X# You may have to edit the LIBX11 defition to reflect the location of X# the X11 runtime library if it is non-standard. X -X#STDWINDIR= ../../stdwin -X#ARCH= sgi -X#LIBSTDWIN= $(STDWINDIR)/Build/$(ARCH)/x11/lib/lib.a -X#LIBX11 = -lX11 -X#STDW_INCL= -I$(STDWINDIR)/H -X#STDW_USE= -DUSE_STDWIN -X#STDW_LIBS= $(LIBSTDWIN) $(LIBX11) -X#STDW_LIBDEPS= $(LIBSTDWIN) -X#STDW_SRC= stdwinmodule.c -X#STDW_OBJ= stdwinmodule.o +X#STDWINDIR= ../../stdwin +X#ARCH= sgi +X#LIBSTDWIN= $(STDWINDIR)/Build/$(ARCH)/x11/lib/lib.a +X#LIBX11 = -lX11 +X#STDW_INCL= -I$(STDWINDIR)/H +X#STDW_USE= -DUSE_STDWIN +X#STDW_LIBS= $(LIBSTDWIN) $(LIBX11) +X#STDW_LIBDEPS= $(LIBSTDWIN) +X#STDW_SRC= stdwinmodule.c +X#STDW_OBJ= stdwinmodule.o X X X# Amoeba Option @@ -750,31 +750,31 @@ X# X# If you have the Amoeba 4.0 distribution (Beta or otherwise) you can X# configure Python to incorporate the built-in module 'amoeba'. X# (Python can also be built for native Amoeba, but it requires more -X# work and thought. Contact the author.) +X# work and thought. Contact the author.) X# X# Uncomment and edit the following block to use the Amoeba option. X# - Edit the AMOEBADIR defition to reflect the top of the Amoeba source -X# tree. +X# tree. X# - Edit the AM_CONF definition to reflect the machine/operating system -X# configuration needed by Amoeba (this is the name of a subdirectory -X# of $(AMOEBADIR)/conf/unix, e.g., vax.ultrix). +X# configuration needed by Amoeba (this is the name of a subdirectory +X# of $(AMOEBADIR)/conf/unix, e.g., vax.ultrix). X -X#AMOEBADIR= /usr/amoeba -X#AM_CONF= mipseb.irix -X#LIBAMUNIX= $(AMOEBADIR)/conf/unix/$(AM_CONF)/lib/amunix/libamunix.a -X#AM_INCL= -I$(AMOEBADIR)/src/h -X#AM_USE = -DUSE_AMOEBA -X#AM_LIBDEPS= $(LIBAMUNIX) -X#AM_LIBS= $(LIBAMUNIX) -X#AM_SRC = amoebamodule.c sc_interpr.c sc_errors.c -X#AM_OBJ = amoebamodule.o sc_interpr.o sc_errors.o +X#AMOEBADIR= /usr/amoeba +X#AM_CONF= mipseb.irix +X#LIBAMUNIX= $(AMOEBADIR)/conf/unix/$(AM_CONF)/lib/amunix/libamunix.a +X#AM_INCL= -I$(AMOEBADIR)/src/h +X#AM_USE = -DUSE_AMOEBA +X#AM_LIBDEPS= $(LIBAMUNIX) +X#AM_LIBS= $(LIBAMUNIX) +X#AM_SRC = amoebamodule.c sc_interpr.c sc_errors.c +X#AM_OBJ = amoebamodule.o sc_interpr.o sc_errors.o X X X# Silicon Graphics IRIS Options X# ============================= X# X# The following three options are only relevant if you are using a -X# Silicon Graphics IRIS machine. These have been tested with IRIX 3.3.1 +X# Silicon Graphics IRIS machine. These have been tested with IRIX 3.3.1 X# on a 4D/25. X X @@ -782,22 +782,22 @@ X# GL Option X# ========= X# X# This option incorporates the built-in module 'gl', which provides a -X# complete interface to the Silicon Graphics GL library. It adds +X# complete interface to the Silicon Graphics GL library. It adds X# about 70K to the Python text size and about 260K to the unstripped X# binary size. X# -X# Note: the file 'glmodule.c' is created by a Python script. If you +X# Note: the file 'glmodule.c' is created by a Python script. If you X# lost the file and have no working Python interpreter, turn off the GL X# and Panel options, rebuild the Python interpreter, use it to create X# glmodule.c, and then turn the options back on. X# X# Uncomment the following block to use the GL option. X -X#GL_USE = -DUSE_GL -X#GL_LIBDEPS= -X#GL_LIBS= -lgl_s -X#GL_SRC = glmodule.c cgensupport.c -X#GL_OBJ = glmodule.o cgensupport.o +X#GL_USE = -DUSE_GL +X#GL_LIBDEPS= +X#GL_LIBS= -lgl_s +X#GL_SRC = glmodule.c cgensupport.c +X#GL_OBJ = glmodule.o cgensupport.o X X X# Panel Option @@ -806,23 +806,23 @@ X# X# If you have source to the NASA Ames Panel Library, you can configure X# Python to incorporate the built-in module 'pnl', which is used byu X# the standard module 'panel' to provide an interface to most features -X# of the Panel Library. This option requires that you also turn on the -X# GL option. It adds about 100K to the Python text size and about 160K +X# of the Panel Library. This option requires that you also turn on the +X# GL option. It adds about 100K to the Python text size and about 160K X# to the unstripped binary size. X# X# Uncomment and edit the following block to use the Panel option. X# - Edit the PANELDIR definition to point to the top-level directory -X# of the Panel distribution tree. +X# of the Panel distribution tree. X -X#PANELDIR= /usr/people/guido/src/pl -X#PANELLIBDIR= $(PANELDIR)/library -X#LIBPANEL= $(PANELLIBDIR)/lib/libpanel.a -X#PANEL_USE= -DUSE_PANEL -X#PANEL_INCL= -I$(PANELLIBDIR)/include -X#PANEL_LIBDEPS= $(LIBPANEL) -X#PANEL_LIBS= $(LIBPANEL) -X#PANEL_SRC= panelmodule.c -X#PANEL_OBJ= panelmodule.o +X#PANELDIR= /usr/people/guido/src/pl +X#PANELLIBDIR= $(PANELDIR)/library +X#LIBPANEL= $(PANELLIBDIR)/lib/libpanel.a +X#PANEL_USE= -DUSE_PANEL +X#PANEL_INCL= -I$(PANELLIBDIR)/include +X#PANEL_LIBDEPS= $(LIBPANEL) +X#PANEL_LIBS= $(LIBPANEL) +X#PANEL_SRC= panelmodule.c +X#PANEL_OBJ= panelmodule.o X X X# Audio Option @@ -832,140 +832,140 @@ X# This option lets you play with /dev/audio on the IRIS 4D/25. X# It incorporates the built-in module 'audio'. X# Warning: using the asynchronous I/O facilities of this module can X# create a second 'thread', which looks in the listings of 'ps' like a -X# forked child. However, it shares its address space with the parent. +X# forked child. However, it shares its address space with the parent. X# X# Uncomment the following block to use the Audio option. X -X#AUDIO_USE= -DUSE_AUDIO -X#AUDIO_SRC= audiomodule.c asa.c -X#AUDIO_OBJ= audiomodule.o asa.o +X#AUDIO_USE= -DUSE_AUDIO +X#AUDIO_SRC= audiomodule.c asa.c +X#AUDIO_OBJ= audiomodule.o asa.o X X X# Major Definitions X# ================= X -XSTANDARD_OBJ= acceler.o bltinmodule.o ceval.o classobject.o \ -X compile.o dictobject.o errors.o fgetsintr.o \ -X fileobject.o floatobject.o $(FMOD_OBJ) frameobject.o \ -X funcobject.o $(GETCWD_OBJ) \ -X graminit.o grammar1.o import.o \ -X intobject.o intrcheck.o listnode.o listobject.o \ -X mathmodule.o methodobject.o modsupport.o \ -X moduleobject.o node.o object.o parser.o \ -X parsetok.o posixmodule.o regexp.o regexpmodule.o \ -X strdup.o $(STRERROR_OBJ) \ -X stringobject.o $(STRTOL_OBJ) structmember.o \ -X sysmodule.o timemodule.o tokenizer.o traceback.o \ -X tupleobject.o typeobject.o -X -XSTANDARD_SRC= acceler.c bltinmodule.c ceval.c classobject.c \ -X compile.c dictobject.c errors.c fgetsintr.c \ -X fileobject.c floatobject.c $(FMOD_SRC) frameobject.c \ -X funcobject.c $(GETCWD_SRC) \ -X graminit.c grammar1.c import.c \ -X intobject.c intrcheck.c listnode.c listobject.c \ -X mathmodule.c methodobject.c modsupport.c \ -X moduleobject.c node.c object.c parser.c \ -X parsetok.c posixmodule.c regexp.c regexpmodule.c \ -X strdup.c $(STRERROR_SRC) \ -X stringobject.c $(STRTOL_SRC) structmember.c \ -X sysmodule.c timemodule.c tokenizer.c traceback.c \ -X tupleobject.c typeobject.c -X -XCONFIGDEFS= $(STDW_USE) $(AM_USE) $(AUDIO_USE) $(GL_USE) $(PANEL_USE) \ -X '-DPYTHONPATH="$(PYTHONPATH)"' -X -XCONFIGINCLS= $(STDW_INCL) -X -XLIBDEPS= libpython.a $(STDW_LIBDEPS) $(AM_LIBDEPS) \ -X $(GL_LIBDEPS) $(PANEL_LIBSDEP) $(RL_LIBDEPS) +XSTANDARD_OBJ= acceler.o bltinmodule.o ceval.o classobject.o \ +X compile.o dictobject.o errors.o fgetsintr.o \ +X fileobject.o floatobject.o $(FMOD_OBJ) frameobject.o \ +X funcobject.o $(GETCWD_OBJ) \ +X graminit.o grammar1.o import.o \ +X intobject.o intrcheck.o listnode.o listobject.o \ +X mathmodule.o methodobject.o modsupport.o \ +X moduleobject.o node.o object.o parser.o \ +X parsetok.o posixmodule.o regexp.o regexpmodule.o \ +X strdup.o $(STRERROR_OBJ) \ +X stringobject.o $(STRTOL_OBJ) structmember.o \ +X sysmodule.o timemodule.o tokenizer.o traceback.o \ +X tupleobject.o typeobject.o +X +XSTANDARD_SRC= acceler.c bltinmodule.c ceval.c classobject.c \ +X compile.c dictobject.c errors.c fgetsintr.c \ +X fileobject.c floatobject.c $(FMOD_SRC) frameobject.c \ +X funcobject.c $(GETCWD_SRC) \ +X graminit.c grammar1.c import.c \ +X intobject.c intrcheck.c listnode.c listobject.c \ +X mathmodule.c methodobject.c modsupport.c \ +X moduleobject.c node.c object.c parser.c \ +X parsetok.c posixmodule.c regexp.c regexpmodule.c \ +X strdup.c $(STRERROR_SRC) \ +X stringobject.c $(STRTOL_SRC) structmember.c \ +X sysmodule.c timemodule.c tokenizer.c traceback.c \ +X tupleobject.c typeobject.c +X +XCONFIGDEFS= $(STDW_USE) $(AM_USE) $(AUDIO_USE) $(GL_USE) $(PANEL_USE) \ +X '-DPYTHONPATH="$(PYTHONPATH)"' +X +XCONFIGINCLS= $(STDW_INCL) +X +XLIBDEPS= libpython.a $(STDW_LIBDEPS) $(AM_LIBDEPS) \ +X $(GL_LIBDEPS) $(PANEL_LIBSDEP) $(RL_LIBDEPS) X X# NB: the ordering of items in LIBS is significant! -XLIBS= libpython.a $(STDW_LIBS) $(AM_LIBS) \ -X $(PANEL_LIBS) $(GL_LIBS) $(RL_LIBS) -lm +XLIBS= libpython.a $(STDW_LIBS) $(AM_LIBS) \ +X $(PANEL_LIBS) $(GL_LIBS) $(RL_LIBS) -lm X -XLIBOBJECTS= $(STANDARD_OBJ) $(STDW_OBJ) $(AM_OBJ) $(AUDIO_OBJ) \ -X $(GL_OBJ) $(PANEL_OBJ) +XLIBOBJECTS= $(STANDARD_OBJ) $(STDW_OBJ) $(AM_OBJ) $(AUDIO_OBJ) \ +X $(GL_OBJ) $(PANEL_OBJ) X -XLIBSOURCES= $(STANDARD_SRC) $(STDW_SRC) $(AM_SRC) $(AUDIO_SRC) \ -X $(GL_SRC) $(PANEL_SRC) +XLIBSOURCES= $(STANDARD_SRC) $(STDW_SRC) $(AM_SRC) $(AUDIO_SRC) \ +X $(GL_SRC) $(PANEL_SRC) X -XOBJECTS= pythonmain.o config.o +XOBJECTS= pythonmain.o config.o X -XSOURCES= $(LIBSOURCES) pythonmain.c config.c +XSOURCES= $(LIBSOURCES) pythonmain.c config.c X -XGENOBJECTS= acceler.o fgetsintr.o grammar1.o \ -X intrcheck.o listnode.o node.o parser.o \ -X parsetok.o strdup.o tokenizer.o bitset.o \ -X firstsets.o grammar.o metagrammar.o pgen.o \ -X pgenmain.o printgrammar.o +XGENOBJECTS= acceler.o fgetsintr.o grammar1.o \ +X intrcheck.o listnode.o node.o parser.o \ +X parsetok.o strdup.o tokenizer.o bitset.o \ +X firstsets.o grammar.o metagrammar.o pgen.o \ +X pgenmain.o printgrammar.o X -XGENSOURCES= acceler.c fgetsintr.c grammar1.c \ -X intrcheck.c listnode.c node.c parser.c \ -X parsetok.c strdup.c tokenizer.c bitset.c \ -X firstsets.c grammar.c metagrammar.c pgen.c \ -X pgenmain.c printgrammar.c +XGENSOURCES= acceler.c fgetsintr.c grammar1.c \ +X intrcheck.c listnode.c node.c parser.c \ +X parsetok.c strdup.c tokenizer.c bitset.c \ +X firstsets.c grammar.c metagrammar.c pgen.c \ +X pgenmain.c printgrammar.c X X X# Main Targets X# ============ X -Xpython: libpython.a $(OBJECTS) $(LIBDEPS) Makefile -X $(CC) $(CFLAGS) $(OBJECTS) $(LIBS) -o @python -X mv @python python +Xpython: libpython.a $(OBJECTS) $(LIBDEPS) Makefile +X $(CC) $(CFLAGS) $(OBJECTS) $(LIBS) -o @python +X mv @python python X -Xlibpython.a: $(LIBOBJECTS) -X -rm -f @lib -X ar cr @lib $(LIBOBJECTS) -X $(RANLIB) @lib -X mv @lib libpython.a +Xlibpython.a: $(LIBOBJECTS) +X -rm -f @lib +X ar cr @lib $(LIBOBJECTS) +X $(RANLIB) @lib +X mv @lib libpython.a X -Xpython_gen: $(GENOBJECTS) $(RL_LIBDEPS) -X $(CC) $(CFLAGS) $(GENOBJECTS) $(RL_LIBS) -o python_gen +Xpython_gen: $(GENOBJECTS) $(RL_LIBDEPS) +X $(CC) $(CFLAGS) $(GENOBJECTS) $(RL_LIBS) -o python_gen X X X# Utility Targets X# =============== X -X# Don't take the output from lint too seriously. I have not attempted -X# to make Python lint-free. But I use function prototypes. +X# Don't take the output from lint too seriously. I have not attempted +X# to make Python lint-free. But I use function prototypes. X -XLINTFLAGS= -h +XLINTFLAGS= -h X -XLINTCPPFLAGS= $(CONFIGDEFS) $(CONFIGINCLS) $(SYSVDEF) \ -X $(AM_INCL) $(PANEL_INCL) +XLINTCPPFLAGS= $(CONFIGDEFS) $(CONFIGINCLS) $(SYSVDEF) \ +X $(AM_INCL) $(PANEL_INCL) X -XLINT= lint +XLINT= lint X -Xlint:: $(SOURCES) -X $(LINT) $(LINTFLAGS) $(LINTCPPFLAGS) $(SOURCES) +Xlint:: $(SOURCES) +X $(LINT) $(LINTFLAGS) $(LINTCPPFLAGS) $(SOURCES) X -Xlint:: $(GENSOURCES) -X $(LINT) $(LINTFLAGS) $(GENSOURCES) +Xlint:: $(GENSOURCES) +X $(LINT) $(LINTFLAGS) $(GENSOURCES) X X# Generating dependencies is only necessary if you intend to hack Python. X# You may change $(MKDEP) to your favorite dependency generator (it should X# edit the Makefile in place). X -XMKDEP= mkdep +XMKDEP= mkdep X Xdepend:: -X $(MKDEP) $(LINTCPPFLAGS) $(SOURCES) $(GENSOURCES) +X $(MKDEP) $(LINTCPPFLAGS) $(SOURCES) $(GENSOURCES) X X# You may change $(CTAGS) to suit your taste... X -XCTAGS= ctags -t -w +XCTAGS= ctags -t -w X -XHEADERS= *.h +XHEADERS= *.h X -Xtags: $(SOURCES) $(GENSOURCES) $(HEADERS) -X $(CTAGS) $(SOURCES) $(GENSOURCES) $(HEADERS) +Xtags: $(SOURCES) $(GENSOURCES) $(HEADERS) +X $(CTAGS) $(SOURCES) $(GENSOURCES) $(HEADERS) X Xclean:: -X -rm -f *.o core [,#@]* +X -rm -f *.o core [,#@]* X -Xclobber:: clean -X -rm -f python python_gen libpython.a tags +Xclobber:: clean +X -rm -f python python_gen libpython.a tags X X X# Build Special Objects @@ -973,42 +973,42 @@ X# ===================== X X# You may change $(COMPILE) to reflect the default .c.o rule... X -XCOMPILE= $(CC) -c $(CFLAGS) +XCOMPILE= $(CC) -c $(CFLAGS) X -Xamoebamodule.o: amoebamodule.c -X $(COMPILE) $(AM_INCL) $*.c +Xamoebamodule.o: amoebamodule.c +X $(COMPILE) $(AM_INCL) $*.c X -Xconfig.o: config.c Makefile -X $(COMPILE) $(CONFIGDEFS) $(CONFIGINCLS) $*.c +Xconfig.o: config.c Makefile +X $(COMPILE) $(CONFIGDEFS) $(CONFIGINCLS) $*.c X -Xfgetsintr.o: fgetsintr.c -X $(COMPILE) $(SIGTYPEDEF) $*.c +Xfgetsintr.o: fgetsintr.c +X $(COMPILE) $(SIGTYPEDEF) $*.c X -Xintrcheck.o: intrcheck.c -X $(COMPILE) $(SIGTYPEDEF) $*.c +Xintrcheck.o: intrcheck.c +X $(COMPILE) $(SIGTYPEDEF) $*.c X -Xpanelmodule.o: panelmodule.c -X $(COMPILE) $(PANEL_INCL) $*.c +Xpanelmodule.o: panelmodule.c +X $(COMPILE) $(PANEL_INCL) $*.c X -Xposixmodule.o: posixmodule.c -X $(COMPILE) $(SYSVDEF) $(NOSYMLINKDEF) $*.c +Xposixmodule.o: posixmodule.c +X $(COMPILE) $(SYSVDEF) $(NOSYMLINKDEF) $*.c X -Xsc_interpr.o: sc_interpr.c -X $(COMPILE) $(AM_INCL) $*.c +Xsc_interpr.o: sc_interpr.c +X $(COMPILE) $(AM_INCL) $*.c X -Xsc_error.o: sc_error.c -X $(COMPILE) $(AM_INCL) $*.c +Xsc_error.o: sc_error.c +X $(COMPILE) $(AM_INCL) $*.c X -Xstdwinmodule.o: stdwinmodule.c -X $(COMPILE) $(STDW_INCL) $*.c +Xstdwinmodule.o: stdwinmodule.c +X $(COMPILE) $(STDW_INCL) $*.c X -Xtimemodule.o: timemodule.c -X $(COMPILE) $(SIGTYPEDEF) $(BSDTIMEDEF) $*.c +Xtimemodule.o: timemodule.c +X $(COMPILE) $(SIGTYPEDEF) $(BSDTIMEDEF) $*.c X -Xtokenizer.o: tokenizer.c -X $(COMPILE) $(RL_USE) $*.c +Xtokenizer.o: tokenizer.c +X $(COMPILE) $(RL_USE) $*.c X -X.PRECIOUS: python libpython.a glmodule.c graminit.c graminit.h +X.PRECIOUS: python libpython.a glmodule.c graminit.c graminit.h X X X# Generated Sources @@ -1021,16 +1021,16 @@ X# Build "glmodule.c", the GL interface. X# Ignore the messages emitted by the cgen script. X# Also ignore the warnings emitted while compiling glmodule.c; it works. X -Xglmodule.c: cstubs cgen -X python cgen <cstubs >@glmodule.c -X mv @glmodule.c glmodule.c +Xglmodule.c: cstubs cgen +X python cgen <cstubs >@glmodule.c +X mv @glmodule.c glmodule.c X X# The dependencies for graminit.[ch] are not turned on in the X# distributed Makefile because the files themselves are distributed. X# Turn them on if you want to hack the grammar. X -X#graminit.c graminit.h: Grammar python_gen -X# python_gen Grammar +X#graminit.c graminit.h: Grammar python_gen +X# python_gen Grammar X EOF fi @@ -1043,12 +1043,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1097,7 +1097,7 @@ X Xextern char *err_why(); Xextern char *ar_cap(); X -X#define STUBCODE "+stubcode" +X#define STUBCODE "+stubcode" X Xstatic object *AmoebaError; Xobject *StubcodeError; @@ -1111,36 +1111,36 @@ Xextern object *convertcapv(); /* Forward */ X Xstatic void Xins(d, name, v) -X object *d; -X char *name; -X object *v; +X object *d; +X char *name; +X object *v; X{ -X if (v == NULL || dictinsert(d, name, v) != 0) -X fatal("can't initialize amoeba module"); +X if (v == NULL || dictinsert(d, name, v) != 0) +X fatal("can't initialize amoeba module"); X} X Xvoid Xinitamoeba() X{ -X object *m, *d, *v; -X -X m = initmodule("amoeba", amoeba_methods); -X d = getmoduledict(m); -X -X /* Define capv */ -X v = convertcapv(); -X ins(d, "capv", v); -X DECREF(v); -X -X /* Set timeout */ -X timeout((interval)2000); -X -X /* Initialize amoeba.error exception */ -X AmoebaError = newstringobject("amoeba.error"); -X ins(d, "error", AmoebaError); -X StubcodeError = newstringobject("amoeba.stubcode_error"); -X ins(d, "stubcode_error", StubcodeError); -X sc_dict = newdictobject(); +X object *m, *d, *v; +X +X m = initmodule("amoeba", amoeba_methods); +X d = getmoduledict(m); +X +X /* Define capv */ +X v = convertcapv(); +X ins(d, "capv", v); +X DECREF(v); +X +X /* Set timeout */ +X timeout((interval)2000); +X +X /* Initialize amoeba.error exception */ +X AmoebaError = newstringobject("amoeba.error"); +X ins(d, "error", AmoebaError); +X StubcodeError = newstringobject("amoeba.stubcode_error"); +X ins(d, "stubcode_error", StubcodeError); +X sc_dict = newdictobject(); X} X X @@ -1148,17 +1148,17 @@ X/* Set an Amoeba-specific error, and return NULL */ X Xobject * Xamoeba_error(err) -X errstat err; +X errstat err; X{ -X object *v = newtupleobject(2); -X if (v != NULL) { -X settupleitem(v, 0, newintobject((long)err)); -X settupleitem(v, 1, newstringobject(err_why(err))); -X } -X err_setval(AmoebaError, v); -X if (v != NULL) -X DECREF(v); -X return NULL; +X object *v = newtupleobject(2); +X if (v != NULL) { +X settupleitem(v, 0, newintobject((long)err)); +X settupleitem(v, 1, newstringobject(err_why(err))); +X } +X err_setval(AmoebaError, v); +X if (v != NULL) +X DECREF(v); +X return NULL; X} X X @@ -1169,62 +1169,62 @@ X X#define is_capobject(v) ((v)->ob_type == &Captype) X Xtypedef struct { -X OB_HEAD -X capability ob_cap; +X OB_HEAD +X capability ob_cap; X} capobject; X Xobject * Xnewcapobject(cap) -X capability *cap; +X capability *cap; X{ -X capobject *v = NEWOBJ(capobject, &Captype); -X if (v == NULL) -X return NULL; -X v->ob_cap = *cap; -X return (object *)v; +X capobject *v = NEWOBJ(capobject, &Captype); +X if (v == NULL) +X return NULL; +X v->ob_cap = *cap; +X return (object *)v; X} X Xgetcapability(v, cap) -X object *v; -X capability *cap; +X object *v; +X capability *cap; X{ X -X if (!is_capobject(v)) -X return err_badarg(); -X *cap = ((capobject *)v)->ob_cap; -X return 0; +X if (!is_capobject(v)) +X return err_badarg(); +X *cap = ((capobject *)v)->ob_cap; +X return 0; X} X X/* -X * is_capobj exports the is_capobject macro to the stubcode modules +X * is_capobj exports the is_capobject macro to the stubcode modules X */ X Xint Xis_capobj(v) -X object *v; +X object *v; X{ X -X return is_capobject(v); +X return is_capobject(v); X} X X/* Methods */ X Xstatic void Xcapprint(v, fp, flags) -X capobject *v; -X FILE *fp; -X int flags; +X capobject *v; +X FILE *fp; +X int flags; X{ -X /* XXX needs lock when multi-threading */ -X fputs(ar_cap(&v->ob_cap), fp); +X /* XXX needs lock when multi-threading */ +X fputs(ar_cap(&v->ob_cap), fp); X} X Xstatic object * Xcaprepr(v) -X capobject *v; +X capobject *v; X{ -X /* XXX needs lock when multi-threading */ -X return newstringobject(ar_cap(&v->ob_cap)); +X /* XXX needs lock when multi-threading */ +X return newstringobject(ar_cap(&v->ob_cap)); X} X Xextern object *sc_interpreter(); @@ -1233,216 +1233,216 @@ Xextern struct methodlist cap_methods[]; /* Forward */ X Xobject * Xsc_makeself(cap, stubcode, name) -X object *cap, *stubcode; -X char *name; +X object *cap, *stubcode; +X char *name; X{ -X object *sc_name, *sc_self; -X -X sc_name = newstringobject(name); -X if (sc_name == NULL) -X return NULL; -X sc_self = newtupleobject(3); -X if (sc_self == NULL) { -X DECREF(sc_name); -X return NULL; -X } -X if (settupleitem(sc_self, NAME, sc_name) != 0) { -X DECREF(sc_self); -X return NULL; -X } -X INCREF(cap); -X if (settupleitem(sc_self, CAP, cap) != 0) { -X DECREF(sc_self); -X return NULL; -X } -X INCREF(stubcode); -X if (settupleitem(sc_self, STUBC, stubcode) != 0) { -X DECREF(sc_self); -X return NULL; -X } -X return sc_self; +X object *sc_name, *sc_self; +X +X sc_name = newstringobject(name); +X if (sc_name == NULL) +X return NULL; +X sc_self = newtupleobject(3); +X if (sc_self == NULL) { +X DECREF(sc_name); +X return NULL; +X } +X if (settupleitem(sc_self, NAME, sc_name) != 0) { +X DECREF(sc_self); +X return NULL; +X } +X INCREF(cap); +X if (settupleitem(sc_self, CAP, cap) != 0) { +X DECREF(sc_self); +X return NULL; +X } +X INCREF(stubcode); +X if (settupleitem(sc_self, STUBC, stubcode) != 0) { +X DECREF(sc_self); +X return NULL; +X } +X return sc_self; X} X X Xstatic void Xswapcode(code, len) -X char *code; -X int len; +X char *code; +X int len; X{ -X int i = sizeof(TscOperand); -X TscOpcode opcode; -X TscOperand operand; -X -X while (i < len) { -X memcpy(&opcode, &code[i], sizeof(TscOpcode)); -X SwapOpcode(opcode); -X memcpy(&code[i], &opcode, sizeof(TscOpcode)); -X i += sizeof(TscOpcode); -X if (opcode & OPERAND) { -X memcpy(&operand, &code[i], sizeof(TscOperand)); -X SwapOperand(operand); -X memcpy(&code[i], &operand, sizeof(TscOperand)); -X i += sizeof(TscOperand); -X } -X } +X int i = sizeof(TscOperand); +X TscOpcode opcode; +X TscOperand operand; +X +X while (i < len) { +X memcpy(&opcode, &code[i], sizeof(TscOpcode)); +X SwapOpcode(opcode); +X memcpy(&code[i], &opcode, sizeof(TscOpcode)); +X i += sizeof(TscOpcode); +X if (opcode & OPERAND) { +X memcpy(&operand, &code[i], sizeof(TscOperand)); +X SwapOperand(operand); +X memcpy(&code[i], &operand, sizeof(TscOperand)); +X i += sizeof(TscOperand); +X } +X } X} X Xobject * Xsc_findstubcode(v, name) -X object *v; -X char *name; +X object *v; +X char *name; X{ -X int fd, fsize; -X char *fname, *buffer; -X struct stat statbuf; -X object *sc_stubcode, *ret; -X TscOperand sc_magic; -X -X /* -X * Only look in the current directory for now. -X */ -X fname = malloc(strlen(name) + 4); -X if (fname == NULL) { -X return err_nomem(); -X } -X sprintf(fname, "%s.sc", name); -X if ((fd = open(fname, O_RDONLY)) == -1) { -X extern int errno; -X -X if (errno == 2) { -X /* -X ** errno == 2 is file not found. -X */ -X err_setstr(NameError, fname); -X return NULL; -X } -X free(fname); -X return err_errno(newstringobject(name)); -X } -X fstat(fd, &statbuf); -X fsize = (int)statbuf.st_size; -X buffer = malloc(fsize); -X if (buffer == NULL) { -X free(fname); -X close(fd); -X return err_nomem(); -X } -X if (read(fd, buffer, fsize) != fsize) { -X close(fd); -X free(fname); -X return err_errno(newstringobject(name)); -X } -X close(fd); -X free(fname); -X memcpy(&sc_magic, buffer, sizeof(TscOperand)); -X if (sc_magic != SC_MAGIC) { -X SwapOperand(sc_magic); -X if (sc_magic != SC_MAGIC) { -X free(buffer); -X return NULL; -X } else { -X swapcode(buffer, fsize); -X } -X } -X sc_stubcode = newsizedstringobject( &buffer[sizeof(TscOperand)], -X fsize - sizeof(TscOperand)); -X free(buffer); -X if (sc_stubcode == NULL) { -X return NULL; -X } -X if (dictinsert(sc_dict, name, sc_stubcode) != 0) { -X DECREF(sc_stubcode); -X return NULL; -X } -X DECREF(sc_stubcode); /* XXXX */ -X sc_stubcode = sc_makeself(v, sc_stubcode, name); -X if (sc_stubcode == NULL) { -X return NULL; -X } -X return sc_stubcode; +X int fd, fsize; +X char *fname, *buffer; +X struct stat statbuf; +X object *sc_stubcode, *ret; +X TscOperand sc_magic; +X +X /* +X * Only look in the current directory for now. +X */ +X fname = malloc(strlen(name) + 4); +X if (fname == NULL) { +X return err_nomem(); +X } +X sprintf(fname, "%s.sc", name); +X if ((fd = open(fname, O_RDONLY)) == -1) { +X extern int errno; +X +X if (errno == 2) { +X /* +X ** errno == 2 is file not found. +X */ +X err_setstr(NameError, fname); +X return NULL; +X } +X free(fname); +X return err_errno(newstringobject(name)); +X } +X fstat(fd, &statbuf); +X fsize = (int)statbuf.st_size; +X buffer = malloc(fsize); +X if (buffer == NULL) { +X free(fname); +X close(fd); +X return err_nomem(); +X } +X if (read(fd, buffer, fsize) != fsize) { +X close(fd); +X free(fname); +X return err_errno(newstringobject(name)); +X } +X close(fd); +X free(fname); +X memcpy(&sc_magic, buffer, sizeof(TscOperand)); +X if (sc_magic != SC_MAGIC) { +X SwapOperand(sc_magic); +X if (sc_magic != SC_MAGIC) { +X free(buffer); +X return NULL; +X } else { +X swapcode(buffer, fsize); +X } +X } +X sc_stubcode = newsizedstringobject( &buffer[sizeof(TscOperand)], +X fsize - sizeof(TscOperand)); +X free(buffer); +X if (sc_stubcode == NULL) { +X return NULL; +X } +X if (dictinsert(sc_dict, name, sc_stubcode) != 0) { +X DECREF(sc_stubcode); +X return NULL; +X } +X DECREF(sc_stubcode); /* XXXX */ +X sc_stubcode = sc_makeself(v, sc_stubcode, name); +X if (sc_stubcode == NULL) { +X return NULL; +X } +X return sc_stubcode; X} X Xobject * Xcapgetattr(v, name) -X capobject *v; -X char *name; +X capobject *v; +X char *name; X{ -X object *sc_method, *sc_stubcodemethod; -X -X if (sc_dict == NULL) { -X /* -X ** For some reason the dictionary has not been -X ** initialized. Try to find one of the built in -X ** methods. -X */ -X return findmethod(cap_methods, (object *)v, name); -X } -X sc_stubcodemethod = dictlookup(sc_dict, name); -X if (sc_stubcodemethod != NULL) { -X /* -X ** There is a stubcode method in the dictionary. -X ** Execute the stubcode interpreter with the right -X ** arguments. -X */ -X object *self, *ret; -X -X self = sc_makeself((object *)v, sc_stubcodemethod, name); -X if (self == NULL) { -X return NULL; -X } -X ret = findmethod(cap_methods, self, STUBCODE); -X DECREF(self); -X return ret; -X } -X err_clear(); -X sc_method = findmethod(cap_methods, (object *)v, name); -X if (sc_method == NULL) { -X /* -X ** The method is not built in and not in the -X ** dictionary. Try to find it as a stubcode file. -X */ -X object *self, *ret; -X -X err_clear(); -X self = sc_findstubcode((object *)v, name); -X if (self == NULL) { -X return NULL; -X } -X ret = findmethod(cap_methods, self, STUBCODE); -X DECREF(self); -X return ret; -X } -X return sc_method; +X object *sc_method, *sc_stubcodemethod; +X +X if (sc_dict == NULL) { +X /* +X ** For some reason the dictionary has not been +X ** initialized. Try to find one of the built in +X ** methods. +X */ +X return findmethod(cap_methods, (object *)v, name); +X } +X sc_stubcodemethod = dictlookup(sc_dict, name); +X if (sc_stubcodemethod != NULL) { +X /* +X ** There is a stubcode method in the dictionary. +X ** Execute the stubcode interpreter with the right +X ** arguments. +X */ +X object *self, *ret; +X +X self = sc_makeself((object *)v, sc_stubcodemethod, name); +X if (self == NULL) { +X return NULL; +X } +X ret = findmethod(cap_methods, self, STUBCODE); +X DECREF(self); +X return ret; +X } +X err_clear(); +X sc_method = findmethod(cap_methods, (object *)v, name); +X if (sc_method == NULL) { +X /* +X ** The method is not built in and not in the +X ** dictionary. Try to find it as a stubcode file. +X */ +X object *self, *ret; +X +X err_clear(); +X self = sc_findstubcode((object *)v, name); +X if (self == NULL) { +X return NULL; +X } +X ret = findmethod(cap_methods, self, STUBCODE); +X DECREF(self); +X return ret; +X } +X return sc_method; X} X Xint Xcapcompare(v, w) -X capobject *v, *w; +X capobject *v, *w; X{ -X int cmp = bcmp((char *)&v->ob_cap.cap_port, -X (char *)&w->ob_cap, PORTSIZE); -X if (cmp != 0) -X return cmp; -X return prv_number(&v->ob_cap.cap_priv) - -X prv_number(&w->ob_cap.cap_priv); +X int cmp = bcmp((char *)&v->ob_cap.cap_port, +X (char *)&w->ob_cap, PORTSIZE); +X if (cmp != 0) +X return cmp; +X return prv_number(&v->ob_cap.cap_priv) - +X prv_number(&w->ob_cap.cap_priv); X} X Xstatic typeobject Captype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "capability", -X sizeof(capobject), -X 0, -X free, /*tp_dealloc*/ -X capprint, /*tp_print*/ -X capgetattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X capcompare, /*tp_comp +X OB_HEAD_INIT(&Typetype) +X 0, +X "capability", +X sizeof(capobject), +X 0, +X free, /*tp_dealloc*/ +X capprint, /*tp_print*/ +X capgetattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X capcompare, /*tp_comp are*/ -X caprepr, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X caprepr, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X X @@ -1453,22 +1453,22 @@ X Xstatic object * Xconvertcapv() X{ -X object *d; -X struct caplist *c; -X d = newdictobject(); -X if (d == NULL) -X return NULL; -X if (capv == NULL) -X return d; -X for (c = capv; c->cl_name != NULL; c++) { -X object *v = newcapobject(c->cl_cap); -X if (v == NULL || dictinsert(d, c->cl_name, v) != 0) { -X DECREF(d); -X return NULL; -X } -X DECREF(v); -X } -X return d; +X object *d; +X struct caplist *c; +X d = newdictobject(); +X if (d == NULL) +X return NULL; +X if (capv == NULL) +X return d; +X for (c = capv; c->cl_name != NULL; c++) { +X object *v = newcapobject(c->cl_cap); +X if (v == NULL || dictinsert(d, c->cl_name, v) != 0) { +X DECREF(d); +X return NULL; +X } +X DECREF(v); +X } +X return d; X} X X @@ -1476,25 +1476,25 @@ X/* Strongly Amoeba-specific argument handlers */ X Xstatic int Xgetcaparg(v, a) -X object *v; -X capability *a; +X object *v; +X capability *a; X{ -X if (v == NULL || !is_capobject(v)) -X return err_badarg(); -X *a = ((capobject *)v) -> ob_cap; -X return 1; +X if (v == NULL || !is_capobject(v)) +X return err_badarg(); +X *a = ((capobject *)v) -> ob_cap; +X return 1; X} X Xstatic int Xgetstrcapargs(v, a, b) -X object *v; -X object **a; -X capability *b; +X object *v; +X object **a; +X capability *b; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) -X return err_badarg(); -X return getstrarg(gettupleitem(v, 0), a) && -X getcaparg(gettupleitem(v, 1), b); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) +X return err_badarg(); +X return getstrarg(gettupleitem(v, 0), a) && +X getcaparg(gettupleitem(v, 1), b); X} X X @@ -1502,316 +1502,316 @@ X/* Amoeba methods */ X Xstatic object * Xamoeba_name_lookup(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *name; -X capability cap; -X errstat err; -X if (!getstrarg(args, &name)) -X return NULL; -X err = name_lookup(getstringvalue(name), &cap); -X if (err != STD_OK) -X return amoeba_error(err); -X return newcapobject(&cap); +X object *name; +X capability cap; +X errstat err; +X if (!getstrarg(args, &name)) +X return NULL; +X err = name_lookup(getstringvalue(name), &cap); +X if (err != STD_OK) +X return amoeba_error(err); +X return newcapobject(&cap); X} X Xstatic object * Xamoeba_name_append(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *name; -X capability cap; -X errstat err; -X if (!getstrcapargs(args, &name, &cap)) -X return NULL; -X err = name_append(getstringvalue(name), &cap); -X if (err != STD_OK) -X return amoeba_error(err); -X INCREF(None); -X return None; +X object *name; +X capability cap; +X errstat err; +X if (!getstrcapargs(args, &name, &cap)) +X return NULL; +X err = name_append(getstringvalue(name), &cap); +X if (err != STD_OK) +X return amoeba_error(err); +X INCREF(None); +X return None; X} X Xstatic object * Xamoeba_name_replace(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *name; -X capability cap; -X errstat err; -X if (!getstrcapargs(args, &name, &cap)) -X return NULL; -X err = name_replace(getstringvalue(name), &cap); -X if (err != STD_OK) -X return amoeba_error(err); -X INCREF(None); -X return None; +X object *name; +X capability cap; +X errstat err; +X if (!getstrcapargs(args, &name, &cap)) +X return NULL; +X err = name_replace(getstringvalue(name), &cap); +X if (err != STD_OK) +X return amoeba_error(err); +X INCREF(None); +X return None; X} X Xstatic object * Xamoeba_name_delete(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *name; -X errstat err; -X if (!getstrarg(args, &name)) -X return NULL; -X err = name_delete(getstringvalue(name)); -X if (err != STD_OK) -X return amoeba_error(err); -X INCREF(None); -X return None; +X object *name; +X errstat err; +X if (!getstrarg(args, &name)) +X return NULL; +X err = name_delete(getstringvalue(name)); +X if (err != STD_OK) +X return amoeba_error(err); +X INCREF(None); +X return None; X} X Xstatic object * Xamoeba_timeout(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int i; -X object *v; -X interval tout; -X if (!getintarg(args, &i)) -X return NULL; -X tout = timeout((interval)i); -X v = newintobject((long)tout); -X if (v == NULL) -X timeout(tout); -X return v; +X int i; +X object *v; +X interval tout; +X if (!getintarg(args, &i)) +X return NULL; +X tout = timeout((interval)i); +X v = newintobject((long)tout); +X if (v == NULL) +X timeout(tout); +X return v; X} X Xstatic struct methodlist amoeba_methods[] = { -X {"name_append", amoeba_name_append}, -X {"name_delete", amoeba_name_delete}, -X {"name_lookup", amoeba_name_lookup}, -X {"name_replace", amoeba_name_replace}, -X {"timeout", amoeba_timeout}, -X {NULL, NULL} /* Sentinel */ +X {"name_append", amoeba_name_append}, +X {"name_delete", amoeba_name_delete}, +X {"name_lookup", amoeba_name_lookup}, +X {"name_replace", amoeba_name_replace}, +X {"timeout", amoeba_timeout}, +X {NULL, NULL} /* Sentinel */ X}; X X/* Capability methods */ X Xstatic object * Xcap_b_size(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X errstat err; -X b_fsize size; -X if (!getnoarg(args)) -X return NULL; -X err = b_size(&self->ob_cap, &size); -X if (err != STD_OK) -X return amoeba_error(err); -X return newintobject((long)size); +X errstat err; +X b_fsize size; +X if (!getnoarg(args)) +X return NULL; +X err = b_size(&self->ob_cap, &size); +X if (err != STD_OK) +X return amoeba_error(err); +X return newintobject((long)size); X} X Xstatic object * Xcap_b_read(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X errstat err; -X char *buf; -X object *v; -X long offset, size; -X b_fsize nread; -X if (!getlonglongargs(args, &offset, &size)) -X return NULL; -X buf = malloc((unsigned int)size); -X if (buf == NULL) { -X return err_nomem(); -X } -X err = b_read(&self->ob_cap, (b_fsize)offset, buf, (b_fsize)size, -X &nread); -X if (err != STD_OK) { -X free(buf); -X return amoeba_error(err); -X } -X v = newsizedstringobject(buf, (int)nread); -X free(buf); -X return v; +X errstat err; +X char *buf; +X object *v; +X long offset, size; +X b_fsize nread; +X if (!getlonglongargs(args, &offset, &size)) +X return NULL; +X buf = malloc((unsigned int)size); +X if (buf == NULL) { +X return err_nomem(); +X } +X err = b_read(&self->ob_cap, (b_fsize)offset, buf, (b_fsize)size, +X &nread); +X if (err != STD_OK) { +X free(buf); +X return amoeba_error(err); +X } +X v = newsizedstringobject(buf, (int)nread); +X free(buf); +X return v; X} X Xstatic object * Xcap_dir_lookup(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X object *name; -X capability cap; -X errstat err; -X if (!getstrarg(args, &name)) -X return NULL; -X err = dir_lookup(&self->ob_cap, getstringvalue(name), &cap); -X if (err != STD_OK) -X return amoeba_error(err); -X return newcapobject(&cap); +X object *name; +X capability cap; +X errstat err; +X if (!getstrarg(args, &name)) +X return NULL; +X err = dir_lookup(&self->ob_cap, getstringvalue(name), &cap); +X if (err != STD_OK) +X return amoeba_error(err); +X return newcapobject(&cap); X} X Xstatic object * Xcap_dir_append(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X object *name; -X capability cap; -X errstat err; -X if (!getstrcapargs(args, &name, &cap)) -X return NULL; -X err = dir_append(&self->ob_cap, getstringvalue(name), &cap); -X if (err != STD_OK) -X return amoeba_error(err); -X INCREF(None); -X return None; +X object *name; +X capability cap; +X errstat err; +X if (!getstrcapargs(args, &name, &cap)) +X return NULL; +X err = dir_append(&self->ob_cap, getstringvalue(name), &cap); +X if (err != STD_OK) +X return amoeba_error(err); +X INCREF(None); +X return None; X} X Xstatic object * Xcap_dir_delete(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X object *name; -X errstat err; -X if (!getstrarg(args, &name)) -X return NULL; -X err = dir_delete(&self->ob_cap, getstringvalue(name)); -X if (err != STD_OK) -X return amoeba_error(err); -X INCREF(None); -X return None; +X object *name; +X errstat err; +X if (!getstrarg(args, &name)) +X return NULL; +X err = dir_delete(&self->ob_cap, getstringvalue(name)); +X if (err != STD_OK) +X return amoeba_error(err); +X INCREF(None); +X return None; X} X Xstatic object * Xcap_dir_replace(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X object *name; -X capability cap; -X errstat err; -X if (!getstrcapargs(args, &name, &cap)) -X return NULL; -X err = dir_replace(&self->ob_cap, getstringvalue(name), &cap); -X if (err != STD_OK) -X return amoeba_error(err); -X INCREF(None); -X return None; +X object *name; +X capability cap; +X errstat err; +X if (!getstrcapargs(args, &name, &cap)) +X return NULL; +X err = dir_replace(&self->ob_cap, getstringvalue(name), &cap); +X if (err != STD_OK) +X return amoeba_error(err); +X INCREF(None); +X return None; X} X Xstatic object * Xcap_dir_list(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X errstat err; -X struct dir_open *dd; -X object *d; -X char *name; -X if (!getnoarg(args)) -X return NULL; -X if ((dd = dir_open(&self->ob_cap)) == NULL) -X return amoeba_error(STD_COMBAD); -X if ((d = newlistobject(0)) == NULL) { -X dir_close(dd); -X return NULL; -X } -X while ((name = dir_next(dd)) != NULL) { -X object *v; -X v = newstringobject(name); -X if (v == NULL) { -X DECREF(d); -X d = NULL; -X break; -X } -X if (addlistitem(d, v) != 0) { -X DECREF(v); -X DECREF(d); -X d = NULL; -X break; -X } -X DECREF(v); -X } -X dir_close(dd); -X return d; +X errstat err; +X struct dir_open *dd; +X object *d; +X char *name; +X if (!getnoarg(args)) +X return NULL; +X if ((dd = dir_open(&self->ob_cap)) == NULL) +X return amoeba_error(STD_COMBAD); +X if ((d = newlistobject(0)) == NULL) { +X dir_close(dd); +X return NULL; +X } +X while ((name = dir_next(dd)) != NULL) { +X object *v; +X v = newstringobject(name); +X if (v == NULL) { +X DECREF(d); +X d = NULL; +X break; +X } +X if (addlistitem(d, v) != 0) { +X DECREF(v); +X DECREF(d); +X d = NULL; +X break; +X } +X DECREF(v); +X } +X dir_close(dd); +X return d; X} X Xobject * Xcap_std_info(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X char buf[256]; -X errstat err; -X int n; -X if (!getnoarg(args)) -X return NULL; -X err = std_info(&self->ob_cap, buf, sizeof buf, &n); -X if (err != STD_OK) -X return amoeba_error(err); -X return newsizedstringobject(buf, n); +X char buf[256]; +X errstat err; +X int n; +X if (!getnoarg(args)) +X return NULL; +X err = std_info(&self->ob_cap, buf, sizeof buf, &n); +X if (err != STD_OK) +X return amoeba_error(err); +X return newsizedstringobject(buf, n); X} X Xobject * Xcap_tod_gettime(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X header h; -X errstat err; -X bufsize n; -X long sec; -X int msec, tz, dst; -X if (!getnoarg(args)) -X return NULL; -X h.h_port = self->ob_cap.cap_port; -X h.h_priv = self->ob_cap.cap_priv; -X h.h_command = TOD_GETTIME; -X n = trans(&h, NILBUF, 0, &h, NILBUF, 0); -X if (ERR_STATUS(n)) -X return amoeba_error(ERR_CONVERT(n)); -X tod_decode(&h, &sec, &msec, &tz, &dst); -X return newintobject(sec); +X header h; +X errstat err; +X bufsize n; +X long sec; +X int msec, tz, dst; +X if (!getnoarg(args)) +X return NULL; +X h.h_port = self->ob_cap.cap_port; +X h.h_priv = self->ob_cap.cap_priv; +X h.h_command = TOD_GETTIME; +X n = trans(&h, NILBUF, 0, &h, NILBUF, 0); +X if (ERR_STATUS(n)) +X return amoeba_error(ERR_CONVERT(n)); +X tod_decode(&h, &sec, &msec, &tz, &dst); +X return newintobject(sec); X} X Xobject * Xcap_tod_settime(self, args) -X capobject *self; -X object *args; +X capobject *self; +X object *args; X{ -X header h; -X errstat err; -X bufsize n; -X long sec; -X if (!getlongarg(args, &sec)) -X return NULL; -X h.h_port = self->ob_cap.cap_port; -X h.h_priv = self->ob_cap.cap_priv; -X h.h_command = TOD_SETTIME; -X tod_encode(&h, sec, 0, 0, 0); -X n = trans(&h, NILBUF, 0, &h, NILBUF, 0); -X if (ERR_STATUS(n)) -X return amoeba_error(ERR_CONVERT(n)); -X INCREF(None); -X return None; +X header h; +X errstat err; +X bufsize n; +X long sec; +X if (!getlongarg(args, &sec)) +X return NULL; +X h.h_port = self->ob_cap.cap_port; +X h.h_priv = self->ob_cap.cap_priv; +X h.h_command = TOD_SETTIME; +X tod_encode(&h, sec, 0, 0, 0); +X n = trans(&h, NILBUF, 0, &h, NILBUF, 0); +X if (ERR_STATUS(n)) +X return amoeba_error(ERR_CONVERT(n)); +X INCREF(None); +X return None; X} X Xstatic struct methodlist cap_methods[] = { -X { STUBCODE, sc_interpreter}, -X {"b_read", cap_b_read}, -X {"b_size", cap_b_size}, -X {"dir_append", cap_dir_append}, -X {"dir_delete", cap_dir_delete}, -X {"dir_list", cap_dir_list}, -X {"dir_lookup", cap_dir_lookup}, -X {"dir_replace", cap_dir_replace}, -X {"std_info", cap_std_info}, -X {"tod_gettime", cap_tod_gettime}, -X {"tod_settime", cap_tod_settime}, -X {NULL, NULL} /* Sentinel */ +X { STUBCODE, sc_interpreter}, +X {"b_read", cap_b_read}, +X {"b_size", cap_b_size}, +X {"dir_append", cap_dir_append}, +X {"dir_delete", cap_dir_delete}, +X {"dir_list", cap_dir_list}, +X {"dir_lookup", cap_dir_lookup}, +X {"dir_replace", cap_dir_replace}, +X {"std_info", cap_std_info}, +X {"tod_gettime", cap_tod_gettime}, +X {"tod_settime", cap_tod_settime}, +X {NULL, NULL} /* Sentinel */ X}; EOF fi @@ -1824,12 +1824,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1875,37 +1875,37 @@ X X/* Token names */ X Xchar *tok_name[] = { -X "ENDMARKER", -X "NAME", -X "NUMBER", -X "STRING", -X "NEWLINE", -X "INDENT", -X "DEDENT", -X "LPAR", -X "RPAR", -X "LSQB", -X "RSQB", -X "COLON", -X "COMMA", -X "SEMI", -X "PLUS", -X "MINUS", -X "STAR", -X "SLASH", -X "VBAR", -X "AMPER", -X "LESS", -X "GREATER", -X "EQUAL", -X "DOT", -X "PERCENT", -X "BACKQUOTE", -X "LBRACE", -X "RBRACE", -X "OP", -X "<ERRORTOKEN>", -X "<N_TOKENS>" +X "ENDMARKER", +X "NAME", +X "NUMBER", +X "STRING", +X "NEWLINE", +X "INDENT", +X "DEDENT", +X "LPAR", +X "RPAR", +X "LSQB", +X "RSQB", +X "COLON", +X "COMMA", +X "SEMI", +X "PLUS", +X "MINUS", +X "STAR", +X "SLASH", +X "VBAR", +X "AMPER", +X "LESS", +X "GREATER", +X "EQUAL", +X "DOT", +X "PERCENT", +X "BACKQUOTE", +X "LBRACE", +X "RBRACE", +X "OP", +X "<ERRORTOKEN>", +X "<N_TOKENS>" X}; X X @@ -1914,20 +1914,20 @@ X Xstatic struct tok_state * Xtok_new() X{ -X struct tok_state *tok = NEW(struct tok_state, 1); -X if (tok == NULL) -X return NULL; -X tok->buf = tok->cur = tok->end = tok->inp = NULL; -X tok->done = E_OK; -X tok->fp = NULL; -X tok->tabsize = TABSIZE; -X tok->indent = 0; -X tok->indstack[0] = 0; -X tok->atbol = 1; -X tok->pendin = 0; -X tok->prompt = tok->nextprompt = NULL; -X tok->lineno = 0; -X return tok; +X struct tok_state *tok = NEW(struct tok_state, 1); +X if (tok == NULL) +X return NULL; +X tok->buf = tok->cur = tok->end = tok->inp = NULL; +X tok->done = E_OK; +X tok->fp = NULL; +X tok->tabsize = TABSIZE; +X tok->indent = 0; +X tok->indstack[0] = 0; +X tok->atbol = 1; +X tok->pendin = 0; +X tok->prompt = tok->nextprompt = NULL; +X tok->lineno = 0; +X return tok; X} X X @@ -1935,14 +1935,14 @@ X/* Set up tokenizer for string */ X Xstruct tok_state * Xtok_setups(str) -X char *str; +X char *str; X{ -X struct tok_state *tok = tok_new(); -X if (tok == NULL) -X return NULL; -X tok->buf = tok->cur = str; -X tok->end = tok->inp = strchr(str, '\0'); -X return tok; +X struct tok_state *tok = tok_new(); +X if (tok == NULL) +X return NULL; +X tok->buf = tok->cur = str; +X tok->end = tok->inp = strchr(str, '\0'); +X return tok; X} X X @@ -1950,22 +1950,22 @@ X/* Set up tokenizer for string */ X Xstruct tok_state * Xtok_setupf(fp, ps1, ps2) -X FILE *fp; -X char *ps1, *ps2; +X FILE *fp; +X char *ps1, *ps2; X{ -X struct tok_state *tok = tok_new(); -X if (tok == NULL) -X return NULL; -X if ((tok->buf = NEW(char, BUFSIZ)) == NULL) { -X DEL(tok); -X return NULL; -X } -X tok->cur = tok->inp = tok->buf; -X tok->end = tok->buf + BUFSIZ; -X tok->fp = fp; -X tok->prompt = ps1; -X tok->nextprompt = ps2; -X return tok; +X struct tok_state *tok = tok_new(); +X if (tok == NULL) +X return NULL; +X if ((tok->buf = NEW(char, BUFSIZ)) == NULL) { +X DEL(tok); +X return NULL; +X } +X tok->cur = tok->inp = tok->buf; +X tok->end = tok->buf + BUFSIZ; +X tok->fp = fp; +X tok->prompt = ps1; +X tok->nextprompt = ps2; +X return tok; X} X X @@ -1973,12 +1973,12 @@ X/* Free a tok_state structure */ X Xvoid Xtok_free(tok) -X struct tok_state *tok; +X struct tok_state *tok; X{ -X /* XXX really need a separate flag to say 'my buffer' */ -X if (tok->fp != NULL && tok->buf != NULL) -X DEL(tok->buf); -X DEL(tok); +X /* XXX really need a separate flag to say 'my buffer' */ +X if (tok->fp != NULL && tok->buf != NULL) +X DEL(tok->buf); +X DEL(tok); X} X X @@ -1986,89 +1986,89 @@ X/* Get next char, updating state; error code goes into tok->done */ X Xstatic int Xtok_nextc(tok) -X register struct tok_state *tok; +X register struct tok_state *tok; X{ -X if (tok->done != E_OK) -X return EOF; -X -X for (;;) { -X if (tok->cur < tok->inp) -X return *tok->cur++; -X if (tok->fp == NULL) { -X tok->done = E_EOF; -X return EOF; -X } -X if (tok->inp > tok->buf && tok->inp[-1] == '\n') -X tok->inp = tok->buf; -X if (tok->inp == tok->end) { -X int n = tok->end - tok->buf; -X char *new = tok->buf; -X RESIZE(new, char, n+n); -X if (new == NULL) { -X fprintf(stderr, "tokenizer out of mem\n"); -X tok->done = E_NOMEM; -X return EOF; -X } -X tok->buf = new; -X tok->inp = tok->buf + n; -X tok->end = tok->inp + n; -X } +X if (tok->done != E_OK) +X return EOF; +X +X for (;;) { +X if (tok->cur < tok->inp) +X return *tok->cur++; +X if (tok->fp == NULL) { +X tok->done = E_EOF; +X return EOF; +X } +X if (tok->inp > tok->buf && tok->inp[-1] == '\n') +X tok->inp = tok->buf; +X if (tok->inp == tok->end) { +X int n = tok->end - tok->buf; +X char *new = tok->buf; +X RESIZE(new, char, n+n); +X if (new == NULL) { +X fprintf(stderr, "tokenizer out of mem\n"); +X tok->done = E_NOMEM; +X return EOF; +X } +X tok->buf = new; +X tok->inp = tok->buf + n; +X tok->end = tok->inp + n; +X } X#ifdef USE_READLINE -X if (tok->prompt != NULL) { -X extern char *readline PROTO((char *prompt)); -X static int been_here; -X if (!been_here) { -X /* Force rebind of TAB to insert-tab */ -X extern int rl_insert(); -X rl_bind_key('\t', rl_insert); -X been_here++; -X } -X if (tok->buf != NULL) -X free(tok->buf); -X tok->buf = readline(tok->prompt); -X (void) intrcheck(); /* Clear pending interrupt */ -X if (tok->nextprompt != NULL) -X tok->prompt = tok->nextprompt; -X /* XXX different semantics w/o readline()! */ -X if (tok->buf == NULL) { -X tok->done = E_EOF; -X } -X else { -X unsigned int n = strlen(tok->buf); -X if (n > 0) -X add_history(tok->buf); -X /* Append the '\n' that readline() -X doesn't give us, for the tokenizer... */ -X tok->buf = realloc(tok->buf, n+2); -X if (tok->buf == NULL) -X tok->done = E_NOMEM; -X else { -X tok->end = tok->buf + n; -X *tok->end++ = '\n'; -X *tok->end = '\0'; -X tok->inp = tok->end; -X tok->cur = tok->buf; -X } -X } -X } -X else +X if (tok->prompt != NULL) { +X extern char *readline PROTO((char *prompt)); +X static int been_here; +X if (!been_here) { +X /* Force rebind of TAB to insert-tab */ +X extern int rl_insert(); +X rl_bind_key('\t', rl_insert); +X been_here++; +X } +X if (tok->buf != NULL) +X free(tok->buf); +X tok->buf = readline(tok->prompt); +X (void) intrcheck(); /* Clear pending interrupt */ +X if (tok->nextprompt != NULL) +X tok->prompt = tok->nextprompt; +X /* XXX different semantics w/o readline()! */ +X if (tok->buf == NULL) { +X tok->done = E_EOF; +X } +X else { +X unsigned int n = strlen(tok->buf); +X if (n > 0) +X add_history(tok->buf); +X /* Append the '\n' that readline() +X doesn't give us, for the tokenizer... */ +X tok->buf = realloc(tok->buf, n+2); +X if (tok->buf == NULL) +X tok->done = E_NOMEM; +X else { +X tok->end = tok->buf + n; +X *tok->end++ = '\n'; +X *tok->end = '\0'; +X tok->inp = tok->end; +X tok->cur = tok->buf; +X } +X } +X } +X else X#endif -X { -X tok->cur = tok->inp; -X if (tok->prompt != NULL && tok->inp == tok->buf) { -X fprintf(stderr, "%s", tok->prompt); -X tok->prompt = tok->nextprompt; -X } -X tok->done = fgets_intr(tok->inp, -X (int)(tok->end - tok->inp), tok->fp); -X } -X if (tok->done != E_OK) { -X if (tok->prompt != NULL) -X fprintf(stderr, "\n"); -X return EOF; -X } -X tok->inp = strchr(tok->inp, '\0'); -X } +X { +X tok->cur = tok->inp; +X if (tok->prompt != NULL && tok->inp == tok->buf) { +X fprintf(stderr, "%s", tok->prompt); +X tok->prompt = tok->nextprompt; +X } +X tok->done = fgets_intr(tok->inp, +X (int)(tok->end - tok->inp), tok->fp); +X } +X if (tok->done != E_OK) { +X if (tok->prompt != NULL) +X fprintf(stderr, "\n"); +X return EOF; +X } +X tok->inp = strchr(tok->inp, '\0'); +X } X} X X @@ -2076,17 +2076,17 @@ X/* Back-up one character */ X Xstatic void Xtok_backup(tok, c) -X register struct tok_state *tok; -X register int c; +X register struct tok_state *tok; +X register int c; X{ -X if (c != EOF) { -X if (--tok->cur < tok->buf) { -X fprintf(stderr, "tok_backup: begin of buffer\n"); -X abort(); -X } -X if (*tok->cur != c) -X *tok->cur = c; -X } +X if (c != EOF) { +X if (--tok->cur < tok->buf) { +X fprintf(stderr, "tok_backup: begin of buffer\n"); +X abort(); +X } +X if (*tok->cur != c) +X *tok->cur = c; +X } X} X X @@ -2094,32 +2094,32 @@ X/* Return the token corresponding to a single character */ X Xint Xtok_1char(c) -X int c; +X int c; X{ -X switch (c) { -X case '(': return LPAR; -X case ')': return RPAR; -X case '[': return LSQB; -X case ']': return RSQB; -X case ':': return COLON; -X case ',': return COMMA; -X case ';': return SEMI; -X case '+': return PLUS; -X case '-': return MINUS; -X case '*': return STAR; -X case '/': return SLASH; -X case '|': return VBAR; -X case '&': return AMPER; -X case '<': return LESS; -X case '>': return GREATER; -X case '=': return EQUAL; -X case '.': return DOT; -X case '%': return PERCENT; -X case '`': return BACKQUOTE; -X case '{': return LBRACE; -X case '}': return RBRACE; -X default: return OP; -X } +X switch (c) { +X case '(': return LPAR; +X case ')': return RPAR; +X case '[': return LSQB; +X case ']': return RSQB; +X case ':': return COLON; +X case ',': return COMMA; +X case ';': return SEMI; +X case '+': return PLUS; +X case '-': return MINUS; +X case '*': return STAR; +X case '/': return SLASH; +X case '|': return VBAR; +X case '&': return AMPER; +X case '<': return LESS; +X case '>': return GREATER; +X case '=': return EQUAL; +X case '.': return DOT; +X case '%': return PERCENT; +X case '`': return BACKQUOTE; +X case '{': return LBRACE; +X case '}': return RBRACE; +X default: return OP; +X } X} X X @@ -2127,206 +2127,206 @@ X/* Get next token, after space stripping etc. */ X Xint Xtok_get(tok, p_start, p_end) -X register struct tok_state *tok; /* In/out: tokenizer state */ -X char **p_start, **p_end; /* Out: point to start/end of token */ +X register struct tok_state *tok; /* In/out: tokenizer state */ +X char **p_start, **p_end; /* Out: point to start/end of token */ X{ -X register int c; -X -X /* Get indentation level */ -X if (tok->atbol) { -X register int col = 0; -X tok->atbol = 0; -X tok->lineno++; -X for (;;) { -X c = tok_nextc(tok); -X if (c == ' ') -X col++; -X else if (c == '\t') -X col = (col/tok->tabsize + 1) * tok->tabsize; -X else -X break; -X } -X tok_backup(tok, c); -X if (col == tok->indstack[tok->indent]) { -X /* No change */ -X } -X else if (col > tok->indstack[tok->indent]) { -X /* Indent -- always one */ -X if (tok->indent+1 >= MAXINDENT) { -X fprintf(stderr, "excessive indent\n"); -X tok->done = E_TOKEN; -X return ERRORTOKEN; -X } -X tok->pendin++; -X tok->indstack[++tok->indent] = col; -X } -X else /* col < tok->indstack[tok->indent] */ { -X /* Dedent -- any number, must be consistent */ -X while (tok->indent > 0 && -X col < tok->indstack[tok->indent]) { -X tok->indent--; -X tok->pendin--; -X } -X if (col != tok->indstack[tok->indent]) { -X fprintf(stderr, "inconsistent dedent\n"); -X tok->done = E_TOKEN; -X return ERRORTOKEN; -X } -X } -X } -X -X *p_start = *p_end = tok->cur; -X -X /* Return pending indents/dedents */ -X if (tok->pendin != 0) { -X if (tok->pendin < 0) { -X tok->pendin++; -X return DEDENT; -X } -X else { -X tok->pendin--; -X return INDENT; -X } -X } -X +X register int c; +X +X /* Get indentation level */ +X if (tok->atbol) { +X register int col = 0; +X tok->atbol = 0; +X tok->lineno++; +X for (;;) { +X c = tok_nextc(tok); +X if (c == ' ') +X col++; +X else if (c == '\t') +X col = (col/tok->tabsize + 1) * tok->tabsize; +X else +X break; +X } +X tok_backup(tok, c); +X if (col == tok->indstack[tok->indent]) { +X /* No change */ +X } +X else if (col > tok->indstack[tok->indent]) { +X /* Indent -- always one */ +X if (tok->indent+1 >= MAXINDENT) { +X fprintf(stderr, "excessive indent\n"); +X tok->done = E_TOKEN; +X return ERRORTOKEN; +X } +X tok->pendin++; +X tok->indstack[++tok->indent] = col; +X } +X else /* col < tok->indstack[tok->indent] */ { +X /* Dedent -- any number, must be consistent */ +X while (tok->indent > 0 && +X col < tok->indstack[tok->indent]) { +X tok->indent--; +X tok->pendin--; +X } +X if (col != tok->indstack[tok->indent]) { +X fprintf(stderr, "inconsistent dedent\n"); +X tok->done = E_TOKEN; +X return ERRORTOKEN; +X } +X } +X } +X +X *p_start = *p_end = tok->cur; +X +X /* Return pending indents/dedents */ +X if (tok->pendin != 0) { +X if (tok->pendin < 0) { +X tok->pendin++; +X return DEDENT; +X } +X else { +X tok->pendin--; +X return INDENT; +X } +X } +X X again: -X /* Skip spaces */ -X do { -X c = tok_nextc(tok); -X } while (c == ' ' || c == '\t'); -X -X /* Set start of current token */ -X *p_start = tok->cur - 1; -X -X /* Skip comment */ -X if (c == '#') { -X /* Hack to allow overriding the tabsize in the file. -X This is also recognized by vi, when it occurs near the -X beginning or end of the file. (Will vi never die...?) */ -X int x; -X /* XXX The case to (unsigned char *) is needed by THINK C 3.0 */ -X if (sscanf(/*(unsigned char *)*/tok->cur, -X " vi:set tabsize=%d:", &x) == 1 && -X x >= 1 && x <= 40) { -X fprintf(stderr, "# vi:set tabsize=%d:\n", x); -X tok->tabsize = x; -X } -X do { -X c = tok_nextc(tok); -X } while (c != EOF && c != '\n'); -X } -X -X /* Check for EOF and errors now */ -X if (c == EOF) -X return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; -X -X /* Identifier (most frequent token!) */ -X if (isalpha(c) || c == '_') { -X do { -X c = tok_nextc(tok); -X } while (isalnum(c) || c == '_'); -X tok_backup(tok, c); -X *p_end = tok->cur; -X return NAME; -X } -X -X /* Newline */ -X if (c == '\n') { -X tok->atbol = 1; -X *p_end = tok->cur - 1; /* Leave '\n' out of the string */ -X return NEWLINE; -X } -X -X /* Number */ -X if (isdigit(c)) { -X if (c == '0') { -X /* Hex or octal */ -X c = tok_nextc(tok); -X if (c == '.') -X goto fraction; -X if (c == 'x' || c == 'X') { -X /* Hex */ -X do { -X c = tok_nextc(tok); -X } while (isxdigit(c)); -X } -X else { -X /* Octal; c is first char of it */ -X /* There's no 'isoctdigit' macro, sigh */ -X while ('0' <= c && c < '8') { -X c = tok_nextc(tok); -X } -X } -X } -X else { -X /* Decimal */ -X do { -X c = tok_nextc(tok); -X } while (isdigit(c)); -X /* Accept floating point numbers. -X XXX This accepts incomplete things like 12e or 1e+; -X worry about that at run-time. -X XXX Doesn't accept numbers starting with a dot */ -X if (c == '.') { -X fraction: -X /* Fraction */ -X do { -X c = tok_nextc(tok); -X } while (isdigit(c)); -X } -X if (c == 'e' || c == 'E') { -X /* Exponent part */ -X c = tok_nextc(tok); -X if (c == '+' || c == '-') -X c = tok_nextc(tok); -X while (isdigit(c)) { -X c = tok_nextc(tok); -X } -X } -X } -X tok_backup(tok, c); -X *p_end = tok->cur; -X return NUMBER; -X } -X -X /* String */ -X if (c == '\'') { -X for (;;) { -X c = tok_nextc(tok); -X if (c == '\n' || c == EOF) { -X tok->done = E_TOKEN; -X return ERRORTOKEN; -X } -X if (c == '\\') { -X c = tok_nextc(tok); -X *p_end = tok->cur; -X if (c == '\n' || c == EOF) { -X tok->done = E_TOKEN; -X return ERRORTOKEN; -X } -X continue; -X } -X if (c == '\'') -X break; -X } -X *p_end = tok->cur; -X return STRING; -X } -X -X /* Line continuation */ -X if (c == '\\') { -X c = tok_nextc(tok); -X if (c != '\n') { -X tok->done = E_TOKEN; -X return ERRORTOKEN; -X } -X tok->lineno++; -X goto again; /* Read next line */ -X } -X -X /* Punctuation character */ -X *p_end = tok->cur; -X return tok_1char(c); +X /* Skip spaces */ +X do { +X c = tok_nextc(tok); +X } while (c == ' ' || c == '\t'); +X +X /* Set start of current token */ +X *p_start = tok->cur - 1; +X +X /* Skip comment */ +X if (c == '#') { +X /* Hack to allow overriding the tabsize in the file. +X This is also recognized by vi, when it occurs near the +X beginning or end of the file. (Will vi never die...?) */ +X int x; +X /* XXX The case to (unsigned char *) is needed by THINK C 3.0 */ +X if (sscanf(/*(unsigned char *)*/tok->cur, +X " vi:set tabsize=%d:", &x) == 1 && +X x >= 1 && x <= 40) { +X fprintf(stderr, "# vi:set tabsize=%d:\n", x); +X tok->tabsize = x; +X } +X do { +X c = tok_nextc(tok); +X } while (c != EOF && c != '\n'); +X } +X +X /* Check for EOF and errors now */ +X if (c == EOF) +X return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; +X +X /* Identifier (most frequent token!) */ +X if (isalpha(c) || c == '_') { +X do { +X c = tok_nextc(tok); +X } while (isalnum(c) || c == '_'); +X tok_backup(tok, c); +X *p_end = tok->cur; +X return NAME; +X } +X +X /* Newline */ +X if (c == '\n') { +X tok->atbol = 1; +X *p_end = tok->cur - 1; /* Leave '\n' out of the string */ +X return NEWLINE; +X } +X +X /* Number */ +X if (isdigit(c)) { +X if (c == '0') { +X /* Hex or octal */ +X c = tok_nextc(tok); +X if (c == '.') +X goto fraction; +X if (c == 'x' || c == 'X') { +X /* Hex */ +X do { +X c = tok_nextc(tok); +X } while (isxdigit(c)); +X } +X else { +X /* Octal; c is first char of it */ +X /* There's no 'isoctdigit' macro, sigh */ +X while ('0' <= c && c < '8') { +X c = tok_nextc(tok); +X } +X } +X } +X else { +X /* Decimal */ +X do { +X c = tok_nextc(tok); +X } while (isdigit(c)); +X /* Accept floating point numbers. +X XXX This accepts incomplete things like 12e or 1e+; +X worry about that at run-time. +X XXX Doesn't accept numbers starting with a dot */ +X if (c == '.') { +X fraction: +X /* Fraction */ +X do { +X c = tok_nextc(tok); +X } while (isdigit(c)); +X } +X if (c == 'e' || c == 'E') { +X /* Exponent part */ +X c = tok_nextc(tok); +X if (c == '+' || c == '-') +X c = tok_nextc(tok); +X while (isdigit(c)) { +X c = tok_nextc(tok); +X } +X } +X } +X tok_backup(tok, c); +X *p_end = tok->cur; +X return NUMBER; +X } +X +X /* String */ +X if (c == '\'') { +X for (;;) { +X c = tok_nextc(tok); +X if (c == '\n' || c == EOF) { +X tok->done = E_TOKEN; +X return ERRORTOKEN; +X } +X if (c == '\\') { +X c = tok_nextc(tok); +X *p_end = tok->cur; +X if (c == '\n' || c == EOF) { +X tok->done = E_TOKEN; +X return ERRORTOKEN; +X } +X continue; +X } +X if (c == '\'') +X break; +X } +X *p_end = tok->cur; +X return STRING; +X } +X +X /* Line continuation */ +X if (c == '\\') { +X c = tok_nextc(tok); +X if (c != '\n') { +X tok->done = E_TOKEN; +X return ERRORTOKEN; +X } +X tok->lineno++; +X goto again; /* Read next line */ +X } +X +X /* Punctuation character */ +X *p_end = tok->cur; +X return tok_1char(c); X} X X @@ -2334,16 +2334,16 @@ X#ifdef DEBUG X Xvoid Xtok_dump(type, start, end) -X int type; -X char *start, *end; +X int type; +X char *start, *end; X{ -X printf("%s", tok_name[type]); -X if (type == NAME || type == NUMBER || type == STRING || type == OP) -X printf("(%.*s)", (int)(end - start), start); +X printf("%s", tok_name[type]); +X if (type == NAME || type == NUMBER || type == STRING || type == OP) +X printf("(%.*s)", (int)(end - start), start); X} X X#endif EOF fi echo 'Part 08 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-09-21.shar b/shar/python-0.9.1-09-21.shar index 0aee04d..7638cf4 100644 --- a/shar/python-0.9.1-09-21.shar +++ b/shar/python-0.9.1-09-21.shar @@ -29,7 +29,7 @@ X\funcitem{hexdigits} XThe string X{\tt '0123456789abcdefABCDEF'}. X\funcitem{letters} -XThe concatenation of the strings +XThe concatenation of the strings X{\tt lowercase} Xand X{\tt uppercase} @@ -109,7 +109,7 @@ X\funcitem{swapcase}{s} XConverts lower case letters to upper case and vice versa. X\funcitem{upper}{s} XConvert letters to upper case. -X\funcitem{ljust(s, width), rjust(s, width), center}{s, width} +X\funcitem{ljust(s, width), rjust(s, width), center}{s, width} X%.br XThese functions respectively left-justify, right-justify and center a Xstring in a field of given width. @@ -262,7 +262,7 @@ X>>> optlist X[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] X>>> args X['a1', 'a2'] -X>>> +X>>> X\end{verbatim}\ecode XThe exception X{\tt getopt.error = 'getopt error'} @@ -315,7 +315,7 @@ XRead the file for details. XSuggested usage is X\bcode\begin{verbatim} X>>> from stdwinevents import * -X>>> +X>>> X\end{verbatim}\ecode X X\subsection{Standard Module {\tt rect}} @@ -352,7 +352,7 @@ X>>> r2 = (0, 0), (10, 20) X>>> r3 = rect.intersect(r1, r2) X>>> if r3 is rect.empty: print 'Empty intersection' XEmpty intersection -X>>> +X>>> X\end{verbatim}\ecode X\funcitem{is\_empty}{r} X%.br @@ -503,12 +503,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -539,12 +539,12 @@ X Xstatic int Xinit() X{ -X if (audio_fd >= 0) -X return 1; -X if ((audio_fd = asa_init()) >= 0) -X return 1; -X err_setstr(RuntimeError, "can't initialize async audio"); -X return 0; +X if (audio_fd >= 0) +X return 1; +X if ((audio_fd = asa_init()) >= 0) +X return 1; +X err_setstr(RuntimeError, "can't initialize async audio"); +X return 0; X} X X @@ -552,567 +552,567 @@ X/* POSIX methods */ X Xstatic object * Xaudio_get_ioctl(self, args, code) -X object *self; -X object *args; -X long code; +X object *self; +X object *args; +X long code; X{ -X long x; -X if (!getnoarg(args)) -X return NULL; -X if (!init()) -X return NULL; -X if ((x = ioctl(audio_fd, code, (char *) NULL)) < 0) { -X return NULL; -X } -X return newintobject(x); +X long x; +X if (!getnoarg(args)) +X return NULL; +X if (!init()) +X return NULL; +X if ((x = ioctl(audio_fd, code, (char *) NULL)) < 0) { +X return NULL; +X } +X return newintobject(x); X} X Xstatic object * Xaudio_set_ioctl(self, args, code) -X object *self; -X object *args; -X long code; +X object *self; +X object *args; +X long code; X{ -X long x; -X if (!getlongarg(args, &x)) -X return NULL; -X if (!init()) -X return NULL; -X if (ioctl(audio_fd, code, (char *) x) != 0) -X return NULL; -X INCREF(None); -X return None; +X long x; +X if (!getlongarg(args, &x)) +X return NULL; +X if (!init()) +X return NULL; +X if (ioctl(audio_fd, code, (char *) x) != 0) +X return NULL; +X INCREF(None); +X return None; X} X Xstatic object * Xaudio_getingain(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return audio_get_ioctl(self, args, AUDIOCGETINGAIN); +X return audio_get_ioctl(self, args, AUDIOCGETINGAIN); X} X Xstatic object * Xaudio_getoutgain(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return audio_get_ioctl(self, args, AUDIOCGETOUTGAIN); +X return audio_get_ioctl(self, args, AUDIOCGETOUTGAIN); X} X Xstatic object * Xaudio_setingain(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return audio_set_ioctl(self, args, AUDIOCSETINGAIN); +X return audio_set_ioctl(self, args, AUDIOCSETINGAIN); X} X Xstatic object * Xaudio_setoutgain(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return audio_set_ioctl(self, args, AUDIOCSETOUTGAIN); +X return audio_set_ioctl(self, args, AUDIOCSETOUTGAIN); X} X Xstatic object * Xaudio_setrate(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return audio_set_ioctl(self, args, AUDIOCSETRATE); +X return audio_set_ioctl(self, args, AUDIOCSETRATE); X} X Xstatic object * Xaudio_setduration(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X return audio_set_ioctl(self, args, AUDIOCDURATION); +X return audio_set_ioctl(self, args, AUDIOCDURATION); X} X X/* Compute average bias, and remove it */ X Xstatic void Xunbias(buf, len) -X char *buf; -X int len; -X{ -X register int i; -X register int c; -X register long bias; -X if (len == 0) -X return; -X bias = 0; -X for (i = 0; i < len; i++) { -X c = buf[i]; -X if (c > 127) -X c -= 256; -X bias += c; -X } -X bias = (bias + len/2) / len; /* Rounded average */ -X if (bias != 0) { -X for (i = 0; i < len; i++) { -X buf[i] -= bias; -X } -X } +X char *buf; +X int len; +X{ +X register int i; +X register int c; +X register long bias; +X if (len == 0) +X return; +X bias = 0; +X for (i = 0; i < len; i++) { +X c = buf[i]; +X if (c > 127) +X c -= 256; +X bias += c; +X } +X bias = (bias + len/2) / len; /* Rounded average */ +X if (bias != 0) { +X for (i = 0; i < len; i++) { +X buf[i] -= bias; +X } +X } X} X Xstatic object * Xaudio_read(self, args) -X object *self; -X object *args; -X{ -X int c, i, n; -X object *v; -X char *s; -X if (!getintarg(args, &n)) -X return NULL; -X if (n <= 0) { -X err_setstr(RuntimeError, "audio.read: arg <= 0"); -X return NULL; -X } -X if (!init()) -X return NULL; -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return err_nomem(); -X s = getstringvalue(v); -X n = read(audio_fd, s, n); -X if (intrcheck()) { -X DECREF(v); -X err_set(KeyboardInterrupt); -X return NULL; -X } -X /* Check for errors */ -X if (n < 0) { -X DECREF(v); -X return NULL; -X } -X /* But EOF is reported as an empty string */ -X -X unbias(s, n); -X resizestring(&v, n); -X return v; +X object *self; +X object *args; +X{ +X int c, i, n; +X object *v; +X char *s; +X if (!getintarg(args, &n)) +X return NULL; +X if (n <= 0) { +X err_setstr(RuntimeError, "audio.read: arg <= 0"); +X return NULL; +X } +X if (!init()) +X return NULL; +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return err_nomem(); +X s = getstringvalue(v); +X n = read(audio_fd, s, n); +X if (intrcheck()) { +X DECREF(v); +X err_set(KeyboardInterrupt); +X return NULL; +X } +X /* Check for errors */ +X if (n < 0) { +X DECREF(v); +X return NULL; +X } +X /* But EOF is reported as an empty string */ +X +X unbias(s, n); +X resizestring(&v, n); +X return v; X} X Xstatic object * Xaudio_write(self, args) -X object *self; -X object *args; -X{ -X int n, n2; -X object *v; -X if (!getstrarg(args, &v)) -X return NULL; -X if (!init()) -X return NULL; -X errno = 0; -X n2 = write(audio_fd, getstringvalue(v), n = getstringsize(v)); -X if (intrcheck()) { -X err_set(KeyboardInterrupt); -X return NULL; -X } -X /* Check for other errors */ -X if (n2 != n) { -X if (errno == 0) -X errno = EIO; -X return NULL; -X } -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X int n, n2; +X object *v; +X if (!getstrarg(args, &v)) +X return NULL; +X if (!init()) +X return NULL; +X errno = 0; +X n2 = write(audio_fd, getstringvalue(v), n = getstringsize(v)); +X if (intrcheck()) { +X err_set(KeyboardInterrupt); +X return NULL; +X } +X /* Check for other errors */ +X if (n2 != n) { +X if (errno == 0) +X errno = EIO; +X return NULL; +X } +X INCREF(None); +X return None; X} X X/* audio.amplify(sample, f1, f2). -X Amplify a sample by a factor changing from f1/256 to (almost) f2/256. -X Negative factors are allowed. Sound values that are to large -X to fit in a byte are clipped. */ +X Amplify a sample by a factor changing from f1/256 to (almost) f2/256. +X Negative factors are allowed. Sound values that are to large +X to fit in a byte are clipped. */ X Xstatic object * Xaudio_amplify(self, args) -X object *self; -X object *args; -X{ -X object *v; -X char *s, *t; -X int f1, f2; -X int i, n; -X int c; -X if (!getstrintintarg(args, &v, &f1, &f2)) -X return NULL; -X n = getstringsize(v); -X s = getstringvalue(v); -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return err_nomem(); -X t = getstringvalue(v); -X for (i = 0; i < n; i++) { -X c = s[i]; -X if (c > 127) c -= 256; /* If chars are unsigned */ -X c = c * ( f1*(n-i) + f2*i ) / ( n*256 ); -X if (c > 127) c = 127; -X else if (c < -128) c = -128; -X t[i] = c; -X } -X return v; +X object *self; +X object *args; +X{ +X object *v; +X char *s, *t; +X int f1, f2; +X int i, n; +X int c; +X if (!getstrintintarg(args, &v, &f1, &f2)) +X return NULL; +X n = getstringsize(v); +X s = getstringvalue(v); +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return err_nomem(); +X t = getstringvalue(v); +X for (i = 0; i < n; i++) { +X c = s[i]; +X if (c > 127) c -= 256; /* If chars are unsigned */ +X c = c * ( f1*(n-i) + f2*i ) / ( n*256 ); +X if (c > 127) c = 127; +X else if (c < -128) c = -128; +X t[i] = c; +X } +X return v; X} X X/* audio.reverse(s): return a sample backwards */ X Xstatic object * Xaudio_reverse(self, args) -X object *self; -X object *args; -X{ -X object *v; -X char *s, *t; -X int i, n; -X if (!getstrarg(args, &v)) -X return NULL; -X n = getstringsize(v); -X s = getstringvalue(v); -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return err_nomem(); -X t = getstringvalue(v); -X for (i = 0; i < n; i++) { -X t[n-1-i] = s[i]; -X } -X return v; +X object *self; +X object *args; +X{ +X object *v; +X char *s, *t; +X int i, n; +X if (!getstrarg(args, &v)) +X return NULL; +X n = getstringsize(v); +X s = getstringvalue(v); +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return err_nomem(); +X t = getstringvalue(v); +X for (i = 0; i < n; i++) { +X t[n-1-i] = s[i]; +X } +X return v; X} X X/* audio.add(a, b): add two samples. -X Bytes that exceed the range are clipped. -X If one is shorter, the rest of the longer sample is returned unchanged. */ +X Bytes that exceed the range are clipped. +X If one is shorter, the rest of the longer sample is returned unchanged. */ X Xstatic object * Xaudio_add(self, args) -X object *self; -X object *args; -X{ -X object *a, *b, *v; -X char *sa, *sb, *t; -X int i, n, na, nb, c, ca, cb; -X if (!getstrstrarg(args, &a, &b)) -X return NULL; -X na = getstringsize(a); -X sa = getstringvalue(a); -X nb = getstringsize(b); -X sb = getstringvalue(b); -X n = (na > nb) ? na : nb; -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return err_nomem(); -X t = getstringvalue(v); -X for (i = 0; i < n; i++) { -X c = 0; -X if (i < na) { -X ca = sa[i]; -X if (ca > 127) ca = ca - 256; -X c = c + ca; -X } -X if (i < nb) { -X cb = sb[i]; -X if (cb > 127) cb = cb - 256; -X c = c + cb; -X } -X if (c > 127) c = 127; -X else if (c < -128) c = -128; -X t[i] = c; -X } -X return v; +X object *self; +X object *args; +X{ +X object *a, *b, *v; +X char *sa, *sb, *t; +X int i, n, na, nb, c, ca, cb; +X if (!getstrstrarg(args, &a, &b)) +X return NULL; +X na = getstringsize(a); +X sa = getstringvalue(a); +X nb = getstringsize(b); +X sb = getstringvalue(b); +X n = (na > nb) ? na : nb; +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return err_nomem(); +X t = getstringvalue(v); +X for (i = 0; i < n; i++) { +X c = 0; +X if (i < na) { +X ca = sa[i]; +X if (ca > 127) ca = ca - 256; +X c = c + ca; +X } +X if (i < nb) { +X cb = sb[i]; +X if (cb > 127) cb = cb - 256; +X c = c + cb; +X } +X if (c > 127) c = 127; +X else if (c < -128) c = -128; +X t[i] = c; +X } +X return v; X} X X/* audio.chr2num(s) returns a list containing the numeric values -X of the samples. */ +X of the samples. */ X Xstatic object * Xaudio_chr2num(self, args) -X object *self; -X object *args; -X{ -X object *v, *w; -X char *s; -X int c, i, n; -X static object *ints[256]; -X -X /* To avoid filling memory with all those int objects, we create -X integer objects for all the desired values and reference these. */ -X if (ints[255] == NULL) { -X for (i = 0; i < 256; i++) { -X if (ints[i] != NULL) -X continue; -X c = i; -X if (c > 127) c -= 256; -X ints[i] = newintobject((long)c); -X if (ints[i] == NULL) -X return NULL; -X } -X } -X -X if (!getstrarg(args, &v)) -X return NULL; -X n = getstringsize(v); -X s = getstringvalue(v); -X v = newlistobject(n); -X if (v == NULL) -X return err_nomem(); -X for (i = 0; i < n; i++) { -X c = s[i] & 0xff; -X w = ints[c]; -X INCREF(w); -X if (setlistitem(v, i, w) != 0) { -X DECREF(v); -X return NULL; -X } -X } -X return v; +X object *self; +X object *args; +X{ +X object *v, *w; +X char *s; +X int c, i, n; +X static object *ints[256]; +X +X /* To avoid filling memory with all those int objects, we create +X integer objects for all the desired values and reference these. */ +X if (ints[255] == NULL) { +X for (i = 0; i < 256; i++) { +X if (ints[i] != NULL) +X continue; +X c = i; +X if (c > 127) c -= 256; +X ints[i] = newintobject((long)c); +X if (ints[i] == NULL) +X return NULL; +X } +X } +X +X if (!getstrarg(args, &v)) +X return NULL; +X n = getstringsize(v); +X s = getstringvalue(v); +X v = newlistobject(n); +X if (v == NULL) +X return err_nomem(); +X for (i = 0; i < n; i++) { +X c = s[i] & 0xff; +X w = ints[c]; +X INCREF(w); +X if (setlistitem(v, i, w) != 0) { +X DECREF(v); +X return NULL; +X } +X } +X return v; X} X X/* audio.num2chr is the inverse of audio.chr2num. -X Excess values are clipped. */ +X Excess values are clipped. */ X Xstatic object * Xaudio_num2chr(self, args) -X object *self; -X object *args; -X{ -X object *v, *w; -X char *s; -X int c, i, n; -X if (!is_listobject(args)) { -X err_badarg(); -X return NULL; -X } -X n = getlistsize(args); -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return NULL; -X s = getstringvalue(v); -X for (i = 0; i < n; i++) { -X w = getlistitem(args, i); -X if (!is_intobject(w)) { -X DECREF(v); -X err_badarg(); -X return NULL; -X } -X s[i] = getintvalue(w); -X } -X return v; +X object *self; +X object *args; +X{ +X object *v, *w; +X char *s; +X int c, i, n; +X if (!is_listobject(args)) { +X err_badarg(); +X return NULL; +X } +X n = getlistsize(args); +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return NULL; +X s = getstringvalue(v); +X for (i = 0; i < n; i++) { +X w = getlistitem(args, i); +X if (!is_intobject(w)) { +X DECREF(v); +X err_badarg(); +X return NULL; +X } +X s[i] = getintvalue(w); +X } +X return v; X} X Xstatic object *stdaudio_buffer = NULL; X Xstatic object * Xaudio_start_recording(self, args) -X object *self; -X object *args; -X{ -X int n; -X object *v; -X char *s; -X if (!getintarg(args, &n)) -X return NULL; -X if (stdaudio_buffer != NULL) { -X err_setstr(RuntimeError, "audio.start_recording: device busy"); -X return NULL; -X } -X if (n <= 0) { -X err_setstr(TypeError, "audio.start_recording: arg <= 0"); -X return NULL; -X } -X if (!init()) -X return NULL; -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return err_nomem(); -X s = getstringvalue(v); -X asa_start_read(s, n); -X stdaudio_buffer = v; -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X int n; +X object *v; +X char *s; +X if (!getintarg(args, &n)) +X return NULL; +X if (stdaudio_buffer != NULL) { +X err_setstr(RuntimeError, "audio.start_recording: device busy"); +X return NULL; +X } +X if (n <= 0) { +X err_setstr(TypeError, "audio.start_recording: arg <= 0"); +X return NULL; +X } +X if (!init()) +X return NULL; +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return err_nomem(); +X s = getstringvalue(v); +X asa_start_read(s, n); +X stdaudio_buffer = v; +X INCREF(None); +X return None; X} X Xstatic object * Xaudio_poll(self, args) -X object *self; -X object *args; -X{ -X int n; -X if (!getnoarg(args)) -X return NULL; -X if (stdaudio_buffer == NULL) { -X err_setstr(RuntimeError, "audio.poll: not busy"); -X return NULL; -X } -X if (!init()) -X return NULL; -X if ((n = asa_poll()) < 0) -X return NULL; -X return newintobject(n); +X object *self; +X object *args; +X{ +X int n; +X if (!getnoarg(args)) +X return NULL; +X if (stdaudio_buffer == NULL) { +X err_setstr(RuntimeError, "audio.poll: not busy"); +X return NULL; +X } +X if (!init()) +X return NULL; +X if ((n = asa_poll()) < 0) +X return NULL; +X return newintobject(n); X} X Xstatic object * Xaudio_wait_recording(self, args) -X object *self; -X object *args; -X{ -X object *v; -X int n; -X if (!getnoarg(args)) -X return NULL; -X if (stdaudio_buffer == NULL) { -X err_setstr(RuntimeError, "audio.wait_recording: not busy"); -X return NULL; -X } -X if (!init()) -X return NULL; -X if ((n = asa_wait()) < 0) -X return NULL; -X v = stdaudio_buffer; -X stdaudio_buffer = NULL; -X unbias(getstringvalue(v), n); -X resizestring(&v, n); -X return v; +X object *self; +X object *args; +X{ +X object *v; +X int n; +X if (!getnoarg(args)) +X return NULL; +X if (stdaudio_buffer == NULL) { +X err_setstr(RuntimeError, "audio.wait_recording: not busy"); +X return NULL; +X } +X if (!init()) +X return NULL; +X if ((n = asa_wait()) < 0) +X return NULL; +X v = stdaudio_buffer; +X stdaudio_buffer = NULL; +X unbias(getstringvalue(v), n); +X resizestring(&v, n); +X return v; X} X Xstatic object * Xaudio_stop_recording(self, args) -X object *self; -X object *args; -X{ -X int n; -X object *v; -X char *s; -X if (!getnoarg(args)) -X return NULL; -X if (stdaudio_buffer == NULL) { -X err_setstr(RuntimeError, "audio.stop_recording: not busy"); -X return NULL; -X } -X if ((n = asa_cancel()) < 0) -X return NULL; -X v = stdaudio_buffer; -X stdaudio_buffer = NULL; -X s = getstringvalue(v); -X unbias(s, n); -X resizestring(&v, n); -X return v; +X object *self; +X object *args; +X{ +X int n; +X object *v; +X char *s; +X if (!getnoarg(args)) +X return NULL; +X if (stdaudio_buffer == NULL) { +X err_setstr(RuntimeError, "audio.stop_recording: not busy"); +X return NULL; +X } +X if ((n = asa_cancel()) < 0) +X return NULL; +X v = stdaudio_buffer; +X stdaudio_buffer = NULL; +X s = getstringvalue(v); +X unbias(s, n); +X resizestring(&v, n); +X return v; X} X Xstatic object * Xaudio_start_playing(self, args) -X object *self; -X object *args; -X{ -X object *v; -X if (!getstrarg(args, &v)) -X return NULL; -X if (stdaudio_buffer != NULL) { -X err_setstr(RuntimeError, "audio.start_recording: device rbusy"); -X return NULL; -X } -X asa_start_write(getstringvalue(v), (int)getstringsize(v)); -X INCREF(v); -X stdaudio_buffer = v; -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X object *v; +X if (!getstrarg(args, &v)) +X return NULL; +X if (stdaudio_buffer != NULL) { +X err_setstr(RuntimeError, "audio.start_recording: device rbusy"); +X return NULL; +X } +X asa_start_write(getstringvalue(v), (int)getstringsize(v)); +X INCREF(v); +X stdaudio_buffer = v; +X INCREF(None); +X return None; X} X Xstatic object * Xaudio_wait_playing(self, args) -X object *self; -X object *args; -X{ -X int n; -X if (!getnoarg(args)) -X return NULL; -X if (stdaudio_buffer == NULL) { -X err_setstr(RuntimeError, "audio.wait_playing: not busy"); -X return NULL; -X } -X if ((n = asa_wait()) < 0) -X return NULL; -X DECREF(stdaudio_buffer); -X stdaudio_buffer = NULL; -X /* XXX return newintobject((long)n); ??? */ -X INCREF(None); -X return None; +X object *self; +X object *args; +X{ +X int n; +X if (!getnoarg(args)) +X return NULL; +X if (stdaudio_buffer == NULL) { +X err_setstr(RuntimeError, "audio.wait_playing: not busy"); +X return NULL; +X } +X if ((n = asa_wait()) < 0) +X return NULL; +X DECREF(stdaudio_buffer); +X stdaudio_buffer = NULL; +X /* XXX return newintobject((long)n); ??? */ +X INCREF(None); +X return None; X} X Xstatic object * Xaudio_stop_playing(self, args) -X object *self; -X object *args; -X{ -X int n; -X if (!getnoarg(args)) -X return NULL; -X if (stdaudio_buffer == NULL) { -X err_setstr(RuntimeError, "audio.stop_playing: not busy"); -X return NULL; -X } -X if ((n = asa_cancel()) < 0) -X return NULL; -X DECREF(stdaudio_buffer); -X stdaudio_buffer = NULL; -X return newintobject((long)n); +X object *self; +X object *args; +X{ +X int n; +X if (!getnoarg(args)) +X return NULL; +X if (stdaudio_buffer == NULL) { +X err_setstr(RuntimeError, "audio.stop_playing: not busy"); +X return NULL; +X } +X if ((n = asa_cancel()) < 0) +X return NULL; +X DECREF(stdaudio_buffer); +X stdaudio_buffer = NULL; +X return newintobject((long)n); X} X Xstatic object * Xaudio_audio_done(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X asa_done(); -X if (stdaudio_buffer != NULL) -X DECREF(stdaudio_buffer); -X stdaudio_buffer = NULL; -X audio_fd = -1; -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X asa_done(); +X if (stdaudio_buffer != NULL) +X DECREF(stdaudio_buffer); +X stdaudio_buffer = NULL; +X audio_fd = -1; +X INCREF(None); +X return None; X} X X Xstatic struct methodlist audio_methods[] = { -X {"getingain", audio_getingain}, -X {"getoutgain", audio_getoutgain}, -X {"setingain", audio_setingain}, -X {"setoutgain", audio_setoutgain}, -X {"setrate", audio_setrate}, -X {"setduration", audio_setduration}, -X {"read", audio_read}, -X {"write", audio_write}, -X {"amplify", audio_amplify}, -X {"reverse", audio_reverse}, -X {"add", audio_add}, -X {"chr2num", audio_chr2num}, -X {"num2chr", audio_num2chr}, -X -X /* "asa" interface: */ -X -X {"start_recording", audio_start_recording}, -X {"poll_recording", audio_poll}, -X {"wait_recording", audio_wait_recording}, -X {"stop_recording", audio_stop_recording}, -X -X {"start_playing", audio_start_playing}, -X {"poll_playing", audio_poll}, -X {"wait_playing", audio_wait_playing}, -X {"stop_playing", audio_stop_playing}, -X -X {"done", audio_audio_done}, -X -X {NULL, NULL} /* Sentinel */ +X {"getingain", audio_getingain}, +X {"getoutgain", audio_getoutgain}, +X {"setingain", audio_setingain}, +X {"setoutgain", audio_setoutgain}, +X {"setrate", audio_setrate}, +X {"setduration", audio_setduration}, +X {"read", audio_read}, +X {"write", audio_write}, +X {"amplify", audio_amplify}, +X {"reverse", audio_reverse}, +X {"add", audio_add}, +X {"chr2num", audio_chr2num}, +X {"num2chr", audio_num2chr}, +X +X /* "asa" interface: */ +X +X {"start_recording", audio_start_recording}, +X {"poll_recording", audio_poll}, +X {"wait_recording", audio_wait_recording}, +X {"stop_recording", audio_stop_recording}, +X +X {"start_playing", audio_start_playing}, +X {"poll_playing", audio_poll}, +X {"wait_playing", audio_wait_playing}, +X {"stop_playing", audio_stop_playing}, +X +X {"done", audio_audio_done}, +X +X {NULL, NULL} /* Sentinel */ X}; X Xvoid Xinitaudio() X{ -X initmodule("audio", audio_methods); +X initmodule("audio", audio_methods); X} EOF fi @@ -1125,12 +1125,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1155,7 +1155,7 @@ X- uses chaining instead of hashed linear probing X- remembers the hash value with the entry to speed up table resizing X- sets the table size to a power of 2 X- uses a different hash function: -X h = 0; p = str; while (*p) h = (h<<5) - h + *p++; +X h = 0; p = str; while (*p) h = (h<<5) - h + *p++; X*/ X X#include "allobjects.h" @@ -1171,10 +1171,10 @@ Xof that many entries to fail (if none of the earlier values cause such Xfailure already). X*/ Xstatic unsigned int primes[] = { -X 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2017, 4093, -X 5987, -X 9551, 15683, 19609, 31397, -X 0xffffffff /* All bits set -- truncation OK */ +X 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2017, 4093, +X 5987, +X 9551, 15683, 19609, 31397, +X 0xffffffff /* All bits set -- truncation OK */ X}; X X/* String used as dummy key to fill deleted entries */ @@ -1183,12 +1183,12 @@ X X/* XInvariant for entries: when in use, de_value is not NULL and de_key is Xnot NULL and not dummy; when not in use, de_value is NULL and de_key -Xis either NULL or dummy. A dummy key value cannot be replaced by NULL, +Xis either NULL or dummy. A dummy key value cannot be replaced by NULL, Xsince otherwise other keys may be lost. X*/ Xtypedef struct { -X stringobject *de_key; -X object *de_value; +X stringobject *de_key; +X object *de_value; X} dictentry; X X/* @@ -1200,34 +1200,34 @@ XTo avoid slowing down lookups on a near-full table, we resize the table Xwhen it is more than half filled. X*/ Xtypedef struct { -X OB_HEAD -X int di_fill; -X int di_used; -X int di_size; -X dictentry *di_table; +X OB_HEAD +X int di_fill; +X int di_used; +X int di_size; +X dictentry *di_table; X} dictobject; X Xobject * Xnewdictobject() X{ -X register dictobject *dp; -X if (dummy == NULL) { /* Auto-initialize dummy */ -X dummy = (stringobject *) newstringobject(""); -X if (dummy == NULL) -X return NULL; -X } -X dp = NEWOBJ(dictobject, &Dicttype); -X if (dp == NULL) -X return NULL; -X dp->di_size = primes[0]; -X dp->di_table = (dictentry *) calloc(sizeof(dictentry), dp->di_size); -X if (dp->di_table == NULL) { -X DEL(dp); -X return err_nomem(); -X } -X dp->di_fill = 0; -X dp->di_used = 0; -X return (object *)dp; +X register dictobject *dp; +X if (dummy == NULL) { /* Auto-initialize dummy */ +X dummy = (stringobject *) newstringobject(""); +X if (dummy == NULL) +X return NULL; +X } +X dp = NEWOBJ(dictobject, &Dicttype); +X if (dp == NULL) +X return NULL; +X dp->di_size = primes[0]; +X dp->di_table = (dictentry *) calloc(sizeof(dictentry), dp->di_size); +X if (dp->di_table == NULL) { +X DEL(dp); +X return err_nomem(); +X } +X dp->di_fill = 0; +X dp->di_used = 0; +X return (object *)dp; X} X X/* @@ -1245,44 +1245,44 @@ XThe initial probe index is then computed as sum mod the table size. XSubsequent probe indices are incr apart (mod table size), where incr Xis also derived from sum, with the additional requirement that it is Xrelative prime to the table size (i.e., 1 <= incr < size, since the size -Xis a prime number). My choice for incr is somewhat arbitrary. +Xis a prime number). My choice for incr is somewhat arbitrary. X*/ Xstatic dictentry *lookdict PROTO((dictobject *, char *)); Xstatic dictentry * Xlookdict(dp, key) -X register dictobject *dp; -X char *key; -X{ -X register int i, incr; -X register dictentry *freeslot = NULL; -X register unsigned char *p = (unsigned char *) key; -X register unsigned long sum = *p << 7; -X while (*p != '\0') -X sum = sum + sum + *p++; -X i = sum % dp->di_size; -X do { -X sum = sum + sum + 1; -X incr = sum % dp->di_size; -X } while (incr == 0); -X for (;;) { -X register dictentry *ep = &dp->di_table[i]; -X if (ep->de_key == NULL) { -X if (freeslot != NULL) -X return freeslot; -X else -X return ep; -X } -X if (ep->de_key == dummy) { -X if (freeslot != NULL) -X freeslot = ep; -X } -X else if (GETSTRINGVALUE(ep->de_key)[0] == key[0]) { -X if (strcmp(GETSTRINGVALUE(ep->de_key), key) == 0) { -X return ep; -X } -X } -X i = (i + incr) % dp->di_size; -X } +X register dictobject *dp; +X char *key; +X{ +X register int i, incr; +X register dictentry *freeslot = NULL; +X register unsigned char *p = (unsigned char *) key; +X register unsigned long sum = *p << 7; +X while (*p != '\0') +X sum = sum + sum + *p++; +X i = sum % dp->di_size; +X do { +X sum = sum + sum + 1; +X incr = sum % dp->di_size; +X } while (incr == 0); +X for (;;) { +X register dictentry *ep = &dp->di_table[i]; +X if (ep->de_key == NULL) { +X if (freeslot != NULL) +X return freeslot; +X else +X return ep; +X } +X if (ep->de_key == dummy) { +X if (freeslot != NULL) +X freeslot = ep; +X } +X else if (GETSTRINGVALUE(ep->de_key)[0] == key[0]) { +X if (strcmp(GETSTRINGVALUE(ep->de_key), key) == 0) { +X return ep; +X } +X } +X i = (i + incr) % dp->di_size; +X } X} X X/* @@ -1293,438 +1293,438 @@ X*/ Xstatic void insertdict PROTO((dictobject *, stringobject *, object *)); Xstatic void Xinsertdict(dp, key, value) -X register dictobject *dp; -X stringobject *key; -X object *value; -X{ -X register dictentry *ep; -X ep = lookdict(dp, GETSTRINGVALUE(key)); -X if (ep->de_value != NULL) { -X DECREF(ep->de_value); -X DECREF(key); -X } -X else { -X if (ep->de_key == NULL) -X dp->di_fill++; -X else -X DECREF(ep->de_key); -X ep->de_key = key; -X dp->di_used++; -X } -X ep->de_value = value; +X register dictobject *dp; +X stringobject *key; +X object *value; +X{ +X register dictentry *ep; +X ep = lookdict(dp, GETSTRINGVALUE(key)); +X if (ep->de_value != NULL) { +X DECREF(ep->de_value); +X DECREF(key); +X } +X else { +X if (ep->de_key == NULL) +X dp->di_fill++; +X else +X DECREF(ep->de_key); +X ep->de_key = key; +X dp->di_used++; +X } +X ep->de_value = value; X} X X/* XRestructure the table by allocating a new table and reinserting all -Xitems again. When entries have been deleted, the new table may +Xitems again. When entries have been deleted, the new table may Xactually be smaller than the old one. X*/ Xstatic int dictresize PROTO((dictobject *)); Xstatic int Xdictresize(dp) -X dictobject *dp; -X{ -X register int oldsize = dp->di_size; -X register int newsize; -X register dictentry *oldtable = dp->di_table; -X register dictentry *newtable; -X register dictentry *ep; -X register int i; -X newsize = dp->di_size; -X for (i = 0; ; i++) { -X if (primes[i] > dp->di_used*2) { -X newsize = primes[i]; -X break; -X } -X } -X newtable = (dictentry *) calloc(sizeof(dictentry), newsize); -X if (newtable == NULL) { -X err_nomem(); -X return -1; -X } -X dp->di_size = newsize; -X dp->di_table = newtable; -X dp->di_fill = 0; -X dp->di_used = 0; -X for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { -X if (ep->de_value != NULL) -X insertdict(dp, ep->de_key, ep->de_value); -X else if (ep->de_key != NULL) -X DECREF(ep->de_key); -X } -X DEL(oldtable); -X return 0; +X dictobject *dp; +X{ +X register int oldsize = dp->di_size; +X register int newsize; +X register dictentry *oldtable = dp->di_table; +X register dictentry *newtable; +X register dictentry *ep; +X register int i; +X newsize = dp->di_size; +X for (i = 0; ; i++) { +X if (primes[i] > dp->di_used*2) { +X newsize = primes[i]; +X break; +X } +X } +X newtable = (dictentry *) calloc(sizeof(dictentry), newsize); +X if (newtable == NULL) { +X err_nomem(); +X return -1; +X } +X dp->di_size = newsize; +X dp->di_table = newtable; +X dp->di_fill = 0; +X dp->di_used = 0; +X for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { +X if (ep->de_value != NULL) +X insertdict(dp, ep->de_key, ep->de_value); +X else if (ep->de_key != NULL) +X DECREF(ep->de_key); +X } +X DEL(oldtable); +X return 0; X} X Xobject * Xdictlookup(op, key) -X object *op; -X char *key; +X object *op; +X char *key; X{ -X if (!is_dictobject(op)) -X fatal("dictlookup on non-dictionary"); -X return lookdict((dictobject *)op, key) -> de_value; +X if (!is_dictobject(op)) +X fatal("dictlookup on non-dictionary"); +X return lookdict((dictobject *)op, key) -> de_value; X} X X#ifdef NOT_USED Xstatic object * Xdict2lookup(op, key) -X register object *op; -X register object *key; -X{ -X register object *res; -X if (!is_dictobject(op)) { -X err_badcall(); -X return NULL; -X } -X if (!is_stringobject(key)) { -X err_badarg(); -X return NULL; -X } -X res = lookdict((dictobject *)op, ((stringobject *)key)->ob_sval) -X -> de_value; -X if (res == NULL) -X err_setstr(KeyError, "key not in dictionary"); -X return res; +X register object *op; +X register object *key; +X{ +X register object *res; +X if (!is_dictobject(op)) { +X err_badcall(); +X return NULL; +X } +X if (!is_stringobject(key)) { +X err_badarg(); +X return NULL; +X } +X res = lookdict((dictobject *)op, ((stringobject *)key)->ob_sval) +X -> de_value; +X if (res == NULL) +X err_setstr(KeyError, "key not in dictionary"); +X return res; X} X#endif X Xstatic int Xdict2insert(op, key, value) -X register object *op; -X object *key; -X object *value; -X{ -X register dictobject *dp; -X register stringobject *keyobj; -X if (!is_dictobject(op)) { -X err_badcall(); -X return -1; -X } -X dp = (dictobject *)op; -X if (!is_stringobject(key)) { -X err_badarg(); -X return -1; -X } -X keyobj = (stringobject *)key; -X /* if fill >= 2/3 size, resize */ -X if (dp->di_fill*3 >= dp->di_size*2) { -X if (dictresize(dp) != 0) { -X if (dp->di_fill+1 > dp->di_size) -X return -1; -X } -X } -X INCREF(keyobj); -X INCREF(value); -X insertdict(dp, keyobj, value); -X return 0; +X register object *op; +X object *key; +X object *value; +X{ +X register dictobject *dp; +X register stringobject *keyobj; +X if (!is_dictobject(op)) { +X err_badcall(); +X return -1; +X } +X dp = (dictobject *)op; +X if (!is_stringobject(key)) { +X err_badarg(); +X return -1; +X } +X keyobj = (stringobject *)key; +X /* if fill >= 2/3 size, resize */ +X if (dp->di_fill*3 >= dp->di_size*2) { +X if (dictresize(dp) != 0) { +X if (dp->di_fill+1 > dp->di_size) +X return -1; +X } +X } +X INCREF(keyobj); +X INCREF(value); +X insertdict(dp, keyobj, value); +X return 0; X} X Xint Xdictinsert(op, key, value) -X object *op; -X char *key; -X object *value; -X{ -X register object *keyobj; -X register int err; -X keyobj = newstringobject(key); -X if (keyobj == NULL) { -X err_nomem(); -X return -1; -X } -X err = dict2insert(op, keyobj, value); -X DECREF(keyobj); -X return err; +X object *op; +X char *key; +X object *value; +X{ +X register object *keyobj; +X register int err; +X keyobj = newstringobject(key); +X if (keyobj == NULL) { +X err_nomem(); +X return -1; +X } +X err = dict2insert(op, keyobj, value); +X DECREF(keyobj); +X return err; X} X Xint Xdictremove(op, key) -X object *op; -X char *key; -X{ -X register dictobject *dp; -X register dictentry *ep; -X if (!is_dictobject(op)) { -X err_badcall(); -X return -1; -X } -X dp = (dictobject *)op; -X ep = lookdict(dp, key); -X if (ep->de_value == NULL) { -X err_setstr(KeyError, "key not in dictionary"); -X return -1; -X } -X DECREF(ep->de_key); -X INCREF(dummy); -X ep->de_key = dummy; -X DECREF(ep->de_value); -X ep->de_value = NULL; -X dp->di_used--; -X return 0; +X object *op; +X char *key; +X{ +X register dictobject *dp; +X register dictentry *ep; +X if (!is_dictobject(op)) { +X err_badcall(); +X return -1; +X } +X dp = (dictobject *)op; +X ep = lookdict(dp, key); +X if (ep->de_value == NULL) { +X err_setstr(KeyError, "key not in dictionary"); +X return -1; +X } +X DECREF(ep->de_key); +X INCREF(dummy); +X ep->de_key = dummy; +X DECREF(ep->de_value); +X ep->de_value = NULL; +X dp->di_used--; +X return 0; X} X Xstatic int Xdict2remove(op, key) -X object *op; -X register object *key; +X object *op; +X register object *key; X{ -X if (!is_stringobject(key)) { -X err_badarg(); -X return -1; -X } -X return dictremove(op, GETSTRINGVALUE((stringobject *)key)); +X if (!is_stringobject(key)) { +X err_badarg(); +X return -1; +X } +X return dictremove(op, GETSTRINGVALUE((stringobject *)key)); X} X Xint Xgetdictsize(op) -X register object *op; +X register object *op; X{ -X if (!is_dictobject(op)) { -X err_badcall(); -X return -1; -X } -X return ((dictobject *)op) -> di_size; +X if (!is_dictobject(op)) { +X err_badcall(); +X return -1; +X } +X return ((dictobject *)op) -> di_size; X} X Xstatic object * Xgetdict2key(op, i) -X object *op; -X register int i; -X{ -X /* XXX This can't return errors since its callers assume -X that NULL means there was no key at that point */ -X register dictobject *dp; -X if (!is_dictobject(op)) { -X /* err_badcall(); */ -X return NULL; -X } -X dp = (dictobject *)op; -X if (i < 0 || i >= dp->di_size) { -X /* err_badarg(); */ -X return NULL; -X } -X if (dp->di_table[i].de_value == NULL) { -X /* Not an error! */ -X return NULL; -X } -X return (object *) dp->di_table[i].de_key; +X object *op; +X register int i; +X{ +X /* XXX This can't return errors since its callers assume +X that NULL means there was no key at that point */ +X register dictobject *dp; +X if (!is_dictobject(op)) { +X /* err_badcall(); */ +X return NULL; +X } +X dp = (dictobject *)op; +X if (i < 0 || i >= dp->di_size) { +X /* err_badarg(); */ +X return NULL; +X } +X if (dp->di_table[i].de_value == NULL) { +X /* Not an error! */ +X return NULL; +X } +X return (object *) dp->di_table[i].de_key; X} X Xchar * Xgetdictkey(op, i) -X object *op; -X int i; +X object *op; +X int i; X{ -X register object *keyobj = getdict2key(op, i); -X if (keyobj == NULL) -X return NULL; -X return GETSTRINGVALUE((stringobject *)keyobj); +X register object *keyobj = getdict2key(op, i); +X if (keyobj == NULL) +X return NULL; +X return GETSTRINGVALUE((stringobject *)keyobj); X} X X/* Methods */ X Xstatic void Xdict_dealloc(dp) -X register dictobject *dp; +X register dictobject *dp; X{ -X register int i; -X register dictentry *ep; -X for (i = 0, ep = dp->di_table; i < dp->di_size; i++, ep++) { -X if (ep->de_key != NULL) -X DECREF(ep->de_key); -X if (ep->de_value != NULL) -X DECREF(ep->de_value); -X } -X if (dp->di_table != NULL) -X DEL(dp->di_table); -X DEL(dp); +X register int i; +X register dictentry *ep; +X for (i = 0, ep = dp->di_table; i < dp->di_size; i++, ep++) { +X if (ep->de_key != NULL) +X DECREF(ep->de_key); +X if (ep->de_value != NULL) +X DECREF(ep->de_value); +X } +X if (dp->di_table != NULL) +X DEL(dp->di_table); +X DEL(dp); X} X Xstatic void Xdict_print(dp, fp, flags) -X register dictobject *dp; -X register FILE *fp; -X register int flags; -X{ -X register int i; -X register int any; -X register dictentry *ep; -X fprintf(fp, "{"); -X any = 0; -X for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; -X i++, ep++) { -X if (ep->de_value != NULL) { -X if (any++ > 0) -X fprintf(fp, "; "); -X printobject((object *)ep->de_key, fp, flags); -X fprintf(fp, ": "); -X printobject(ep->de_value, fp, flags); -X } -X } -X fprintf(fp, "}"); +X register dictobject *dp; +X register FILE *fp; +X register int flags; +X{ +X register int i; +X register int any; +X register dictentry *ep; +X fprintf(fp, "{"); +X any = 0; +X for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; +X i++, ep++) { +X if (ep->de_value != NULL) { +X if (any++ > 0) +X fprintf(fp, "; "); +X printobject((object *)ep->de_key, fp, flags); +X fprintf(fp, ": "); +X printobject(ep->de_value, fp, flags); +X } +X } +X fprintf(fp, "}"); X} X Xstatic void Xjs(pv, w) -X object **pv; -X object *w; +X object **pv; +X object *w; X{ -X joinstring(pv, w); -X if (w != NULL) -X DECREF(w); +X joinstring(pv, w); +X if (w != NULL) +X DECREF(w); X} X Xstatic object * Xdict_repr(dp) -X dictobject *dp; -X{ -X auto object *v; -X register object *w; -X object *semi, *colon; -X register int i; -X register int any; -X register dictentry *ep; -X v = newstringobject("{"); -X semi = newstringobject("; "); -X colon = newstringobject(": "); -X any = 0; -X for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; -X i++, ep++) { -X if (ep->de_value != NULL) { -X if (any++) -X joinstring(&v, semi); -X js(&v, w = reprobject((object *)ep->de_key)); -X joinstring(&v, colon); -X js(&v, w = reprobject(ep->de_value)); -X } -X } -X js(&v, w = newstringobject("}")); -X if (semi != NULL) -X DECREF(semi); -X if (colon != NULL) -X DECREF(colon); -X return v; +X dictobject *dp; +X{ +X auto object *v; +X register object *w; +X object *semi, *colon; +X register int i; +X register int any; +X register dictentry *ep; +X v = newstringobject("{"); +X semi = newstringobject("; "); +X colon = newstringobject(": "); +X any = 0; +X for (i = 0, ep = dp->di_table; i < dp->di_size && !StopPrint; +X i++, ep++) { +X if (ep->de_value != NULL) { +X if (any++) +X joinstring(&v, semi); +X js(&v, w = reprobject((object *)ep->de_key)); +X joinstring(&v, colon); +X js(&v, w = reprobject(ep->de_value)); +X } +X } +X js(&v, w = newstringobject("}")); +X if (semi != NULL) +X DECREF(semi); +X if (colon != NULL) +X DECREF(colon); +X return v; X} X Xstatic int Xdict_length(dp) -X dictobject *dp; +X dictobject *dp; X{ -X return dp->di_used; +X return dp->di_used; X} X Xstatic object * Xdict_subscript(dp, v) -X dictobject *dp; -X register object *v; +X dictobject *dp; +X register object *v; X{ -X if (!is_stringobject(v)) { -X err_badarg(); -X return NULL; -X } -X v = lookdict(dp, GETSTRINGVALUE((stringobject *)v)) -> de_value; -X if (v == NULL) -X err_setstr(KeyError, "key not in dictionary"); -X else -X INCREF(v); -X return v; +X if (!is_stringobject(v)) { +X err_badarg(); +X return NULL; +X } +X v = lookdict(dp, GETSTRINGVALUE((stringobject *)v)) -> de_value; +X if (v == NULL) +X err_setstr(KeyError, "key not in dictionary"); +X else +X INCREF(v); +X return v; X} X Xstatic int Xdict_ass_sub(dp, v, w) -X dictobject *dp; -X object *v, *w; +X dictobject *dp; +X object *v, *w; X{ -X if (w == NULL) -X return dict2remove((object *)dp, v); -X else -X return dict2insert((object *)dp, v, w); +X if (w == NULL) +X return dict2remove((object *)dp, v); +X else +X return dict2insert((object *)dp, v, w); X} X Xstatic mapping_methods dict_as_mapping = { -X dict_length, /*mp_length*/ -X dict_subscript, /*mp_subscript*/ -X dict_ass_sub, /*mp_ass_subscript*/ +X dict_length, /*mp_length*/ +X dict_subscript, /*mp_subscript*/ +X dict_ass_sub, /*mp_ass_subscript*/ X}; X Xstatic object * Xdict_keys(dp, args) -X register dictobject *dp; -X object *args; -X{ -X register object *v; -X register int i, j; -X if (!getnoarg(args)) -X return NULL; -X v = newlistobject(dp->di_used); -X if (v == NULL) -X return NULL; -X for (i = 0, j = 0; i < dp->di_size; i++) { -X if (dp->di_table[i].de_value != NULL) { -X stringobject *key = dp->di_table[i].de_key; -X INCREF(key); -X setlistitem(v, j, (object *)key); -X j++; -X } -X } -X return v; +X register dictobject *dp; +X object *args; +X{ +X register object *v; +X register int i, j; +X if (!getnoarg(args)) +X return NULL; +X v = newlistobject(dp->di_used); +X if (v == NULL) +X return NULL; +X for (i = 0, j = 0; i < dp->di_size; i++) { +X if (dp->di_table[i].de_value != NULL) { +X stringobject *key = dp->di_table[i].de_key; +X INCREF(key); +X setlistitem(v, j, (object *)key); +X j++; +X } +X } +X return v; X} X Xobject * Xgetdictkeys(dp) -X object *dp; +X object *dp; X{ -X if (dp == NULL || !is_dictobject(dp)) { -X err_badcall(); -X return NULL; -X } -X return dict_keys((dictobject *)dp, (object *)NULL); +X if (dp == NULL || !is_dictobject(dp)) { +X err_badcall(); +X return NULL; +X } +X return dict_keys((dictobject *)dp, (object *)NULL); X} X Xstatic object * Xdict_has_key(dp, args) -X register dictobject *dp; -X object *args; +X register dictobject *dp; +X object *args; X{ -X object *key; -X register long ok; -X if (!getstrarg(args, &key)) -X return NULL; -X ok = lookdict(dp, GETSTRINGVALUE((stringobject *)key))->de_value -X != NULL; -X return newintobject(ok); +X object *key; +X register long ok; +X if (!getstrarg(args, &key)) +X return NULL; +X ok = lookdict(dp, GETSTRINGVALUE((stringobject *)key))->de_value +X != NULL; +X return newintobject(ok); X} X Xstatic struct methodlist dict_methods[] = { -X {"keys", dict_keys}, -X {"has_key", dict_has_key}, -X {NULL, NULL} /* sentinel */ +X {"keys", dict_keys}, +X {"has_key", dict_has_key}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xdict_getattr(dp, name) -X dictobject *dp; -X char *name; +X dictobject *dp; +X char *name; X{ -X return findmethod(dict_methods, (object *)dp, name); +X return findmethod(dict_methods, (object *)dp, name); X} X Xtypeobject Dicttype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "dictionary", -X sizeof(dictobject), -X 0, -X dict_dealloc, /*tp_dealloc*/ -X dict_print, /*tp_print*/ -X dict_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X dict_repr, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X &dict_as_mapping, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "dictionary", +X sizeof(dictobject), +X 0, +X dict_dealloc, /*tp_dealloc*/ +X dict_print, /*tp_print*/ +X dict_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X dict_repr, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X &dict_as_mapping, /*tp_as_mapping*/ X}; EOF fi @@ -1737,12 +1737,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1776,109 +1776,109 @@ X X/* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */ X Xtypedef struct _nfaarc { -X int ar_label; -X int ar_arrow; +X int ar_label; +X int ar_arrow; X} nfaarc; X Xtypedef struct _nfastate { -X int st_narcs; -X nfaarc *st_arc; +X int st_narcs; +X nfaarc *st_arc; X} nfastate; X Xtypedef struct _nfa { -X int nf_type; -X char *nf_name; -X int nf_nstates; -X nfastate *nf_state; -X int nf_start, nf_finish; +X int nf_type; +X char *nf_name; +X int nf_nstates; +X nfastate *nf_state; +X int nf_start, nf_finish; X} nfa; X Xstatic int Xaddnfastate(nf) -X nfa *nf; +X nfa *nf; X{ -X nfastate *st; -X -X RESIZE(nf->nf_state, nfastate, nf->nf_nstates + 1); -X if (nf->nf_state == NULL) -X fatal("out of mem"); -X st = &nf->nf_state[nf->nf_nstates++]; -X st->st_narcs = 0; -X st->st_arc = NULL; -X return st - nf->nf_state; +X nfastate *st; +X +X RESIZE(nf->nf_state, nfastate, nf->nf_nstates + 1); +X if (nf->nf_state == NULL) +X fatal("out of mem"); +X st = &nf->nf_state[nf->nf_nstates++]; +X st->st_narcs = 0; +X st->st_arc = NULL; +X return st - nf->nf_state; X} X Xstatic void Xaddnfaarc(nf, from, to, lbl) -X nfa *nf; -X int from, to, lbl; +X nfa *nf; +X int from, to, lbl; X{ -X nfastate *st; -X nfaarc *ar; -X -X st = &nf->nf_state[from]; -X RESIZE(st->st_arc, nfaarc, st->st_narcs + 1); -X if (st->st_arc == NULL) -X fatal("out of mem"); -X ar = &st->st_arc[st->st_narcs++]; -X ar->ar_label = lbl; -X ar->ar_arrow = to; +X nfastate *st; +X nfaarc *ar; +X +X st = &nf->nf_state[from]; +X RESIZE(st->st_arc, nfaarc, st->st_narcs + 1); +X if (st->st_arc == NULL) +X fatal("out of mem"); +X ar = &st->st_arc[st->st_narcs++]; +X ar->ar_label = lbl; +X ar->ar_arrow = to; X} X Xstatic nfa * Xnewnfa(name) -X char *name; -X{ -X nfa *nf; -X static type = NT_OFFSET; /* All types will be disjunct */ -X -X nf = NEW(nfa, 1); -X if (nf == NULL) -X fatal("no mem for new nfa"); -X nf->nf_type = type++; -X nf->nf_name = name; /* XXX strdup(name) ??? */ -X nf->nf_nstates = 0; -X nf->nf_state = NULL; -X nf->nf_start = nf->nf_finish = -1; -X return nf; +X char *name; +X{ +X nfa *nf; +X static type = NT_OFFSET; /* All types will be disjunct */ +X +X nf = NEW(nfa, 1); +X if (nf == NULL) +X fatal("no mem for new nfa"); +X nf->nf_type = type++; +X nf->nf_name = name; /* XXX strdup(name) ??? */ +X nf->nf_nstates = 0; +X nf->nf_state = NULL; +X nf->nf_start = nf->nf_finish = -1; +X return nf; X} X Xtypedef struct _nfagrammar { -X int gr_nnfas; -X nfa **gr_nfa; -X labellist gr_ll; +X int gr_nnfas; +X nfa **gr_nfa; +X labellist gr_ll; X} nfagrammar; X Xstatic nfagrammar * Xnewnfagrammar() X{ -X nfagrammar *gr; -X -X gr = NEW(nfagrammar, 1); -X if (gr == NULL) -X fatal("no mem for new nfa grammar"); -X gr->gr_nnfas = 0; -X gr->gr_nfa = NULL; -X gr->gr_ll.ll_nlabels = 0; -X gr->gr_ll.ll_label = NULL; -X addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); -X return gr; +X nfagrammar *gr; +X +X gr = NEW(nfagrammar, 1); +X if (gr == NULL) +X fatal("no mem for new nfa grammar"); +X gr->gr_nnfas = 0; +X gr->gr_nfa = NULL; +X gr->gr_ll.ll_nlabels = 0; +X gr->gr_ll.ll_label = NULL; +X addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); +X return gr; X} X Xstatic nfa * Xaddnfa(gr, name) -X nfagrammar *gr; -X char *name; +X nfagrammar *gr; +X char *name; X{ -X nfa *nf; -X -X nf = newnfa(name); -X RESIZE(gr->gr_nfa, nfa *, gr->gr_nnfas + 1); -X if (gr->gr_nfa == NULL) -X fatal("out of mem"); -X gr->gr_nfa[gr->gr_nnfas++] = nf; -X addlabel(&gr->gr_ll, NAME, nf->nf_name); -X return nf; +X nfa *nf; +X +X nf = newnfa(name); +X RESIZE(gr->gr_nfa, nfa *, gr->gr_nnfas + 1); +X if (gr->gr_nfa == NULL) +X fatal("out of mem"); +X gr->gr_nfa[gr->gr_nnfas++] = nf; +X addlabel(&gr->gr_ll, NAME, nf->nf_name); +X return nf; X} X X#ifdef DEBUG @@ -1886,231 +1886,231 @@ X Xstatic char REQNFMT[] = "metacompile: less than %d children\n"; X X#define REQN(i, count) \ -X if (i < count) { \ -X fprintf(stderr, REQNFMT, count); \ -X abort(); \ -X } else +X if (i < count) { \ +X fprintf(stderr, REQNFMT, count); \ +X abort(); \ +X } else X X#else -X#define REQN(i, count) /* empty */ +X#define REQN(i, count) /* empty */ X#endif X Xstatic nfagrammar * Xmetacompile(n) -X node *n; -X{ -X nfagrammar *gr; -X int i; -X -X printf("Compiling (meta-) parse tree into NFA grammar\n"); -X gr = newnfagrammar(); -X REQ(n, MSTART); -X i = n->n_nchildren - 1; /* Last child is ENDMARKER */ -X n = n->n_child; -X for (; --i >= 0; n++) { -X if (n->n_type != NEWLINE) -X compile_rule(gr, n); -X } -X return gr; +X node *n; +X{ +X nfagrammar *gr; +X int i; +X +X printf("Compiling (meta-) parse tree into NFA grammar\n"); +X gr = newnfagrammar(); +X REQ(n, MSTART); +X i = n->n_nchildren - 1; /* Last child is ENDMARKER */ +X n = n->n_child; +X for (; --i >= 0; n++) { +X if (n->n_type != NEWLINE) +X compile_rule(gr, n); +X } +X return gr; X} X Xstatic Xcompile_rule(gr, n) -X nfagrammar *gr; -X node *n; -X{ -X nfa *nf; -X -X REQ(n, RULE); -X REQN(n->n_nchildren, 4); -X n = n->n_child; -X REQ(n, NAME); -X nf = addnfa(gr, n->n_str); -X n++; -X REQ(n, COLON); -X n++; -X REQ(n, RHS); -X compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); -X n++; -X REQ(n, NEWLINE); +X nfagrammar *gr; +X node *n; +X{ +X nfa *nf; +X +X REQ(n, RULE); +X REQN(n->n_nchildren, 4); +X n = n->n_child; +X REQ(n, NAME); +X nf = addnfa(gr, n->n_str); +X n++; +X REQ(n, COLON); +X n++; +X REQ(n, RHS); +X compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); +X n++; +X REQ(n, NEWLINE); X} X Xstatic Xcompile_rhs(ll, nf, n, pa, pb) -X labellist *ll; -X nfa *nf; -X node *n; -X int *pa, *pb; -X{ -X int i; -X int a, b; -X -X REQ(n, RHS); -X i = n->n_nchildren; -X REQN(i, 1); -X n = n->n_child; -X REQ(n, ALT); -X compile_alt(ll, nf, n, pa, pb); -X if (--i <= 0) -X return; -X n++; -X a = *pa; -X b = *pb; -X *pa = addnfastate(nf); -X *pb = addnfastate(nf); -X addnfaarc(nf, *pa, a, EMPTY); -X addnfaarc(nf, b, *pb, EMPTY); -X for (; --i >= 0; n++) { -X REQ(n, VBAR); -X REQN(i, 1); -X --i; -X n++; -X REQ(n, ALT); -X compile_alt(ll, nf, n, &a, &b); -X addnfaarc(nf, *pa, a, EMPTY); -X addnfaarc(nf, b, *pb, EMPTY); -X } +X labellist *ll; +X nfa *nf; +X node *n; +X int *pa, *pb; +X{ +X int i; +X int a, b; +X +X REQ(n, RHS); +X i = n->n_nchildren; +X REQN(i, 1); +X n = n->n_child; +X REQ(n, ALT); +X compile_alt(ll, nf, n, pa, pb); +X if (--i <= 0) +X return; +X n++; +X a = *pa; +X b = *pb; +X *pa = addnfastate(nf); +X *pb = addnfastate(nf); +X addnfaarc(nf, *pa, a, EMPTY); +X addnfaarc(nf, b, *pb, EMPTY); +X for (; --i >= 0; n++) { +X REQ(n, VBAR); +X REQN(i, 1); +X --i; +X n++; +X REQ(n, ALT); +X compile_alt(ll, nf, n, &a, &b); +X addnfaarc(nf, *pa, a, EMPTY); +X addnfaarc(nf, b, *pb, EMPTY); +X } X} X Xstatic Xcompile_alt(ll, nf, n, pa, pb) -X labellist *ll; -X nfa *nf; -X node *n; -X int *pa, *pb; -X{ -X int i; -X int a, b; -X -X REQ(n, ALT); -X i = n->n_nchildren; -X REQN(i, 1); -X n = n->n_child; -X REQ(n, ITEM); -X compile_item(ll, nf, n, pa, pb); -X --i; -X n++; -X for (; --i >= 0; n++) { -X if (n->n_type == COMMA) { /* XXX Temporary */ -X REQN(i, 1); -X --i; -X n++; -X } -X REQ(n, ITEM); -X compile_item(ll, nf, n, &a, &b); -X addnfaarc(nf, *pb, a, EMPTY); -X *pb = b; -X } +X labellist *ll; +X nfa *nf; +X node *n; +X int *pa, *pb; +X{ +X int i; +X int a, b; +X +X REQ(n, ALT); +X i = n->n_nchildren; +X REQN(i, 1); +X n = n->n_child; +X REQ(n, ITEM); +X compile_item(ll, nf, n, pa, pb); +X --i; +X n++; +X for (; --i >= 0; n++) { +X if (n->n_type == COMMA) { /* XXX Temporary */ +X REQN(i, 1); +X --i; +X n++; +X } +X REQ(n, ITEM); +X compile_item(ll, nf, n, &a, &b); +X addnfaarc(nf, *pb, a, EMPTY); +X *pb = b; +X } X} X Xstatic Xcompile_item(ll, nf, n, pa, pb) -X labellist *ll; -X nfa *nf; -X node *n; -X int *pa, *pb; -X{ -X int i; -X int a, b; -X -X REQ(n, ITEM); -X i = n->n_nchildren; -X REQN(i, 1); -X n = n->n_child; -X if (n->n_type == LSQB) { -X REQN(i, 3); -X n++; -X REQ(n, RHS); -X *pa = addnfastate(nf); -X *pb = addnfastate(nf); -X addnfaarc(nf, *pa, *pb, EMPTY); -X compile_rhs(ll, nf, n, &a, &b); -X addnfaarc(nf, *pa, a, EMPTY); -X addnfaarc(nf, b, *pb, EMPTY); -X REQN(i, 1); -X n++; -X REQ(n, RSQB); -X } -X else { -X compile_atom(ll, nf, n, pa, pb); -X if (--i <= 0) -X return; -X n++; -X addnfaarc(nf, *pb, *pa, EMPTY); -X if (n->n_type == STAR) -X *pb = *pa; -X else -X REQ(n, PLUS); -X } +X labellist *ll; +X nfa *nf; +X node *n; +X int *pa, *pb; +X{ +X int i; +X int a, b; +X +X REQ(n, ITEM); +X i = n->n_nchildren; +X REQN(i, 1); +X n = n->n_child; +X if (n->n_type == LSQB) { +X REQN(i, 3); +X n++; +X REQ(n, RHS); +X *pa = addnfastate(nf); +X *pb = addnfastate(nf); +X addnfaarc(nf, *pa, *pb, EMPTY); +X compile_rhs(ll, nf, n, &a, &b); +X addnfaarc(nf, *pa, a, EMPTY); +X addnfaarc(nf, b, *pb, EMPTY); +X REQN(i, 1); +X n++; +X REQ(n, RSQB); +X } +X else { +X compile_atom(ll, nf, n, pa, pb); +X if (--i <= 0) +X return; +X n++; +X addnfaarc(nf, *pb, *pa, EMPTY); +X if (n->n_type == STAR) +X *pb = *pa; +X else +X REQ(n, PLUS); +X } X} X Xstatic Xcompile_atom(ll, nf, n, pa, pb) -X labellist *ll; -X nfa *nf; -X node *n; -X int *pa, *pb; -X{ -X int i; -X -X REQ(n, ATOM); -X i = n->n_nchildren; -X REQN(i, 1); -X n = n->n_child; -X if (n->n_type == LPAR) { -X REQN(i, 3); -X n++; -X REQ(n, RHS); -X compile_rhs(ll, nf, n, pa, pb); -X n++; -X REQ(n, RPAR); -X } -X else if (n->n_type == NAME || n->n_type == STRING) { -X *pa = addnfastate(nf); -X *pb = addnfastate(nf); -X addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); -X } -X else -X REQ(n, NAME); +X labellist *ll; +X nfa *nf; +X node *n; +X int *pa, *pb; +X{ +X int i; +X +X REQ(n, ATOM); +X i = n->n_nchildren; +X REQN(i, 1); +X n = n->n_child; +X if (n->n_type == LPAR) { +X REQN(i, 3); +X n++; +X REQ(n, RHS); +X compile_rhs(ll, nf, n, pa, pb); +X n++; +X REQ(n, RPAR); +X } +X else if (n->n_type == NAME || n->n_type == STRING) { +X *pa = addnfastate(nf); +X *pb = addnfastate(nf); +X addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); +X } +X else +X REQ(n, NAME); X} X Xstatic void Xdumpstate(ll, nf, istate) -X labellist *ll; -X nfa *nf; -X int istate; -X{ -X nfastate *st; -X int i; -X nfaarc *ar; -X -X printf("%c%2d%c", -X istate == nf->nf_start ? '*' : ' ', -X istate, -X istate == nf->nf_finish ? '.' : ' '); -X st = &nf->nf_state[istate]; -X ar = st->st_arc; -X for (i = 0; i < st->st_narcs; i++) { -X if (i > 0) -X printf("\n "); -X printf("-> %2d %s", ar->ar_arrow, -X labelrepr(&ll->ll_label[ar->ar_label])); -X ar++; -X } -X printf("\n"); +X labellist *ll; +X nfa *nf; +X int istate; +X{ +X nfastate *st; +X int i; +X nfaarc *ar; +X +X printf("%c%2d%c", +X istate == nf->nf_start ? '*' : ' ', +X istate, +X istate == nf->nf_finish ? '.' : ' '); +X st = &nf->nf_state[istate]; +X ar = st->st_arc; +X for (i = 0; i < st->st_narcs; i++) { +X if (i > 0) +X printf("\n "); +X printf("-> %2d %s", ar->ar_arrow, +X labelrepr(&ll->ll_label[ar->ar_label])); +X ar++; +X } +X printf("\n"); X} X Xstatic void Xdumpnfa(ll, nf) -X labellist *ll; -X nfa *nf; +X labellist *ll; +X nfa *nf; X{ -X int i; -X -X printf("NFA '%s' has %d states; start %d, finish %d\n", -X nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); -X for (i = 0; i < nf->nf_nstates; i++) -X dumpstate(ll, nf, i); +X int i; +X +X printf("NFA '%s' has %d states; start %d, finish %d\n", +X nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); +X for (i = 0; i < nf->nf_nstates; i++) +X dumpstate(ll, nf, i); X} X X @@ -2118,255 +2118,255 @@ X/* PART TWO -- CONSTRUCT DFA -- Algorithm 3.1 from [Aho&Ullman 77] */ X Xstatic int Xaddclosure(ss, nf, istate) -X bitset ss; -X nfa *nf; -X int istate; -X{ -X if (addbit(ss, istate)) { -X nfastate *st = &nf->nf_state[istate]; -X nfaarc *ar = st->st_arc; -X int i; -X -X for (i = st->st_narcs; --i >= 0; ) { -X if (ar->ar_label == EMPTY) -X addclosure(ss, nf, ar->ar_arrow); -X ar++; -X } -X } +X bitset ss; +X nfa *nf; +X int istate; +X{ +X if (addbit(ss, istate)) { +X nfastate *st = &nf->nf_state[istate]; +X nfaarc *ar = st->st_arc; +X int i; +X +X for (i = st->st_narcs; --i >= 0; ) { +X if (ar->ar_label == EMPTY) +X addclosure(ss, nf, ar->ar_arrow); +X ar++; +X } +X } X} X Xtypedef struct _ss_arc { -X bitset sa_bitset; -X int sa_arrow; -X int sa_label; +X bitset sa_bitset; +X int sa_arrow; +X int sa_label; X} ss_arc; X Xtypedef struct _ss_state { -X bitset ss_ss; -X int ss_narcs; -X ss_arc *ss_arc; -X int ss_deleted; -X int ss_finish; -X int ss_rename; +X bitset ss_ss; +X int ss_narcs; +X ss_arc *ss_arc; +X int ss_deleted; +X int ss_finish; +X int ss_rename; X} ss_state; X Xtypedef struct _ss_dfa { -X int sd_nstates; -X ss_state *sd_state; +X int sd_nstates; +X ss_state *sd_state; X} ss_dfa; X Xstatic Xmakedfa(gr, nf, d) -X nfagrammar *gr; -X nfa *nf; -X dfa *d; -X{ -X int nbits = nf->nf_nstates; -X bitset ss; -X int xx_nstates; -X ss_state *xx_state, *yy; -X ss_arc *zz; -X int istate, jstate, iarc, jarc, ibit; -X nfastate *st; -X nfaarc *ar; -X -X ss = newbitset(nbits); -X addclosure(ss, nf, nf->nf_start); -X xx_state = NEW(ss_state, 1); -X if (xx_state == NULL) -X fatal("no mem for xx_state in makedfa"); -X xx_nstates = 1; -X yy = &xx_state[0]; -X yy->ss_ss = ss; -X yy->ss_narcs = 0; -X yy->ss_arc = NULL; -X yy->ss_deleted = 0; -X yy->ss_finish = testbit(ss, nf->nf_finish); -X if (yy->ss_finish) -X printf("Error: nonterminal '%s' may produce empty.\n", -X nf->nf_name); -X -X /* This algorithm is from a book written before -X the invention of structured programming... */ -X -X /* For each unmarked state... */ -X for (istate = 0; istate < xx_nstates; ++istate) { -X yy = &xx_state[istate]; -X ss = yy->ss_ss; -X /* For all its states... */ -X for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { -X if (!testbit(ss, ibit)) -X continue; -X st = &nf->nf_state[ibit]; -X /* For all non-empty arcs from this state... */ -X for (iarc = 0; iarc < st->st_narcs; iarc++) { -X ar = &st->st_arc[iarc]; -X if (ar->ar_label == EMPTY) -X continue; -X /* Look up in list of arcs from this state */ -X for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { -X zz = &yy->ss_arc[jarc]; -X if (ar->ar_label == zz->sa_label) -X goto found; -X } -X /* Add new arc for this state */ -X RESIZE(yy->ss_arc, ss_arc, yy->ss_narcs + 1); -X if (yy->ss_arc == NULL) -X fatal("out of mem"); -X zz = &yy->ss_arc[yy->ss_narcs++]; -X zz->sa_label = ar->ar_label; -X zz->sa_bitset = newbitset(nbits); -X zz->sa_arrow = -1; -X found: ; -X /* Add destination */ -X addclosure(zz->sa_bitset, nf, ar->ar_arrow); -X } -X } -X /* Now look up all the arrow states */ -X for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { -X zz = &xx_state[istate].ss_arc[jarc]; -X for (jstate = 0; jstate < xx_nstates; jstate++) { -X if (samebitset(zz->sa_bitset, -X xx_state[jstate].ss_ss, nbits)) { -X zz->sa_arrow = jstate; -X goto done; -X } -X } -X RESIZE(xx_state, ss_state, xx_nstates + 1); -X if (xx_state == NULL) -X fatal("out of mem"); -X zz->sa_arrow = xx_nstates; -X yy = &xx_state[xx_nstates++]; -X yy->ss_ss = zz->sa_bitset; -X yy->ss_narcs = 0; -X yy->ss_arc = NULL; -X yy->ss_deleted = 0; -X yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); -X done: ; -X } -X } -X -X if (debugging) -X printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, -X "before minimizing"); -X -X simplify(xx_nstates, xx_state); -X -X if (debugging) -X printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, -X "after minimizing"); -X -X convert(d, xx_nstates, xx_state); -X -X /* XXX cleanup */ +X nfagrammar *gr; +X nfa *nf; +X dfa *d; +X{ +X int nbits = nf->nf_nstates; +X bitset ss; +X int xx_nstates; +X ss_state *xx_state, *yy; +X ss_arc *zz; +X int istate, jstate, iarc, jarc, ibit; +X nfastate *st; +X nfaarc *ar; +X +X ss = newbitset(nbits); +X addclosure(ss, nf, nf->nf_start); +X xx_state = NEW(ss_state, 1); +X if (xx_state == NULL) +X fatal("no mem for xx_state in makedfa"); +X xx_nstates = 1; +X yy = &xx_state[0]; +X yy->ss_ss = ss; +X yy->ss_narcs = 0; +X yy->ss_arc = NULL; +X yy->ss_deleted = 0; +X yy->ss_finish = testbit(ss, nf->nf_finish); +X if (yy->ss_finish) +X printf("Error: nonterminal '%s' may produce empty.\n", +X nf->nf_name); +X +X /* This algorithm is from a book written before +X the invention of structured programming... */ +X +X /* For each unmarked state... */ +X for (istate = 0; istate < xx_nstates; ++istate) { +X yy = &xx_state[istate]; +X ss = yy->ss_ss; +X /* For all its states... */ +X for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { +X if (!testbit(ss, ibit)) +X continue; +X st = &nf->nf_state[ibit]; +X /* For all non-empty arcs from this state... */ +X for (iarc = 0; iarc < st->st_narcs; iarc++) { +X ar = &st->st_arc[iarc]; +X if (ar->ar_label == EMPTY) +X continue; +X /* Look up in list of arcs from this state */ +X for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { +X zz = &yy->ss_arc[jarc]; +X if (ar->ar_label == zz->sa_label) +X goto found; +X } +X /* Add new arc for this state */ +X RESIZE(yy->ss_arc, ss_arc, yy->ss_narcs + 1); +X if (yy->ss_arc == NULL) +X fatal("out of mem"); +X zz = &yy->ss_arc[yy->ss_narcs++]; +X zz->sa_label = ar->ar_label; +X zz->sa_bitset = newbitset(nbits); +X zz->sa_arrow = -1; +X found: ; +X /* Add destination */ +X addclosure(zz->sa_bitset, nf, ar->ar_arrow); +X } +X } +X /* Now look up all the arrow states */ +X for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { +X zz = &xx_state[istate].ss_arc[jarc]; +X for (jstate = 0; jstate < xx_nstates; jstate++) { +X if (samebitset(zz->sa_bitset, +X xx_state[jstate].ss_ss, nbits)) { +X zz->sa_arrow = jstate; +X goto done; +X } +X } +X RESIZE(xx_state, ss_state, xx_nstates + 1); +X if (xx_state == NULL) +X fatal("out of mem"); +X zz->sa_arrow = xx_nstates; +X yy = &xx_state[xx_nstates++]; +X yy->ss_ss = zz->sa_bitset; +X yy->ss_narcs = 0; +X yy->ss_arc = NULL; +X yy->ss_deleted = 0; +X yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); +X done: ; +X } +X } +X +X if (debugging) +X printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, +X "before minimizing"); +X +X simplify(xx_nstates, xx_state); +X +X if (debugging) +X printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, +X "after minimizing"); +X +X convert(d, xx_nstates, xx_state); +X +X /* XXX cleanup */ X} X Xstatic Xprintssdfa(xx_nstates, xx_state, nbits, ll, msg) -X int xx_nstates; -X ss_state *xx_state; -X int nbits; -X labellist *ll; -X char *msg; -X{ -X int i, ibit, iarc; -X ss_state *yy; -X ss_arc *zz; -X -X printf("Subset DFA %s\n", msg); -X for (i = 0; i < xx_nstates; i++) { -X yy = &xx_state[i]; -X if (yy->ss_deleted) -X continue; -X printf(" Subset %d", i); -X if (yy->ss_finish) -X printf(" (finish)"); -X printf(" { "); -X for (ibit = 0; ibit < nbits; ibit++) { -X if (testbit(yy->ss_ss, ibit)) -X printf("%d ", ibit); -X } -X printf("}\n"); -X for (iarc = 0; iarc < yy->ss_narcs; iarc++) { -X zz = &yy->ss_arc[iarc]; -X printf(" Arc to state %d, label %s\n", -X zz->sa_arrow, -X labelrepr(&ll->ll_label[zz->sa_label])); -X } -X } +X int xx_nstates; +X ss_state *xx_state; +X int nbits; +X labellist *ll; +X char *msg; +X{ +X int i, ibit, iarc; +X ss_state *yy; +X ss_arc *zz; +X +X printf("Subset DFA %s\n", msg); +X for (i = 0; i < xx_nstates; i++) { +X yy = &xx_state[i]; +X if (yy->ss_deleted) +X continue; +X printf(" Subset %d", i); +X if (yy->ss_finish) +X printf(" (finish)"); +X printf(" { "); +X for (ibit = 0; ibit < nbits; ibit++) { +X if (testbit(yy->ss_ss, ibit)) +X printf("%d ", ibit); +X } +X printf("}\n"); +X for (iarc = 0; iarc < yy->ss_narcs; iarc++) { +X zz = &yy->ss_arc[iarc]; +X printf(" Arc to state %d, label %s\n", +X zz->sa_arrow, +X labelrepr(&ll->ll_label[zz->sa_label])); +X } +X } X} X X X/* PART THREE -- SIMPLIFY DFA */ X X/* Simplify the DFA by repeatedly eliminating states that are -X equivalent to another oner. This is NOT Algorithm 3.3 from -X [Aho&Ullman 77]. It does not always finds the minimal DFA, -X but it does usually make a much smaller one... (For an example -X of sub-optimal behaviour, try S: x a b+ | y a b+.) +X equivalent to another oner. This is NOT Algorithm 3.3 from +X [Aho&Ullman 77]. It does not always finds the minimal DFA, +X but it does usually make a much smaller one... (For an example +X of sub-optimal behaviour, try S: x a b+ | y a b+.) X*/ X Xstatic int Xsamestate(s1, s2) -X ss_state *s1, *s2; +X ss_state *s1, *s2; X{ -X int i; -X -X if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) -X return 0; -X for (i = 0; i < s1->ss_narcs; i++) { -X if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || -X s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) -X return 0; -X } -X return 1; +X int i; +X +X if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) +X return 0; +X for (i = 0; i < s1->ss_narcs; i++) { +X if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || +X s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) +X return 0; +X } +X return 1; X} X Xstatic void Xrenamestates(xx_nstates, xx_state, from, to) -X int xx_nstates; -X ss_state *xx_state; -X int from, to; -X{ -X int i, j; -X -X if (debugging) -X printf("Rename state %d to %d.\n", from, to); -X for (i = 0; i < xx_nstates; i++) { -X if (xx_state[i].ss_deleted) -X continue; -X for (j = 0; j < xx_state[i].ss_narcs; j++) { -X if (xx_state[i].ss_arc[j].sa_arrow == from) -X xx_state[i].ss_arc[j].sa_arrow = to; -X } -X } +X int xx_nstates; +X ss_state *xx_state; +X int from, to; +X{ +X int i, j; +X +X if (debugging) +X printf("Rename state %d to %d.\n", from, to); +X for (i = 0; i < xx_nstates; i++) { +X if (xx_state[i].ss_deleted) +X continue; +X for (j = 0; j < xx_state[i].ss_narcs; j++) { +X if (xx_state[i].ss_arc[j].sa_arrow == from) +X xx_state[i].ss_arc[j].sa_arrow = to; +X } +X } X} X Xstatic Xsimplify(xx_nstates, xx_state) -X int xx_nstates; -X ss_state *xx_state; -X{ -X int changes; -X int i, j, k; -X -X do { -X changes = 0; -X for (i = 1; i < xx_nstates; i++) { -X if (xx_state[i].ss_deleted) -X continue; -X for (j = 0; j < i; j++) { -X if (xx_state[j].ss_deleted) -X continue; -X if (samestate(&xx_state[i], &xx_state[j])) { -X xx_state[i].ss_deleted++; -X renamestates(xx_nstates, xx_state, i, j); -X changes++; -X break; -X } -X } -X } -X } while (changes); +X int xx_nstates; +X ss_state *xx_state; +X{ +X int changes; +X int i, j, k; +X +X do { +X changes = 0; +X for (i = 1; i < xx_nstates; i++) { +X if (xx_state[i].ss_deleted) +X continue; +X for (j = 0; j < i; j++) { +X if (xx_state[j].ss_deleted) +X continue; +X if (samestate(&xx_state[i], &xx_state[j])) { +X xx_state[i].ss_deleted++; +X renamestates(xx_nstates, xx_state, i, j); +X changes++; +X break; +X } +X } +X } +X } while (changes); X} X X @@ -2376,36 +2376,36 @@ X/* Convert the DFA into a grammar that can be used by our parser */ X Xstatic Xconvert(d, xx_nstates, xx_state) -X dfa *d; -X int xx_nstates; -X ss_state *xx_state; -X{ -X int i, j; -X ss_state *yy; -X ss_arc *zz; -X -X for (i = 0; i < xx_nstates; i++) { -X yy = &xx_state[i]; -X if (yy->ss_deleted) -X continue; -X yy->ss_rename = addstate(d); -X } -X -X for (i = 0; i < xx_nstates; i++) { -X yy = &xx_state[i]; -X if (yy->ss_deleted) -X continue; -X for (j = 0; j < yy->ss_narcs; j++) { -X zz = &yy->ss_arc[j]; -X addarc(d, yy->ss_rename, -X xx_state[zz->sa_arrow].ss_rename, -X zz->sa_label); -X } -X if (yy->ss_finish) -X addarc(d, yy->ss_rename, yy->ss_rename, 0); -X } -X -X d->d_initial = 0; +X dfa *d; +X int xx_nstates; +X ss_state *xx_state; +X{ +X int i, j; +X ss_state *yy; +X ss_arc *zz; +X +X for (i = 0; i < xx_nstates; i++) { +X yy = &xx_state[i]; +X if (yy->ss_deleted) +X continue; +X yy->ss_rename = addstate(d); +X } +X +X for (i = 0; i < xx_nstates; i++) { +X yy = &xx_state[i]; +X if (yy->ss_deleted) +X continue; +X for (j = 0; j < yy->ss_narcs; j++) { +X zz = &yy->ss_arc[j]; +X addarc(d, yy->ss_rename, +X xx_state[zz->sa_arrow].ss_rename, +X zz->sa_label); +X } +X if (yy->ss_finish) +X addarc(d, yy->ss_rename, yy->ss_rename, 0); +X } +X +X d->d_initial = 0; X} X X @@ -2413,45 +2413,45 @@ X/* PART FIVE -- GLUE IT ALL TOGETHER */ X Xstatic grammar * Xmaketables(gr) -X nfagrammar *gr; -X{ -X int i; -X nfa *nf; -X dfa *d; -X grammar *g; -X -X if (gr->gr_nnfas == 0) -X return NULL; -X g = newgrammar(gr->gr_nfa[0]->nf_type); -X /* XXX first rule must be start rule */ -X g->g_ll = gr->gr_ll; -X -X for (i = 0; i < gr->gr_nnfas; i++) { -X nf = gr->gr_nfa[i]; -X if (debugging) { -X printf("Dump of NFA for '%s' ...\n", nf->nf_name); -X dumpnfa(&gr->gr_ll, nf); -X } -X printf("Making DFA for '%s' ...\n", nf->nf_name); -X d = adddfa(g, nf->nf_type, nf->nf_name); -X makedfa(gr, gr->gr_nfa[i], d); -X } -X -X return g; +X nfagrammar *gr; +X{ +X int i; +X nfa *nf; +X dfa *d; +X grammar *g; +X +X if (gr->gr_nnfas == 0) +X return NULL; +X g = newgrammar(gr->gr_nfa[0]->nf_type); +X /* XXX first rule must be start rule */ +X g->g_ll = gr->gr_ll; +X +X for (i = 0; i < gr->gr_nnfas; i++) { +X nf = gr->gr_nfa[i]; +X if (debugging) { +X printf("Dump of NFA for '%s' ...\n", nf->nf_name); +X dumpnfa(&gr->gr_ll, nf); +X } +X printf("Making DFA for '%s' ...\n", nf->nf_name); +X d = adddfa(g, nf->nf_type, nf->nf_name); +X makedfa(gr, gr->gr_nfa[i], d); +X } +X +X return g; X} X Xgrammar * Xpgen(n) -X node *n; +X node *n; X{ -X nfagrammar *gr; -X grammar *g; -X -X gr = metacompile(n); -X g = maketables(gr); -X translatelabels(g); -X addfirstsets(g); -X return g; +X nfagrammar *gr; +X grammar *g; +X +X gr = metacompile(n); +X g = maketables(gr); +X translatelabels(g); +X addfirstsets(g); +X return g; X} X X @@ -2462,26 +2462,26 @@ X----------- X XInput is a grammar in extended BNF (using * for repetition, + for Xat-least-once repetition, [] for optional parts, | for alternatives and -X() for grouping). This has already been parsed and turned into a parse +X() for grouping). This has already been parsed and turned into a parse Xtree. X XEach rule is considered as a regular expression in its own right. XIt is turned into a Non-deterministic Finite Automaton (NFA), which Xis then turned into a Deterministic Finite Automaton (DFA), which is then -Xoptimized to reduce the number of states. See [Aho&Ullman 77] chapter 3, +Xoptimized to reduce the number of states. See [Aho&Ullman 77] chapter 3, Xor similar compiler books (this technique is more often used for lexical Xanalyzers). X XThe DFA's are used by the parser as parsing tables in a special way -Xthat's probably unique. Before they are usable, the FIRST sets of all +Xthat's probably unique. Before they are usable, the FIRST sets of all Xnon-terminals are computed. X XReference X--------- X X[Aho&Ullman 77] -X Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 -X (first edition) +X Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 +X (first edition) X X*/ EOF @@ -2495,12 +2495,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2523,166 +2523,166 @@ X#include "modsupport.h" X X#include "regexp.h" X -Xstatic object *RegexpError; /* Exception */ +Xstatic object *RegexpError; /* Exception */ X Xtypedef struct { -X OB_HEAD -X object *re_string; /* The string (for printing) */ -X regexp *re_prog; /* The compiled regular expression */ +X OB_HEAD +X object *re_string; /* The string (for printing) */ +X regexp *re_prog; /* The compiled regular expression */ X} regexpobject; X -Xextern typeobject Regexptype; /* Really static, forward */ +Xextern typeobject Regexptype; /* Really static, forward */ X Xstatic regexpobject * Xnewregexpobject(string, prog) -X object *string; -X regexp *prog; +X object *string; +X regexp *prog; X{ -X regexpobject *re; -X re = NEWOBJ(regexpobject, &Regexptype); -X if (re != NULL) { -X XINCREF(string); -X re->re_string = string; -X re->re_prog = prog; -X } -X return re; +X regexpobject *re; +X re = NEWOBJ(regexpobject, &Regexptype); +X if (re != NULL) { +X XINCREF(string); +X re->re_string = string; +X re->re_prog = prog; +X } +X return re; X} X X/* Regexp methods */ X Xstatic void Xregexp_dealloc(re) -X regexpobject *re; +X regexpobject *re; X{ -X XDECREF(re->re_string); -X XDEL(re->re_prog); -X DEL(re); +X XDECREF(re->re_string); +X XDEL(re->re_prog); +X DEL(re); X} X Xstatic object * Xmakeresult(prog, buffer) -X regexp *prog; -X char *buffer; -X{ -X int n; -X object *v; -X /* Count substrings found, including \0, the main one */ -X for (n = 0; n < 10 && prog->startp[n] != NULL; n++) -X ; -X v = newtupleobject(n); -X if (v != NULL) { -X int i; -X for (i = 0; i < n; i++) { -X object *w, *u; -X long start, end; -X start = prog->startp[i] - buffer; -X end = prog->endp[i] - buffer; -X if ( (w = newtupleobject(2)) == NULL || -X (u = newintobject(start)) == NULL || -X settupleitem(w, 0, u) != 0 || -X (u = newintobject(end)) == NULL || -X settupleitem(w, 1, u) != 0) { -X XDECREF(w); -X DECREF(v); -X return NULL; -X } -X settupleitem(v, i, w); -X } -X } -X return v; +X regexp *prog; +X char *buffer; +X{ +X int n; +X object *v; +X /* Count substrings found, including \0, the main one */ +X for (n = 0; n < 10 && prog->startp[n] != NULL; n++) +X ; +X v = newtupleobject(n); +X if (v != NULL) { +X int i; +X for (i = 0; i < n; i++) { +X object *w, *u; +X long start, end; +X start = prog->startp[i] - buffer; +X end = prog->endp[i] - buffer; +X if ( (w = newtupleobject(2)) == NULL || +X (u = newintobject(start)) == NULL || +X settupleitem(w, 0, u) != 0 || +X (u = newintobject(end)) == NULL || +X settupleitem(w, 1, u) != 0) { +X XDECREF(w); +X DECREF(v); +X return NULL; +X } +X settupleitem(v, i, w); +X } +X } +X return v; X} X Xstatic object * Xregexp_exec(re, args) -X regexpobject *re; -X object *args; -X{ -X object *v; -X char *buffer; -X int offset; -X if (args != NULL && is_stringobject(args)) { -X v = args; -X offset = 0; -X } -X else if (!getstrintarg(args, &v, &offset)) -X return NULL; -X buffer = getstringvalue(v); +X regexpobject *re; +X object *args; +X{ +X object *v; +X char *buffer; +X int offset; +X if (args != NULL && is_stringobject(args)) { +X v = args; +X offset = 0; +X } +X else if (!getstrintarg(args, &v, &offset)) +X return NULL; +X buffer = getstringvalue(v); X#ifndef MULTILINE X#define reglexec(prog, str, offset) regexec((prog), (str)+(offset)) X#endif -X if (!reglexec(re->re_prog, buffer, offset)) -X return newtupleobject(0); -X return makeresult(re->re_prog, buffer); +X if (!reglexec(re->re_prog, buffer, offset)) +X return newtupleobject(0); +X return makeresult(re->re_prog, buffer); X} X Xstatic struct methodlist regexp_methods[] = { -X "exec", regexp_exec, -X {NULL, NULL} /* sentinel */ +X "exec", regexp_exec, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xregexp_getattr(re, name) -X regexpobject *re; -X char *name; +X regexpobject *re; +X char *name; X{ -X return findmethod(regexp_methods, (object *)re, name); +X return findmethod(regexp_methods, (object *)re, name); X} X Xstatic typeobject Regexptype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "regexp", /*tp_name*/ -X sizeof(regexpobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X regexp_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X regexp_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "regexp", /*tp_name*/ +X sizeof(regexpobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X regexp_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X regexp_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; X Xvoid Xregerror(str) -X char *str; +X char *str; X{ -X err_setstr(RegexpError, str); +X err_setstr(RegexpError, str); X} X Xstatic object * Xregexp_compile(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *string; -X regexp *prog; -X if (!getstrarg(args, &string)) -X return NULL; -X prog = regcomp(getstringvalue(string)); -X if (prog == NULL) -X return NULL; /* regerror() has called err_seterr() */ -X return (object *)newregexpobject(string, prog); +X object *string; +X regexp *prog; +X if (!getstrarg(args, &string)) +X return NULL; +X prog = regcomp(getstringvalue(string)); +X if (prog == NULL) +X return NULL; /* regerror() has called err_seterr() */ +X return (object *)newregexpobject(string, prog); X} X Xstatic struct methodlist regexp_global_methods[] = { -X {"compile", regexp_compile}, -X {NULL, NULL} /* sentinel */ +X {"compile", regexp_compile}, +X {NULL, NULL} /* sentinel */ X}; X Xinitregexp() X{ -X object *m, *d; -X -X m = initmodule("regexp", regexp_global_methods); -X d = getmoduledict(m); -X -X /* Initialize regexp.error exception */ -X RegexpError = newstringobject("regexp.error"); -X if (RegexpError == NULL || dictinsert(d, "error", RegexpError) != 0) -X fatal("can't define regexp.error"); +X object *m, *d; +X +X m = initmodule("regexp", regexp_global_methods); +X d = getmoduledict(m); +X +X /* Initialize regexp.error exception */ +X RegexpError = newstringobject("regexp.error"); +X if (RegexpError == NULL || dictinsert(d, "error", RegexpError) != 0) +X fatal("can't define regexp.error"); X} EOF fi echo 'Part 09 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-10-21.shar b/shar/python-0.9.1-10-21.shar index 962819a..7a88874 100644 --- a/shar/python-0.9.1-10-21.shar +++ b/shar/python-0.9.1-10-21.shar @@ -33,27 +33,27 @@ X# the lightmodel. Xmodel = [AMBIENT,0.4,0.4,0.4,LMNULL] X Xdef bindlight (bool) : -X # Initializes all settings for a window. -X if bool <> 0 : -X mmode(MVIEWING) -X perspective (900, 1.0, 1.0, 35.0) -X loadmatrix(idmat) -X # define materials and lights -X lmdef(DEFMATERIAL, 1, m1) -X lmdef(DEFMATERIAL, 2, m2) -X lmdef(DEFMATERIAL, 3, m3) -X lmdef(DEFMATERIAL, 4, m4) -X lmdef(DEFMATERIAL, 5, m5) -X lmdef(DEFMATERIAL, 6, m6) -X lmdef(DEFMATERIAL, 7, m7) -X lmdef(DEFMATERIAL, 8, m8) -X lmdef(DEFMATERIAL, 9, m9) -X lmdef(DEFLIGHT, 1, light1) -X lmdef(DEFLIGHT, 2, light2) -X lmdef(DEFLMODEL, 1, model) -X lmbind(LIGHT0,1) -X lmbind(LIGHT1,2) -X lmbind(LMODEL,1) +X # Initializes all settings for a window. +X if bool <> 0 : +X mmode(MVIEWING) +X perspective (900, 1.0, 1.0, 35.0) +X loadmatrix(idmat) +X # define materials and lights +X lmdef(DEFMATERIAL, 1, m1) +X lmdef(DEFMATERIAL, 2, m2) +X lmdef(DEFMATERIAL, 3, m3) +X lmdef(DEFMATERIAL, 4, m4) +X lmdef(DEFMATERIAL, 5, m5) +X lmdef(DEFMATERIAL, 6, m6) +X lmdef(DEFMATERIAL, 7, m7) +X lmdef(DEFMATERIAL, 8, m8) +X lmdef(DEFMATERIAL, 9, m9) +X lmdef(DEFLIGHT, 1, light1) +X lmdef(DEFLIGHT, 2, light2) +X lmdef(DEFLMODEL, 1, model) +X lmbind(LIGHT0,1) +X lmbind(LIGHT1,2) +X lmbind(LMODEL,1) EOF fi if test -s 'demo/stdwin/wdiff.py' @@ -67,17 +67,17 @@ X# A window-oriented recursive diff utility. X# NB: This uses undocumented window classing modules. X X# TO DO: -X# - faster update after moving/copying one file -X# - diff flags (-b, etc.) should be global or maintained per window -X# - use a few fixed windows instead of creating new ones all the time -X# - ways to specify patterns to skip -X# (best by pointing at a file and clicking a special menu entry!) -X# - add rcsdiff menu commands -X# - add a way to view status of selected files without opening them -X# - add a way to diff two files with different names -X# - add a way to rename files -X# - keep backups of overwritten/deleted files -X# - a way to mark specified files as uninteresting for dircmp +X# - faster update after moving/copying one file +X# - diff flags (-b, etc.) should be global or maintained per window +X# - use a few fixed windows instead of creating new ones all the time +X# - ways to specify patterns to skip +X# (best by pointing at a file and clicking a special menu entry!) +X# - add rcsdiff menu commands +X# - add a way to view status of selected files without opening them +X# - add a way to diff two files with different names +X# - add a way to rename files +X# - keep backups of overwritten/deleted files +X# - a way to mark specified files as uninteresting for dircmp X Ximport sys Ximport posix @@ -105,439 +105,439 @@ Xskiplist = ['RCS', '.Amake', 'tags', '.', '..'] X X Xdef anydiff(a, b, flags): # Display differences between any two objects -X print 'diff', flags, a, b -X if path.isdir(a) and path.isdir(b): -X w = dirdiff(a, b, flags) -X else: -X w = filediff(a, b, flags) -X addstatmenu(w, [a, b]) -X w.original_close = w.close -X w.close = close_dirwin -X return w +X print 'diff', flags, a, b +X if path.isdir(a) and path.isdir(b): +X w = dirdiff(a, b, flags) +X else: +X w = filediff(a, b, flags) +X addstatmenu(w, [a, b]) +X w.original_close = w.close +X w.close = close_dirwin +X return w X Xdef close_dirwin(w): -X close_subwindows(w, (), 0) -X w.original_close(w) +X close_subwindows(w, (), 0) +X w.original_close(w) X Xdef filediff(a, b, flags): # Display differences between two text files -X diffcmd = 'diff' -X if flags: diffcmd = diffcmd + mkarg(flags) -X diffcmd = diffcmd + mkarg(a) + mkarg(b) -X difftext = commands.getoutput(diffcmd) -X return textwin.open_readonly(mktitle(a, b), difftext) +X diffcmd = 'diff' +X if flags: diffcmd = diffcmd + mkarg(flags) +X diffcmd = diffcmd + mkarg(a) + mkarg(b) +X difftext = commands.getoutput(diffcmd) +X return textwin.open_readonly(mktitle(a, b), difftext) X Xdef dirdiff(a, b, flags): # Display differences between two directories -X data = diffdata(a, b, flags) -X w = tablewin.open(mktitle(a, b), data) -X w.flags = flags -X w.a = a -X w.b = b -X addviewmenu(w) -X addactionmenu(w) -X return w +X data = diffdata(a, b, flags) +X w = tablewin.open(mktitle(a, b), data) +X w.flags = flags +X w.a = a +X w.b = b +X addviewmenu(w) +X addactionmenu(w) +X return w X Xdef diffdata(a, b, flags): # Compute directory differences. -X # -X a_only = [('A only:', header_action), ('', header_action)] -X b_only = [('B only:', header_action), ('', header_action)] -X ab_diff = [('A <> B:', header_action), ('', header_action)] -X ab_same = [('A == B:', header_action), ('', header_action)] -X data = [a_only, b_only, ab_diff, ab_same] -X # -X a_list = dircache.listdir(a)[:] -X b_list = dircache.listdir(b)[:] -X dircache.annotate(a, a_list) -X dircache.annotate(b, b_list) -X a_list.sort() -X b_list.sort() -X # -X for x in a_list: -X if x in ['./', '../']: -X pass -X elif x not in b_list: -X a_only.append(x, a_only_action) -X else: -X ax = path.cat(a, x) -X bx = path.cat(b, x) -X if path.isdir(ax) and path.isdir(bx): -X if flags = '-r': -X same = dircmp(ax, bx) -X else: -X same = 0 -X else: -X try: -X same = cmp.cmp(ax, bx) -X except posix.error: -X same = 0 -X if same: -X ab_same.append(x, ab_same_action) -X else: -X ab_diff.append(x, ab_diff_action) -X # -X for x in b_list: -X if x in ['./', '../']: -X pass -X elif x not in a_list: -X b_only.append(x, b_only_action) -X # -X return data +X # +X a_only = [('A only:', header_action), ('', header_action)] +X b_only = [('B only:', header_action), ('', header_action)] +X ab_diff = [('A <> B:', header_action), ('', header_action)] +X ab_same = [('A == B:', header_action), ('', header_action)] +X data = [a_only, b_only, ab_diff, ab_same] +X # +X a_list = dircache.listdir(a)[:] +X b_list = dircache.listdir(b)[:] +X dircache.annotate(a, a_list) +X dircache.annotate(b, b_list) +X a_list.sort() +X b_list.sort() +X # +X for x in a_list: +X if x in ['./', '../']: +X pass +X elif x not in b_list: +X a_only.append(x, a_only_action) +X else: +X ax = path.cat(a, x) +X bx = path.cat(b, x) +X if path.isdir(ax) and path.isdir(bx): +X if flags = '-r': +X same = dircmp(ax, bx) +X else: +X same = 0 +X else: +X try: +X same = cmp.cmp(ax, bx) +X except posix.error: +X same = 0 +X if same: +X ab_same.append(x, ab_same_action) +X else: +X ab_diff.append(x, ab_diff_action) +X # +X for x in b_list: +X if x in ['./', '../']: +X pass +X elif x not in a_list: +X b_only.append(x, b_only_action) +X # +X return data X X# Re-read the directory. X# Attempt to find the selected item back. X Xdef update(w): -X setbusy(w) -X icol, irow = w.selection -X if 0 <= icol < len(w.data) and 2 <= irow < len(w.data[icol]): -X selname = w.data[icol][irow][0] -X else: -X selname = '' -X statcache.forget_dir(w.a) -X statcache.forget_dir(w.b) -X tablewin.select(w, (-1, -1)) -X tablewin.update(w, diffdata(w.a, w.b, w.flags)) -X if selname: -X for icol in range(len(w.data)): -X for irow in range(2, len(w.data[icol])): -X if w.data[icol][irow][0] = selname: -X tablewin.select(w, (icol, irow)) -X break +X setbusy(w) +X icol, irow = w.selection +X if 0 <= icol < len(w.data) and 2 <= irow < len(w.data[icol]): +X selname = w.data[icol][irow][0] +X else: +X selname = '' +X statcache.forget_dir(w.a) +X statcache.forget_dir(w.b) +X tablewin.select(w, (-1, -1)) +X tablewin.update(w, diffdata(w.a, w.b, w.flags)) +X if selname: +X for icol in range(len(w.data)): +X for irow in range(2, len(w.data[icol])): +X if w.data[icol][irow][0] = selname: +X tablewin.select(w, (icol, irow)) +X break X X# Action functions for table items in directory diff windows X Xdef header_action(w, string, (icol, irow), (pos, clicks, button, mask)): -X tablewin.select(w, (-1, -1)) +X tablewin.select(w, (-1, -1)) X Xdef a_only_action(w, string, (icol, irow), (pos, clicks, button, mask)): -X tablewin.select(w, (icol, irow)) -X if clicks = 2: -X w2 = anyopen(path.cat(w.a, string)) -X if w2: -X w2.parent = w +X tablewin.select(w, (icol, irow)) +X if clicks = 2: +X w2 = anyopen(path.cat(w.a, string)) +X if w2: +X w2.parent = w X Xdef b_only_action(w, string, (icol, irow), (pos, clicks, button, mask)): -X tablewin.select(w, (icol, irow)) -X if clicks = 2: -X w2 = anyopen(path.cat(w.b, string)) -X if w2: -X w2.parent = w +X tablewin.select(w, (icol, irow)) +X if clicks = 2: +X w2 = anyopen(path.cat(w.b, string)) +X if w2: +X w2.parent = w X Xdef ab_diff_action(w, string, (icol, irow), (pos, clicks, button, mask)): -X tablewin.select(w, (icol, irow)) -X if clicks = 2: -X w2 = anydiff(path.cat(w.a, string), path.cat(w.b, string), '') -X w2.parent = w +X tablewin.select(w, (icol, irow)) +X if clicks = 2: +X w2 = anydiff(path.cat(w.a, string), path.cat(w.b, string), '') +X w2.parent = w X Xdef ab_same_action(w, string, sel, detail): -X ax = path.cat(w.a, string) -X if path.isdir(ax): -X ab_diff_action(w, string, sel, detail) -X else: -X a_only_action(w, string, sel, detail) +X ax = path.cat(w.a, string) +X if path.isdir(ax): +X ab_diff_action(w, string, sel, detail) +X else: +X a_only_action(w, string, sel, detail) X Xdef anyopen(name): # Open any kind of document, ignore errors -X try: -X w = anywin.open(name) -X except (RuntimeError, posix.error): -X stdwin.message('Can\'t open ' + name) -X return 0 -X addstatmenu(w, [name]) -X return w +X try: +X w = anywin.open(name) +X except (RuntimeError, posix.error): +X stdwin.message('Can\'t open ' + name) +X return 0 +X addstatmenu(w, [name]) +X return w X Xdef dircmp(a, b): # Compare whether two directories are the same -X # To make this as fast as possible, it uses the statcache -X print ' dircmp', a, b -X a_list = dircache.listdir(a) -X b_list = dircache.listdir(b) -X for x in a_list: -X if x in skiplist: -X pass -X elif x not in b_list: -X return 0 -X else: -X ax = path.cat(a, x) -X bx = path.cat(b, x) -X if statcache.isdir(ax) and statcache.isdir(bx): -X if not dircmp(ax, bx): return 0 -X else: -X try: -X if not cmpcache.cmp(ax, bx): return 0 -X except posix.error: -X return 0 -X for x in b_list: -X if x in skiplist: -X pass -X elif x not in a_list: -X return 0 -X return 1 +X # To make this as fast as possible, it uses the statcache +X print ' dircmp', a, b +X a_list = dircache.listdir(a) +X b_list = dircache.listdir(b) +X for x in a_list: +X if x in skiplist: +X pass +X elif x not in b_list: +X return 0 +X else: +X ax = path.cat(a, x) +X bx = path.cat(b, x) +X if statcache.isdir(ax) and statcache.isdir(bx): +X if not dircmp(ax, bx): return 0 +X else: +X try: +X if not cmpcache.cmp(ax, bx): return 0 +X except posix.error: +X return 0 +X for x in b_list: +X if x in skiplist: +X pass +X elif x not in a_list: +X return 0 +X return 1 X X X# View menu (for dir diff windows only) X Xdef addviewmenu(w): -X w.viewmenu = m = w.menucreate('View') -X m.action = [] -X add(m, 'diff -r A B', diffr_ab) -X add(m, 'diff A B', diff_ab) -X add(m, 'diff -b A B', diffb_ab) -X add(m, 'diff -c A B', diffc_ab) -X add(m, 'gdiff A B', gdiff_ab) -X add(m, ('Open A ', 'A'), open_a) -X add(m, ('Open B ', 'B'), open_b) -X add(m, 'Rescan', rescan) -X add(m, 'Rescan -r', rescan_r) +X w.viewmenu = m = w.menucreate('View') +X m.action = [] +X add(m, 'diff -r A B', diffr_ab) +X add(m, 'diff A B', diff_ab) +X add(m, 'diff -b A B', diffb_ab) +X add(m, 'diff -c A B', diffc_ab) +X add(m, 'gdiff A B', gdiff_ab) +X add(m, ('Open A ', 'A'), open_a) +X add(m, ('Open B ', 'B'), open_b) +X add(m, 'Rescan', rescan) +X add(m, 'Rescan -r', rescan_r) X X# Action menu (for dir diff windows only) X Xdef addactionmenu(w): -X w.actionmenu = m = w.menucreate('Action') -X m.action = [] -X add(m, 'cp A B', cp_ab) -X add(m, 'rm B', rm_b) -X add(m, '', nop) -X add(m, 'cp B A', cp_ba) -X add(m, 'rm A', rm_a) +X w.actionmenu = m = w.menucreate('Action') +X m.action = [] +X add(m, 'cp A B', cp_ab) +X add(m, 'rm B', rm_b) +X add(m, '', nop) +X add(m, 'cp B A', cp_ba) +X add(m, 'rm A', rm_a) X X# Main menu (global): X Xdef mainmenu(): -X m = stdwin.menucreate('Wdiff') -X m.action = [] -X add(m, ('Quit wdiff', 'Q'), quit_wdiff) -X add(m, 'Close subwindows', close_subwindows) -X return m +X m = stdwin.menucreate('Wdiff') +X m.action = [] +X add(m, ('Quit wdiff', 'Q'), quit_wdiff) +X add(m, 'Close subwindows', close_subwindows) +X return m X Xdef add(m, text, action): -X m.additem(text) -X m.action.append(action) +X m.additem(text) +X m.action.append(action) X Xdef quit_wdiff(w, m, item): -X if askyesno('Really quit wdiff altogether?', 1): -X sys.exit(0) +X if askyesno('Really quit wdiff altogether?', 1): +X sys.exit(0) X Xdef close_subwindows(w, m, item): -X while 1: -X for w2 in gwin.windows: -X if w2.parent = w: -X close_subwindows(w2, m, item) -X w2.close(w2) -X break # inner loop, continue outer loop -X else: -X break # outer loop +X while 1: +X for w2 in gwin.windows: +X if w2.parent = w: +X close_subwindows(w2, m, item) +X w2.close(w2) +X break # inner loop, continue outer loop +X else: +X break # outer loop X Xdef diffr_ab(w, m, item): -X dodiff(w, '-r') +X dodiff(w, '-r') X Xdef diff_ab(w, m, item): -X dodiff(w, '') +X dodiff(w, '') X Xdef diffb_ab(w, m, item): -X dodiff(w, '-b') +X dodiff(w, '-b') X Xdef diffc_ab(w, m, item): -X dodiff(w, '-c') +X dodiff(w, '-c') X Xdef gdiff_ab(w, m, item): # Call SGI's gdiff utility -X x = getselection(w) -X if x: -X a, b = path.cat(w.a, x), path.cat(w.b, x) -X if path.isdir(a) or path.isdir(b): -X stdwin.fleep() # This is for files only -X else: -X diffcmd = 'gdiff' -X diffcmd = diffcmd + mkarg(a) + mkarg(b) + ' &' -X print diffcmd -X sts = posix.system(diffcmd) -X if sts: print 'Exit status', sts +X x = getselection(w) +X if x: +X a, b = path.cat(w.a, x), path.cat(w.b, x) +X if path.isdir(a) or path.isdir(b): +X stdwin.fleep() # This is for files only +X else: +X diffcmd = 'gdiff' +X diffcmd = diffcmd + mkarg(a) + mkarg(b) + ' &' +X print diffcmd +X sts = posix.system(diffcmd) +X if sts: print 'Exit status', sts X Xdef dodiff(w, flags): -X x = getselection(w) -X if x: -X w2 = anydiff(path.cat(w.a, x), path.cat(w.b, x), flags) -X w2.parent = w +X x = getselection(w) +X if x: +X w2 = anydiff(path.cat(w.a, x), path.cat(w.b, x), flags) +X w2.parent = w X Xdef open_a(w, m, item): -X x = getselection(w) -X if x: -X w2 = anyopen(path.cat(w.a, x)) -X if w2: -X w2.parent = w +X x = getselection(w) +X if x: +X w2 = anyopen(path.cat(w.a, x)) +X if w2: +X w2.parent = w X Xdef open_b(w, m, item): -X x = getselection(w) -X if x: -X w2 = anyopen(path.cat(w.b, x)) -X if w2: -X w2.parent = w +X x = getselection(w) +X if x: +X w2 = anyopen(path.cat(w.b, x)) +X if w2: +X w2.parent = w X Xdef rescan(w, m, item): -X w.flags = '' -X update(w) +X w.flags = '' +X update(w) X Xdef rescan_r(w, m, item): -X w.flags = '-r' -X update(w) +X w.flags = '-r' +X update(w) X Xdef rm_a(w, m, item): -X x = getselection(w) -X if x: -X if x[-1:] = '/': x = x[:-1] -X x = path.cat(w.a, x) -X if path.isdir(x): -X if askyesno('Recursively remove A directory ' + x, 1): -X runcmd('rm -rf' + mkarg(x)) -X else: -X runcmd('rm -f' + mkarg(x)) -X update(w) +X x = getselection(w) +X if x: +X if x[-1:] = '/': x = x[:-1] +X x = path.cat(w.a, x) +X if path.isdir(x): +X if askyesno('Recursively remove A directory ' + x, 1): +X runcmd('rm -rf' + mkarg(x)) +X else: +X runcmd('rm -f' + mkarg(x)) +X update(w) X Xdef rm_b(w, m, item): -X x = getselection(w) -X if x: -X if x[-1:] = '/': x = x[:-1] -X x = path.cat(w.b, x) -X if path.isdir(x): -X if askyesno('Recursively remove B directory ' + x, 1): -X runcmd('rm -rf' + mkarg(x)) -X else: -X runcmd('rm -f' + mkarg(x)) -X update(w) +X x = getselection(w) +X if x: +X if x[-1:] = '/': x = x[:-1] +X x = path.cat(w.b, x) +X if path.isdir(x): +X if askyesno('Recursively remove B directory ' + x, 1): +X runcmd('rm -rf' + mkarg(x)) +X else: +X runcmd('rm -f' + mkarg(x)) +X update(w) X Xdef cp_ab(w, m, item): -X x = getselection(w) -X if x: -X if x[-1:] = '/': x = x[:-1] -X ax = path.cat(w.a, x) -X bx = path.cat(w.b, x) -X if path.isdir(ax): -X if path.exists(bx): -X m = 'Can\'t copy directory to existing target' -X stdwin.message(m) -X return -X runcmd('cp -r' + mkarg(ax) + mkarg(w.b)) -X else: -X runcmd('cp' + mkarg(ax) + mk2arg(w.b, x)) -X update(w) +X x = getselection(w) +X if x: +X if x[-1:] = '/': x = x[:-1] +X ax = path.cat(w.a, x) +X bx = path.cat(w.b, x) +X if path.isdir(ax): +X if path.exists(bx): +X m = 'Can\'t copy directory to existing target' +X stdwin.message(m) +X return +X runcmd('cp -r' + mkarg(ax) + mkarg(w.b)) +X else: +X runcmd('cp' + mkarg(ax) + mk2arg(w.b, x)) +X update(w) X Xdef cp_ba(w, m, item): -X x = getselection(w) -X if x: -X if x[-1:] = '/': x = x[:-1] -X ax = path.cat(w.a, x) -X bx = path.cat(w.b, x) -X if path.isdir(bx): -X if path.exists(ax): -X m = 'Can\'t copy directory to existing target' -X stdwin.message(m) -X return -X runcmd('cp -r' + mkarg(bx) + mkarg(w.a)) -X else: -X runcmd('cp' + mk2arg(w.b, x) + mkarg(ax)) -X update(w) +X x = getselection(w) +X if x: +X if x[-1:] = '/': x = x[:-1] +X ax = path.cat(w.a, x) +X bx = path.cat(w.b, x) +X if path.isdir(bx): +X if path.exists(ax): +X m = 'Can\'t copy directory to existing target' +X stdwin.message(m) +X return +X runcmd('cp -r' + mkarg(bx) + mkarg(w.a)) +X else: +X runcmd('cp' + mk2arg(w.b, x) + mkarg(ax)) +X update(w) X Xdef nop(args): -X pass +X pass X Xdef getselection(w): -X icol, irow = w.selection -X if 0 <= icol < len(w.data): -X if 0 <= irow < len(w.data[icol]): -X return w.data[icol][irow][0] -X stdwin.message('no selection') -X return '' +X icol, irow = w.selection +X if 0 <= icol < len(w.data): +X if 0 <= irow < len(w.data[icol]): +X return w.data[icol][irow][0] +X stdwin.message('no selection') +X return '' X Xdef runcmd(cmd): -X print cmd -X sts, output = commands.getstatusoutput(cmd) -X if sts or output: -X if not output: -X output = 'Exit status ' + `sts` -X stdwin.message(output) +X print cmd +X sts, output = commands.getstatusoutput(cmd) +X if sts or output: +X if not output: +X output = 'Exit status ' + `sts` +X stdwin.message(output) X X X# Status menu (for all kinds of windows) X Xdef addstatmenu(w, files): -X w.statmenu = m = w.menucreate('Stat') -X m.files = files -X m.action = [] -X for file in files: -X m.additem(commands.getstatus(file)) -X m.action.append(stataction) +X w.statmenu = m = w.menucreate('Stat') +X m.files = files +X m.action = [] +X for file in files: +X m.additem(commands.getstatus(file)) +X m.action.append(stataction) X Xdef stataction(w, m, item): # Menu item action for stat menu -X file = m.files[item] -X try: -X m.setitem(item, commands.getstatus(file)) -X except posix.error: -X stdwin.message('Can\'t get status for ' + file) +X file = m.files[item] +X try: +X m.setitem(item, commands.getstatus(file)) +X except posix.error: +X stdwin.message('Can\'t get status for ' + file) X X X# Compute a suitable window title from two paths X Xdef mktitle(a, b): -X if a = b: return a -X i = 1 -X while a[-i:] = b[-i:]: i = i+1 -X i = i-1 -X if not i: -X return a + ' ' + b -X else: -X return '{' + a[:-i] + ',' + b[:-i] + '}' + a[-i:] +X if a = b: return a +X i = 1 +X while a[-i:] = b[-i:]: i = i+1 +X i = i-1 +X if not i: +X return a + ' ' + b +X else: +X return '{' + a[:-i] + ',' + b[:-i] + '}' + a[-i:] X X X# Ask a confirmation question X Xdef askyesno(prompt, default): -X try: -X return stdwin.askync(prompt, default) -X except KeyboardInterrupt: -X return 0 +X try: +X return stdwin.askync(prompt, default) +X except KeyboardInterrupt: +X return 0 X X X# Display a message "busy" in a window, and mark it for updating X Xdef setbusy(w): -X left, top = w.getorigin() -X width, height = w.getwinsize() -X right, bottom = left + width, top + height -X d = w.begindrawing() -X d.erase((0, 0), (10000, 10000)) -X text = 'Busy...' -X textwidth = d.textwidth(text) -X textheight = d.lineheight() -X h, v = left + (width-textwidth)/2, top + (height-textheight)/2 -X d.text((h, v), text) -X del d -X w.change((0, 0), (10000, 10000)) +X left, top = w.getorigin() +X width, height = w.getwinsize() +X right, bottom = left + width, top + height +X d = w.begindrawing() +X d.erase((0, 0), (10000, 10000)) +X text = 'Busy...' +X textwidth = d.textwidth(text) +X textheight = d.lineheight() +X h, v = left + (width-textwidth)/2, top + (height-textheight)/2 +X d.text((h, v), text) +X del d +X w.change((0, 0), (10000, 10000)) X X X# Main function X Xdef main(): -X print 'wdiff: warning: this version does NOT yet make backups' -X argv = sys.argv -X flags = '' -X if len(argv) >= 2 and argv[1][:1] = '-': -X flags = argv[1] -X del argv[1] -X m = mainmenu() # Create menu earlier than windows -X if len(argv) = 2: # 1 argument -X w = anyopen(argv[1]) -X if not w: return -X elif len(argv) = 3: # 2 arguments -X w = anydiff(argv[1], argv[2], flags) -X w.parent = () -X else: -X sys.stdout = sys.stderr -X print 'usage:', argv[0], '[diff-flags] dir-1 [dir-2]' -X sys.exit(2) -X del w # It's preserved in gwin.windows -X while 1: -X try: -X gwin.mainloop() -X break -X except KeyboardInterrupt: -X pass # Just continue... +X print 'wdiff: warning: this version does NOT yet make backups' +X argv = sys.argv +X flags = '' +X if len(argv) >= 2 and argv[1][:1] = '-': +X flags = argv[1] +X del argv[1] +X m = mainmenu() # Create menu earlier than windows +X if len(argv) = 2: # 1 argument +X w = anyopen(argv[1]) +X if not w: return +X elif len(argv) = 3: # 2 arguments +X w = anydiff(argv[1], argv[2], flags) +X w.parent = () +X else: +X sys.stdout = sys.stderr +X print 'usage:', argv[0], '[diff-flags] dir-1 [dir-2]' +X sys.exit(2) +X del w # It's preserved in gwin.windows +X while 1: +X try: +X gwin.mainloop() +X break +X except KeyboardInterrupt: +X pass # Just continue... X X# Start the main function (this is a script) Xmain() @@ -555,27 +555,27 @@ X# X# Design choices: X# X# - Names used for functions are not exactly those used by C Tcl. -X# In Python, names without 'Tcl_' prefix are acceptable because -X# names are less global than in C (and often they are prefixed -X# with a module name anyway). Parameter conventions also differ. +X# In Python, names without 'Tcl_' prefix are acceptable because +X# names are less global than in C (and often they are prefixed +X# with a module name anyway). Parameter conventions also differ. X# X# - The Tcl Interpreter type is implemented using a Python class. -X# Almost all functions with an Interpreter as first parameter are -X# methods of this class. -X# Applications can create derived classes to add additional commands -X# or to override specific internal functions. +X# Almost all functions with an Interpreter as first parameter are +X# methods of this class. +X# Applications can create derived classes to add additional commands +X# or to override specific internal functions. X# X# - Tcl errors are mapped to Python exceptions. -X# (I bet Ousterhout would have done the same in a language with -X# a proper exception mechanism). +X# (I bet Ousterhout would have done the same in a language with +X# a proper exception mechanism). X# X# - Tcl expressions are evaluated by Python's built-in function eval(). -X# This makes Python Tcl scripts incompatible with C Tcl scripts, -X# but is the only sensible solution for a quick-and-dirty version. -X# It also makes an escape to Python possible. +X# This makes Python Tcl scripts incompatible with C Tcl scripts, +X# but is the only sensible solution for a quick-and-dirty version. +X# It also makes an escape to Python possible. X# X# - The Backslash function interprets \<newline>, since it -X# can return a string instead of a character. +X# can return a string instead of a character. X X Xfrom TclUtil import * @@ -589,59 +589,59 @@ XTclReturn = 'TclReturn' X X Xclass CmdBuf(): -X # -X def Create(buffer): -X buffer.string = '' -X return buffer -X # -X def Assemble(buffer, str): -X buffer.string = buffer.string + str -X if buffer.string[-1:] = '\n': -X i, end = 0, len(buffer.string) -X try: -X while i < end: -X list, i = FindNextCommand( \ -X buffer.string, i, end, 0) -X except TclMatchingError: -X return '' -X except TclSyntaxError: -X pass # Let Eval() return the error -X ret = buffer.string -X buffer.string = '' -X return ret -X else: -X return '' +X # +X def Create(buffer): +X buffer.string = '' +X return buffer +X # +X def Assemble(buffer, str): +X buffer.string = buffer.string + str +X if buffer.string[-1:] = '\n': +X i, end = 0, len(buffer.string) +X try: +X while i < end: +X list, i = FindNextCommand( \ +X buffer.string, i, end, 0) +X except TclMatchingError: +X return '' +X except TclSyntaxError: +X pass # Let Eval() return the error +X ret = buffer.string +X buffer.string = '' +X return ret +X else: +X return '' X X Xclass _Frame(): -X def Create(frame): -X frame.locals = {} -X return frame +X def Create(frame): +X frame.locals = {} +X return frame X Xclass _Proc(): -X # -X def Create(proc, (interp, args, body)): -X proc.interp = interp -X proc.args = SplitList(args) # Do this once here -X proc.body = body -X return proc -X # -X def Call(proc, argv): -X if len(argv) <> len(proc.args)+1: -X raise TclRuntimeError, \ -X 'wrong # args to proc "' + \ -X argv[0] + '"' -X # XXX No defaults or variable length 'args' yet -X frame = _Frame().Create() -X for i in range(len(proc.args)): -X frame.locals[proc.args[i]] = argv[i+1] -X proc.interp.stack.append(frame) -X try: -X value = proc.interp.Eval(proc.body) -X except TclReturn, value: -X pass -X del proc.interp.stack[-1:] -X return value +X # +X def Create(proc, (interp, args, body)): +X proc.interp = interp +X proc.args = SplitList(args) # Do this once here +X proc.body = body +X return proc +X # +X def Call(proc, argv): +X if len(argv) <> len(proc.args)+1: +X raise TclRuntimeError, \ +X 'wrong # args to proc "' + \ +X argv[0] + '"' +X # XXX No defaults or variable length 'args' yet +X frame = _Frame().Create() +X for i in range(len(proc.args)): +X frame.locals[proc.args[i]] = argv[i+1] +X proc.interp.stack.append(frame) +X try: +X value = proc.interp.Eval(proc.body) +X except TclReturn, value: +X pass +X del proc.interp.stack[-1:] +X return value X X Ximport regexp @@ -649,311 +649,311 @@ X_expand_prog = regexp.compile('([^[$\\]+|\n)*') Xdel regexp X Xclass Interpreter(): -X # -X def Create(interp): -X interp.globals = {} -X interp.commands = {} -X interp.stack = [] -X interp.commands['break'] = interp.BreakCmd -X interp.commands['concat'] = interp.ConcatCmd -X interp.commands['continue'] = interp.ContinueCmd -X interp.commands['echo'] = interp.EchoCmd -X interp.commands['eval'] = interp.EvalCmd -X interp.commands['expr'] = interp.ExprCmd -X interp.commands['for'] = interp.ForCmd -X interp.commands['glob'] = interp.GlobCmd -X interp.commands['global'] = interp.GlobalCmd -X interp.commands['if'] = interp.IfCmd -X interp.commands['index'] = interp.IndexCmd -X interp.commands['list'] = interp.ListCmd -X interp.commands['proc'] = interp.ProcCmd -X interp.commands['rename'] = interp.RenameCmd -X interp.commands['return'] = interp.ReturnCmd -X interp.commands['set'] = interp.SetCmd -X return interp -X # -X def Delete(interp): -X # -X # Only break circular references here; -X # most things will be garbage-collected. -X # -X for name in interp.commands.keys(): -X del interp.commands[name] -X # -X def CreateCommand(interp, (name, proc)): -X interp.commands[name] = proc -X # -X def DeleteCommand(interp, (name)): -X del interp.commands[name] -X # -X # Local variables are maintained on the stack. -X # A local variable with value "None" is a dummy -X # meaning that the corresponding global variable -X # should be used. -X # -X def GetVar(interp, varName): -X dict = interp.globals -X if interp.stack: -X d = interp.stack[-1:][0].locals -X if d.has_key(varName) and d[varName] = None: -X pass -X else: -X dict = d -X if not dict.has_key(varName): -X raise TclRuntimeError, \ -X 'Variable "' + varName + '" not found' -X return dict[varName] -X # -X def SetVar(interp, (varName, newValue)): -X dict = interp.globals -X if interp.stack: -X d = interp.stack[-1:][0].locals -X if d.has_key(varName) and d[varName] = None: -X pass -X else: -X dict = d -X dict[varName] = newValue -X # -X def Expand(interp, (str, i, end)): -X if end <= i: return '' -X if str[i] = '{' and str[end-1] = '}': -X return str[i+1:end-1] -X if str[i] = '"' and str[end-1] = '"': -X i, end = i+1, end-1 -X result = '' -X while i < end: -X c = str[i] -X if c = '\\': -X x, i = Backslash(str, i, end) -X result = result + x -X elif c = '[': -X j = BalanceBrackets(str, i, end) -X x = interp.EvalBasic(str, i+1, j-1, 1) -X result = result + x -X i = j -X elif c = '$': -X i = i+1 -X j = FindVarName(str, i, end) -X name = str[i:j] -X i = j -X if not name: -X result = result + '$' -X else: -X if name[:1] = '{' and name[-1:] = '}': -X name = name[1:-1] -X result = result + interp.GetVar(name) -X else: -X j = _expand_prog.exec(str, i) -X j = min(j, end) -X result = result + str[i:j] -X i = j -X return result -X # -X def EvalBasic(interp, (str, i, end, bracketed)): -X result = '' -X while i < end: -X indexargv, i = FindNextCommand( \ -X str, i, end, bracketed) -X if indexargv: -X argv = [] -X for x, y in indexargv: -X arg = interp.Expand(str, x, y) -X argv.append(arg) -X name = argv[0] -X if not interp.commands.has_key(name): -X raise TclRuntimeError, \ -X 'Command "' + name + \ -X '" not found' -X result = interp.commands[name](argv) -X return result -X # -X def Eval(interp, str): -X return interp.EvalBasic(str, 0, len(str), 0) -X # -X def ExprBasic(interp, (str, begin, end)): -X expr = interp.Expand(str, begin, end) -X i = SkipSpaces(expr, 0, len(expr)) -X expr = expr[i:] -X try: -X return eval(expr, {}) -X except (NameError, TypeError, RuntimeError, EOFError), msg: -X import sys -X raise TclRuntimeError, sys.exc_type + ': ' + msg -X # -X def Expr(interp, str): -X return interp.ExprBasic(str, 0, len(str)) -X # -X # The rest are command implementations -X # -X def BreakCmd(interp, argv): -X if len(argv) <> 1: -X raise TclRuntimeError, 'usage: break' -X raise TclBreak -X # -X def ConcatCmd(interp, argv): -X if len(argv) < 2: -X raise TclRuntimeError, 'usage: concat arg ...' -X return Concat(argv[1:]) -X # -X def ContinueCmd(interp, argv): -X if len(argv) <> 1: -X raise TclRuntimeError, 'usage: continue' -X raise TclContinue -X # -X def EchoCmd(interp, argv): -X for arg in argv[1:]: print arg, -X print -X return '' -X # -X def EvalCmd(interp, argv): -X if len(argv) < 2: -X raise TclRuntimeError, 'usage: eval arg [arg ...]' -X str = Concat(argv[1:]) -X return interp.Eval(str) -X # -X def ExprCmd(interp, argv): -X if len(argv) <> 2: -X raise TclRuntimeError, 'usage: expr expression' -X expr = argv[1] -X result = interp.Expr(expr) -X if type(result) <> type(''): result = `result` -X return result -X # -X def ForCmd(interp, argv): -X if len(argv) <> 5: -X raise TclRuntimeError, \ -X 'usage: for start test next body' -X x = interp.Eval(argv[1]) -X while interp.Expr(argv[2]): -X try: -X x = interp.Eval(argv[4]) -X except TclBreak: -X break -X except TclContinue: -X pass -X x = interp.Eval(argv[3]) -X return '' -X # -X def GlobCmd(interp, argv): -X import macglob -X if len(argv) < 2: -X raise TclRuntimeError, 'usage: glob pattern ...' -X list = [] -X for pat in argv[1:]: -X list = list + macglob.glob(pat) -X if not list: -X raise TclRuntimeError, 'no match for glob pattern(s)' -X return BuildList(list) -X # -X def GlobalCmd(interp, argv): -X if len(argv) < 2: -X raise TclRuntimeError, 'usage: global varname ...' -X if not interp.stack: -X raise TclRuntimeError, 'global used outside proc' -X dict = interp.stack[-1:][0].locals -X for name in argv[1:]: -X dict[name] = None -X return '' -X # -X def IfCmd(interp, argv): -X argv = argv[:] -X if len(argv) > 2 and argv[2] = 'then': del argv[2] -X if len(argv) > 3 and argv[3] = 'else': del argv[3] -X if not 3 <= len(argv) <= 4: -X raise TclRuntimeError, \ -X 'usage: if test [then] trueBody [else] falseBody' -X if interp.Expr(argv[1]): -X return interp.Eval(argv[2]) -X if len(argv) > 3: -X return interp.Eval(argv[3]) -X return '' -X # -X def IndexCmd(interp, argv): -X if len(argv) <> 3: -X raise TclRuntimeError, 'usage: index value index' -X import string -X try: -X index = string.atoi(argv[2]) -X if index < 0: raise string.atoi_error -X except string.atoi_error: -X raise TclRuntimeError, 'bad index: ' + argv[2] -X list = SplitList(argv[1]) -X if index >= len(list): return '' -X return list[index] -X # -X def ListCmd(interp, argv): -X if len(argv) < 2: -X raise TclRuntimeError, 'usage: list arg ...' -X return BuildList(argv[1:]) -X # -X def ProcCmd(interp, argv): -X if len(argv) <> 4: -X raise TclRuntimeError, 'usage: proc name args body' -X x = _Proc().Create(interp, argv[2], argv[3]) -X interp.CreateCommand(argv[1], x.Call) -X return '' -X # -X def RenameCmd(interp, argv): -X if len(argv) <> 3: -X raise TclRuntimeError, 'usage: rename oldName newName' -X oldName, newName = argv[1], argv[2] -X if not interp.commands.has_key(oldName): -X raise TclRuntimeError, \ -X 'command "' + oldName + '" not found' -X if newName: interp.commands[newName] = interp.commands[oldName] -X del interp.commands[oldName] -X return '' -X # -X def ReturnCmd(interp, argv): -X if not 1 <= len(argv) <= 2: -X raise TclRuntimeError, 'usage: return [arg]' -X if len(argv) = 1: raise TclReturn, '' -X raise TclReturn, argv[1] -X # -X def SetCmd(interp, argv): -X n = len(argv) -X if not 2 <= n <= 3: -X raise TclRuntimeError, 'usage: set varname [newvalue]' -X if n = 2: return interp.GetVar(argv[1]) -X interp.SetVar(argv[1], argv[2]) -X return '' +X # +X def Create(interp): +X interp.globals = {} +X interp.commands = {} +X interp.stack = [] +X interp.commands['break'] = interp.BreakCmd +X interp.commands['concat'] = interp.ConcatCmd +X interp.commands['continue'] = interp.ContinueCmd +X interp.commands['echo'] = interp.EchoCmd +X interp.commands['eval'] = interp.EvalCmd +X interp.commands['expr'] = interp.ExprCmd +X interp.commands['for'] = interp.ForCmd +X interp.commands['glob'] = interp.GlobCmd +X interp.commands['global'] = interp.GlobalCmd +X interp.commands['if'] = interp.IfCmd +X interp.commands['index'] = interp.IndexCmd +X interp.commands['list'] = interp.ListCmd +X interp.commands['proc'] = interp.ProcCmd +X interp.commands['rename'] = interp.RenameCmd +X interp.commands['return'] = interp.ReturnCmd +X interp.commands['set'] = interp.SetCmd +X return interp +X # +X def Delete(interp): +X # +X # Only break circular references here; +X # most things will be garbage-collected. +X # +X for name in interp.commands.keys(): +X del interp.commands[name] +X # +X def CreateCommand(interp, (name, proc)): +X interp.commands[name] = proc +X # +X def DeleteCommand(interp, (name)): +X del interp.commands[name] +X # +X # Local variables are maintained on the stack. +X # A local variable with value "None" is a dummy +X # meaning that the corresponding global variable +X # should be used. +X # +X def GetVar(interp, varName): +X dict = interp.globals +X if interp.stack: +X d = interp.stack[-1:][0].locals +X if d.has_key(varName) and d[varName] = None: +X pass +X else: +X dict = d +X if not dict.has_key(varName): +X raise TclRuntimeError, \ +X 'Variable "' + varName + '" not found' +X return dict[varName] +X # +X def SetVar(interp, (varName, newValue)): +X dict = interp.globals +X if interp.stack: +X d = interp.stack[-1:][0].locals +X if d.has_key(varName) and d[varName] = None: +X pass +X else: +X dict = d +X dict[varName] = newValue +X # +X def Expand(interp, (str, i, end)): +X if end <= i: return '' +X if str[i] = '{' and str[end-1] = '}': +X return str[i+1:end-1] +X if str[i] = '"' and str[end-1] = '"': +X i, end = i+1, end-1 +X result = '' +X while i < end: +X c = str[i] +X if c = '\\': +X x, i = Backslash(str, i, end) +X result = result + x +X elif c = '[': +X j = BalanceBrackets(str, i, end) +X x = interp.EvalBasic(str, i+1, j-1, 1) +X result = result + x +X i = j +X elif c = '$': +X i = i+1 +X j = FindVarName(str, i, end) +X name = str[i:j] +X i = j +X if not name: +X result = result + '$' +X else: +X if name[:1] = '{' and name[-1:] = '}': +X name = name[1:-1] +X result = result + interp.GetVar(name) +X else: +X j = _expand_prog.exec(str, i) +X j = min(j, end) +X result = result + str[i:j] +X i = j +X return result +X # +X def EvalBasic(interp, (str, i, end, bracketed)): +X result = '' +X while i < end: +X indexargv, i = FindNextCommand( \ +X str, i, end, bracketed) +X if indexargv: +X argv = [] +X for x, y in indexargv: +X arg = interp.Expand(str, x, y) +X argv.append(arg) +X name = argv[0] +X if not interp.commands.has_key(name): +X raise TclRuntimeError, \ +X 'Command "' + name + \ +X '" not found' +X result = interp.commands[name](argv) +X return result +X # +X def Eval(interp, str): +X return interp.EvalBasic(str, 0, len(str), 0) +X # +X def ExprBasic(interp, (str, begin, end)): +X expr = interp.Expand(str, begin, end) +X i = SkipSpaces(expr, 0, len(expr)) +X expr = expr[i:] +X try: +X return eval(expr, {}) +X except (NameError, TypeError, RuntimeError, EOFError), msg: +X import sys +X raise TclRuntimeError, sys.exc_type + ': ' + msg +X # +X def Expr(interp, str): +X return interp.ExprBasic(str, 0, len(str)) +X # +X # The rest are command implementations +X # +X def BreakCmd(interp, argv): +X if len(argv) <> 1: +X raise TclRuntimeError, 'usage: break' +X raise TclBreak +X # +X def ConcatCmd(interp, argv): +X if len(argv) < 2: +X raise TclRuntimeError, 'usage: concat arg ...' +X return Concat(argv[1:]) +X # +X def ContinueCmd(interp, argv): +X if len(argv) <> 1: +X raise TclRuntimeError, 'usage: continue' +X raise TclContinue +X # +X def EchoCmd(interp, argv): +X for arg in argv[1:]: print arg, +X print +X return '' +X # +X def EvalCmd(interp, argv): +X if len(argv) < 2: +X raise TclRuntimeError, 'usage: eval arg [arg ...]' +X str = Concat(argv[1:]) +X return interp.Eval(str) +X # +X def ExprCmd(interp, argv): +X if len(argv) <> 2: +X raise TclRuntimeError, 'usage: expr expression' +X expr = argv[1] +X result = interp.Expr(expr) +X if type(result) <> type(''): result = `result` +X return result +X # +X def ForCmd(interp, argv): +X if len(argv) <> 5: +X raise TclRuntimeError, \ +X 'usage: for start test next body' +X x = interp.Eval(argv[1]) +X while interp.Expr(argv[2]): +X try: +X x = interp.Eval(argv[4]) +X except TclBreak: +X break +X except TclContinue: +X pass +X x = interp.Eval(argv[3]) +X return '' +X # +X def GlobCmd(interp, argv): +X import macglob +X if len(argv) < 2: +X raise TclRuntimeError, 'usage: glob pattern ...' +X list = [] +X for pat in argv[1:]: +X list = list + macglob.glob(pat) +X if not list: +X raise TclRuntimeError, 'no match for glob pattern(s)' +X return BuildList(list) +X # +X def GlobalCmd(interp, argv): +X if len(argv) < 2: +X raise TclRuntimeError, 'usage: global varname ...' +X if not interp.stack: +X raise TclRuntimeError, 'global used outside proc' +X dict = interp.stack[-1:][0].locals +X for name in argv[1:]: +X dict[name] = None +X return '' +X # +X def IfCmd(interp, argv): +X argv = argv[:] +X if len(argv) > 2 and argv[2] = 'then': del argv[2] +X if len(argv) > 3 and argv[3] = 'else': del argv[3] +X if not 3 <= len(argv) <= 4: +X raise TclRuntimeError, \ +X 'usage: if test [then] trueBody [else] falseBody' +X if interp.Expr(argv[1]): +X return interp.Eval(argv[2]) +X if len(argv) > 3: +X return interp.Eval(argv[3]) +X return '' +X # +X def IndexCmd(interp, argv): +X if len(argv) <> 3: +X raise TclRuntimeError, 'usage: index value index' +X import string +X try: +X index = string.atoi(argv[2]) +X if index < 0: raise string.atoi_error +X except string.atoi_error: +X raise TclRuntimeError, 'bad index: ' + argv[2] +X list = SplitList(argv[1]) +X if index >= len(list): return '' +X return list[index] +X # +X def ListCmd(interp, argv): +X if len(argv) < 2: +X raise TclRuntimeError, 'usage: list arg ...' +X return BuildList(argv[1:]) +X # +X def ProcCmd(interp, argv): +X if len(argv) <> 4: +X raise TclRuntimeError, 'usage: proc name args body' +X x = _Proc().Create(interp, argv[2], argv[3]) +X interp.CreateCommand(argv[1], x.Call) +X return '' +X # +X def RenameCmd(interp, argv): +X if len(argv) <> 3: +X raise TclRuntimeError, 'usage: rename oldName newName' +X oldName, newName = argv[1], argv[2] +X if not interp.commands.has_key(oldName): +X raise TclRuntimeError, \ +X 'command "' + oldName + '" not found' +X if newName: interp.commands[newName] = interp.commands[oldName] +X del interp.commands[oldName] +X return '' +X # +X def ReturnCmd(interp, argv): +X if not 1 <= len(argv) <= 2: +X raise TclRuntimeError, 'usage: return [arg]' +X if len(argv) = 1: raise TclReturn, '' +X raise TclReturn, argv[1] +X # +X def SetCmd(interp, argv): +X n = len(argv) +X if not 2 <= n <= 3: +X raise TclRuntimeError, 'usage: set varname [newvalue]' +X if n = 2: return interp.GetVar(argv[1]) +X interp.SetVar(argv[1], argv[2]) +X return '' X X X# The rest are just demos: X Xdef MainLoop(interp): -X buffer = CmdBuf().Create() -X if not interp.globals.has_key('ps1'): interp.globals['ps1'] = '% ' -X if not interp.globals.has_key('ps2'): interp.globals['ps2'] = '' -X psname = 'ps1' -X while 1: -X try: -X line = raw_input(interp.globals[psname]) -X except (EOFError, KeyboardInterrupt): -X print -X break -X line = buffer.Assemble(line + '\n') -X if not line: -X psname = 'ps2' -X else: -X psname = 'ps1' -X try: -X x = interp.Eval(line) -X if x <> '': print 'Result:', `x` -X except (TclRuntimeError, TclSyntaxError, \ -X TclMatchingError), msg: -X print 'Error:', msg -X except (TclBreak, TclContinue): -X print 'Error: break or continue outside loop' -X except TclReturn, value: -X # Return outside proc returns to main loop -X if value: print value +X buffer = CmdBuf().Create() +X if not interp.globals.has_key('ps1'): interp.globals['ps1'] = '% ' +X if not interp.globals.has_key('ps2'): interp.globals['ps2'] = '' +X psname = 'ps1' +X while 1: +X try: +X line = raw_input(interp.globals[psname]) +X except (EOFError, KeyboardInterrupt): +X print +X break +X line = buffer.Assemble(line + '\n') +X if not line: +X psname = 'ps2' +X else: +X psname = 'ps1' +X try: +X x = interp.Eval(line) +X if x <> '': print 'Result:', `x` +X except (TclRuntimeError, TclSyntaxError, \ +X TclMatchingError), msg: +X print 'Error:', msg +X except (TclBreak, TclContinue): +X print 'Error: break or continue outside loop' +X except TclReturn, value: +X # Return outside proc returns to main loop +X if value: print value X X Xthe_interpreter = Interpreter().Create() X Xdef main(): -X MainLoop(the_interpreter) +X MainLoop(the_interpreter) X X X# XXX To do: @@ -981,12 +981,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1002,86 +1002,86 @@ X X******************************************************************/ X X/* Asynchronous audio module for Silicon Graphics 4D/20 under IRIX 3.3 -X Copyright 1990 Stichting Mathematisch Centrum, Amsterdam -X Author: Guido van Rossum, <[email protected]> -X Last modified: [email protected], Oct 14, 1990 -X -X Callers should #include "asa.h". -X -X This code is strongly IRIX 3.3 dependent. (Or are sproc() and -X friends standard SYSV now?) -X -X Caution: if you put printf's in the slave for debugging, use "-lmpc" -X to get the semaphore version of stdio! -X -X -X This file contains two library layers and a test program: -X -X -X The lower layer implements a simple asynchronous execution facility, -X built directly on the system calls sproc() and [un]blockproc(). -X -X A slave thread sits in an infinite loop waiting for work assigned to -X it by the master thread. Work is represented by a function pointer -X and an argument of type void*. The function returns a void* pointer -X which is transferred back to the master when it submits the next bit -X of work. Submitting a NULL function pointer can be used by the -X master to wait for completion of the previous work. This lower -X layer could be generally useful, but is currently implemented by -X static functions, for exclusive by the asynchronous audio layer. -X -X -X The higher layer implements an asynchronous interface to the -X /dev/audio device on the Silicon Graphics 4D/20. It defines the -X following functions: -X -X int asa_init() -X Required initialization function. The other functions will call -X abort() when they are called before asa_init(). It creates the -X slave process and returns a file descriptor for the audio -X device which can be used to set the sampling rate and output -X gain, etc. It prints a message to stderr and returns -1 if the -X initialization failed. Calling this function more than onece is -X harmless. -X -X void asa_start_read(char *buf, int len) -X Starts an asynchronous read call on the audio device. This -X waits for completion of the previous request, if any. -X -X void asa_start_write(char *buf, int len) -X Starts an asynchronous write call on the audio device. This -X waits for completion of the previous request, if any. -X -X int asa_poll() -X Polls whether the last asynchronous read or write request is -X finished. Returns -1 if no request was queued, 0 if the request -X is not yet finished, and 1 if it is finished. -X -X int asa_wait() -X Waits for completion if the last asynchronous read or write -X request. It returns the result of the read or write request, -X and sets the error code to the error code set by the request if -X the result is -1. If no request was queued, this also returns -X -1 but leaves the error code unchanged. Note: to get the error -X code, don't inspect the global variable errno but call the -X function oserror(). -X -X int asa_cancel() -X Cancels the last asynchronous read or write request (by sending -X the slave thread a signal for which it has a handler) then -X returns its result and error code as asa_wait(). -X -X void asa_done() -X Kills the slave process and closes the audio device. After -X this, if further use of the module is required, asa_init() -X should be called again. Calling this function when asa_init() -X has not been called is harmless. -X -X -X Finally, this file contains a simple test program that is compiled if -X MAIN is defined (e.g., compile with cc -DMAIN). It makes a recording -X and plays it back. The user must indicate begin and end of recording -X and play-back by pressing the Return key. +X Copyright 1990 Stichting Mathematisch Centrum, Amsterdam +X Author: Guido van Rossum, <[email protected]> +X Last modified: [email protected], Oct 14, 1990 +X +X Callers should #include "asa.h". +X +X This code is strongly IRIX 3.3 dependent. (Or are sproc() and +X friends standard SYSV now?) +X +X Caution: if you put printf's in the slave for debugging, use "-lmpc" +X to get the semaphore version of stdio! +X +X +X This file contains two library layers and a test program: +X +X +X The lower layer implements a simple asynchronous execution facility, +X built directly on the system calls sproc() and [un]blockproc(). +X +X A slave thread sits in an infinite loop waiting for work assigned to +X it by the master thread. Work is represented by a function pointer +X and an argument of type void*. The function returns a void* pointer +X which is transferred back to the master when it submits the next bit +X of work. Submitting a NULL function pointer can be used by the +X master to wait for completion of the previous work. This lower +X layer could be generally useful, but is currently implemented by +X static functions, for exclusive by the asynchronous audio layer. +X +X +X The higher layer implements an asynchronous interface to the +X /dev/audio device on the Silicon Graphics 4D/20. It defines the +X following functions: +X +X int asa_init() +X Required initialization function. The other functions will call +X abort() when they are called before asa_init(). It creates the +X slave process and returns a file descriptor for the audio +X device which can be used to set the sampling rate and output +X gain, etc. It prints a message to stderr and returns -1 if the +X initialization failed. Calling this function more than onece is +X harmless. +X +X void asa_start_read(char *buf, int len) +X Starts an asynchronous read call on the audio device. This +X waits for completion of the previous request, if any. +X +X void asa_start_write(char *buf, int len) +X Starts an asynchronous write call on the audio device. This +X waits for completion of the previous request, if any. +X +X int asa_poll() +X Polls whether the last asynchronous read or write request is +X finished. Returns -1 if no request was queued, 0 if the request +X is not yet finished, and 1 if it is finished. +X +X int asa_wait() +X Waits for completion if the last asynchronous read or write +X request. It returns the result of the read or write request, +X and sets the error code to the error code set by the request if +X the result is -1. If no request was queued, this also returns +X -1 but leaves the error code unchanged. Note: to get the error +X code, don't inspect the global variable errno but call the +X function oserror(). +X +X int asa_cancel() +X Cancels the last asynchronous read or write request (by sending +X the slave thread a signal for which it has a handler) then +X returns its result and error code as asa_wait(). +X +X void asa_done() +X Kills the slave process and closes the audio device. After +X this, if further use of the module is required, asa_init() +X should be called again. Calling this function when asa_init() +X has not been called is harmless. +X +X +X Finally, this file contains a simple test program that is compiled if +X MAIN is defined (e.g., compile with cc -DMAIN). It makes a recording +X and plays it back. The user must indicate begin and end of recording +X and play-back by pressing the Return key. X*/ X X @@ -1114,20 +1114,20 @@ X X/*ARGSUSED*/ Xstatic void Xhandler(sig) -X int sig; +X int sig; X{ -X /* Reinstate the handler (non-BSD signal semantics) */ -X signal(sig, handler); +X /* Reinstate the handler (non-BSD signal semantics) */ +X signal(sig, handler); X} X X/* Subroutine to fiddle signals */ X Xstatic void Xdosig(sig) -X int sig; +X int sig; X{ -X if (signal(sig, SIG_IGN) != SIG_IGN) -X signal(sig, SIG_DFL); +X if (signal(sig, SIG_IGN) != SIG_IGN) +X signal(sig, SIG_DFL); X} X X/* Slave control flow */ @@ -1135,148 +1135,148 @@ X X/*ARGSUSED*/ Xstatic void Xslave(arg) -X void *arg; +X void *arg; X{ -X void * (*func)(); -X void *arg; -X void *result; -X -X /* Reset signal handlers that interactive programs often catch. -X The assumption is that if the master has a handler for these -X signals, it will be a cleanup function. The slave must die -X from these. */ -X dosig(SIGHUP); -X dosig(SIGQUIT); -X dosig(SIGTERM); -X dosig(SIGPIPE); -X -X /* Ignore SIGINT if caught or ignored */ -X if (signal(SIGINT, SIG_IGN) == SIG_DFL) -X signal(SIGINT, SIG_DFL); -X -X /* Let the handler install itself */ -X handler(MYSIG); -X -X /* Set slave_pid. This is also done in the master thread, but -X there is a race condition whereby the slave begins execution -X before the master has assigned the result of sproc() to -X slave_pid. So we set it here as well -- since this sets the -X same value it should be OK. */ -X slave_pid = getpid(); -X -X /* Set the dummy result returned by the first rendezvous */ -X result = NULL; -X -X /* Loop forever, waiting for and executing work */ -X for (;;) { -X /* First rendezvous: store previous result */ -X if (blockproc(slave_pid) < 0) -X perror("slave: [result] blockproc(slave_pid)"); -X work_result = result; -X if (unblockproc(master_pid) < 0) -X perror("slave: [result] unblockproc(master_pid)"); -X -X /* Second rendezvous: fetch work */ -X if (blockproc(slave_pid) < 0) -X perror("slave: [func,arg] blockproc(slave_pid)"); -X func = work_func; -X arg = work_arg; -X if (unblockproc(master_pid) < 0) -X perror("slave: [func,arg] unblockproc(master_pid)"); -X -X /* Execute work, computing new result */ -X if (func == NULL) { -X result = arg; -X } -X else { -X result = (*func)(arg); -X } -X } +X void * (*func)(); +X void *arg; +X void *result; +X +X /* Reset signal handlers that interactive programs often catch. +X The assumption is that if the master has a handler for these +X signals, it will be a cleanup function. The slave must die +X from these. */ +X dosig(SIGHUP); +X dosig(SIGQUIT); +X dosig(SIGTERM); +X dosig(SIGPIPE); +X +X /* Ignore SIGINT if caught or ignored */ +X if (signal(SIGINT, SIG_IGN) == SIG_DFL) +X signal(SIGINT, SIG_DFL); +X +X /* Let the handler install itself */ +X handler(MYSIG); +X +X /* Set slave_pid. This is also done in the master thread, but +X there is a race condition whereby the slave begins execution +X before the master has assigned the result of sproc() to +X slave_pid. So we set it here as well -- since this sets the +X same value it should be OK. */ +X slave_pid = getpid(); +X +X /* Set the dummy result returned by the first rendezvous */ +X result = NULL; +X +X /* Loop forever, waiting for and executing work */ +X for (;;) { +X /* First rendezvous: store previous result */ +X if (blockproc(slave_pid) < 0) +X perror("slave: [result] blockproc(slave_pid)"); +X work_result = result; +X if (unblockproc(master_pid) < 0) +X perror("slave: [result] unblockproc(master_pid)"); +X +X /* Second rendezvous: fetch work */ +X if (blockproc(slave_pid) < 0) +X perror("slave: [func,arg] blockproc(slave_pid)"); +X func = work_func; +X arg = work_arg; +X if (unblockproc(master_pid) < 0) +X perror("slave: [func,arg] unblockproc(master_pid)"); +X +X /* Execute work, computing new result */ +X if (func == NULL) { +X result = arg; +X } +X else { +X result = (*func)(arg); +X } +X } X} X Xstatic int Xslave_init() X{ -X if (slave_pid > 0) -X return slave_pid; -X master_pid = getpid(); -X -X /* Reset the queue, in case this is a re-init after asa_done() */ -X work_result = NULL; -X work_func = NULL; -X work_arg = NULL; -X -X /* Create the slave process, sharing all segments and properties */ -X slave_pid = sproc(slave, PR_SALL, (char *)NULL); -X if (slave_pid < 0) -X perror("slave_init: sproc(slave, PR_SALL, NULL)"); -X -X /* Set up initial conditions---tricky! -X Both the master and the slave start with one credit, since -X both the result slot and the work/func slots are initially -X free. -X Note that we use setblockproccnt() for the master so a -X possible indeterminate semaphore value caused by a previous -X asa_done() at an unfortunate moment doesn't harm us. -X */ -X setblockproccnt(master_pid, 1); -X unblockproc(slave_pid); -X -X return slave_pid; +X if (slave_pid > 0) +X return slave_pid; +X master_pid = getpid(); +X +X /* Reset the queue, in case this is a re-init after asa_done() */ +X work_result = NULL; +X work_func = NULL; +X work_arg = NULL; +X +X /* Create the slave process, sharing all segments and properties */ +X slave_pid = sproc(slave, PR_SALL, (char *)NULL); +X if (slave_pid < 0) +X perror("slave_init: sproc(slave, PR_SALL, NULL)"); +X +X /* Set up initial conditions---tricky! +X Both the master and the slave start with one credit, since +X both the result slot and the work/func slots are initially +X free. +X Note that we use setblockproccnt() for the master so a +X possible indeterminate semaphore value caused by a previous +X asa_done() at an unfortunate moment doesn't harm us. +X */ +X setblockproccnt(master_pid, 1); +X unblockproc(slave_pid); +X +X return slave_pid; X} X Xstatic void Xslave_done() X{ -X if (slave_pid > 0) { -X if (kill(slave_pid, SIGKILL) < 0) -X perror("slave_done: kill(slave_pid, SIGKILL)"); -X } -X slave_pid = -1; +X if (slave_pid > 0) { +X if (kill(slave_pid, SIGKILL) < 0) +X perror("slave_done: kill(slave_pid, SIGKILL)"); +X } +X slave_pid = -1; X} X X/* Queue new work and return result of previous work */ X Xstatic void * Xrendezvous(func, arg) -X void * (*func)(); -X void *arg; +X void * (*func)(); +X void *arg; X{ -X void *result; -X -X if (slave_pid <= 0) -X abort(); /* Illegal call: not initialized properly */ -X -X /* First rendezvous: store new work */ -X if (blockproc(master_pid) < 0) -X perror("rendezvous: [func,arg] blockproc(master_pid)"); -X work_func = func; -X work_arg = arg; -X if (unblockproc(slave_pid) < 0) -X perror("rendezvous: [func,arg] unblockproc(slave_pid)"); -X -X /* Second rendezvous: fetch previous result */ -X if (blockproc(master_pid) < 0) -X perror("rendezvous: [result] blockproc(master_pid)"); -X result = work_result; -X if (unblockproc(slave_pid) < 0) -X perror("rendezvous: [result] unblockproc(slave_pid)"); -X -X return result; +X void *result; +X +X if (slave_pid <= 0) +X abort(); /* Illegal call: not initialized properly */ +X +X /* First rendezvous: store new work */ +X if (blockproc(master_pid) < 0) +X perror("rendezvous: [func,arg] blockproc(master_pid)"); +X work_func = func; +X work_arg = arg; +X if (unblockproc(slave_pid) < 0) +X perror("rendezvous: [func,arg] unblockproc(slave_pid)"); +X +X /* Second rendezvous: fetch previous result */ +X if (blockproc(master_pid) < 0) +X perror("rendezvous: [result] blockproc(master_pid)"); +X result = work_result; +X if (unblockproc(slave_pid) < 0) +X perror("rendezvous: [result] unblockproc(slave_pid)"); +X +X return result; X} X X X/* Asynchronous audio interface (higher layer) */ X X -Xint audio_fd = -1; /* File descriptor -- not initialized yet */ +Xint audio_fd = -1; /* File descriptor -- not initialized yet */ X Xstatic struct queue { -X int func; /* 0 = read, 1 = write */ -X char *buf; -X int len; -X int result; -X int error; +X int func; /* 0 = read, 1 = write */ +X char *buf; +X int len; +X int result; +X int error; X} queue[2]; X Xstatic int qindex = 0; @@ -1284,135 +1284,135 @@ X Xint Xasa_init() X{ -X int fd; -X char *p; -X -X if (audio_fd >= 0) -X return audio_fd; -X fd = open("/dev/audio", 2); -X if (fd < 0) { -X perror("asa_init: Can't open /dev/audio"); -X return -1; -X } -X if (slave_init() < 0) { -X perror("asa_init: Can't create slave process"); -X close(fd); -X return -1; -X } -X audio_fd = fd; -X return fd; +X int fd; +X char *p; +X +X if (audio_fd >= 0) +X return audio_fd; +X fd = open("/dev/audio", 2); +X if (fd < 0) { +X perror("asa_init: Can't open /dev/audio"); +X return -1; +X } +X if (slave_init() < 0) { +X perror("asa_init: Can't create slave process"); +X close(fd); +X return -1; +X } +X audio_fd = fd; +X return fd; X} X Xvoid Xasa_done() X{ -X slave_done(); -X if (audio_fd >= 0) { -X if (close(audio_fd) < 0) -X perror("asa_done: close(audio_fd)"); -X } -X audio_fd = -1; +X slave_done(); +X if (audio_fd >= 0) { +X if (close(audio_fd) < 0) +X perror("asa_done: close(audio_fd)"); +X } +X audio_fd = -1; X} X Xstatic void * Xrunjob(arg) -X void *arg; +X void *arg; X{ -X extern int errno; -X struct queue *q = (struct queue *)arg; -X char *buf = q->buf; -X int len = q->len; -X int n = 0; -X -X if (q->func == 0) -X n = read(audio_fd, buf, len); -X else -X n = write(audio_fd, buf, len); -X if (q->func == 0 && n >= 0) { -X while (--len >= n && buf[len] == '\0') -X ; -X n = len+1; -X } -X q->result = n; -X q->error = oserror(); -X return arg; +X extern int errno; +X struct queue *q = (struct queue *)arg; +X char *buf = q->buf; +X int len = q->len; +X int n = 0; +X +X if (q->func == 0) +X n = read(audio_fd, buf, len); +X else +X n = write(audio_fd, buf, len); +X if (q->func == 0 && n >= 0) { +X while (--len >= n && buf[len] == '\0') +X ; +X n = len+1; +X } +X q->result = n; +X q->error = oserror(); +X return arg; X} X Xstatic void Xstartjob(func, buf, len) -X int func; -X char *buf; -X int len; +X int func; +X char *buf; +X int len; X{ -X struct queue *q; -X -X q = &queue[qindex]; -X qindex = (qindex+1) & 1; -X q->func = func; -X q->buf = buf; -X q->len = len; -X (void) rendezvous(runjob, (void *)q); +X struct queue *q; +X +X q = &queue[qindex]; +X qindex = (qindex+1) & 1; +X q->func = func; +X q->buf = buf; +X q->len = len; +X (void) rendezvous(runjob, (void *)q); X} X Xvoid Xasa_start_read(buf, len) -X char *buf; -X int len; +X char *buf; +X int len; X{ -X memset(buf, '\0', len); -X startjob(0, buf, len); +X memset(buf, '\0', len); +X startjob(0, buf, len); X} X Xvoid Xasa_start_write(buf, len) -X char *buf; -X int len; +X char *buf; +X int len; X{ -X startjob(1, buf, len); +X startjob(1, buf, len); X} X Xint Xasa_wait() X{ -X struct queue *q; -X -X q = (struct queue *) rendezvous((void*(*)())NULL, (void *)NULL); -X if (q == NULL) { -X setoserror(0); -X return -1; /* No work was queued */ -X } -X setoserror(q->error); -X return q->result; +X struct queue *q; +X +X q = (struct queue *) rendezvous((void*(*)())NULL, (void *)NULL); +X if (q == NULL) { +X setoserror(0); +X return -1; /* No work was queued */ +X } +X setoserror(q->error); +X return q->result; X} X Xint Xasa_poll() X{ -X int err; -X -X err = prctl(PR_ISBLOCKED, slave_pid); -X if (err < 0) { -X perror("prctl(PR_ISBLOCKED, slave_pid)"); -X return -1; -X } -X else if (err == 0) -X return 0; -X else if (work_result == NULL) { -X setoserror(0); -X return -1; -X } -X else -X return 1; +X int err; +X +X err = prctl(PR_ISBLOCKED, slave_pid); +X if (err < 0) { +X perror("prctl(PR_ISBLOCKED, slave_pid)"); +X return -1; +X } +X else if (err == 0) +X return 0; +X else if (work_result == NULL) { +X setoserror(0); +X return -1; +X } +X else +X return 1; X} X Xint Xasa_cancel() X{ -X int result; -X -X kill(slave_pid, MYSIG); -X result = asa_wait(); -X return result; +X int result; +X +X kill(slave_pid, MYSIG); +X result = asa_wait(); +X return result; X} X X @@ -1424,50 +1424,50 @@ X#include <sys/audio.h> X Xmain() X{ -X static char buf[10*16*1024]; /* 10 seconds of sound at 16K/sec */ -X int n; -X int afd; -X -X if ((afd = asa_init()) < 0) -X exit(1); -X ioctl(afd, AUDIOCSETRATE, 3); -X ioctl(afd, AUDIOCSETOUTGAIN, 0); -X printf("Poll returns %d\n", asa_poll()); -X go("Hit enter to start recording:\n"); -X asa_start_read(buf, sizeof buf); -X go("Hit enter to stop recording:\n"); -X /*printf("Poll returns %d\n", asa_poll());*/ -X n = asa_cancel(); -X if (n < 0) -X perror("Read failed"); -X else { -X printf("Got %d bytes\n", n); -X printf("Poll returns %d\n", asa_poll()); -X go("Hit enter to start playing:\n"); -X ioctl(afd, AUDIOCSETOUTGAIN, 50); -X asa_start_write(buf, n); -X go("Hit enter to stop playing:\n"); -X printf("Poll returns %d\n", asa_poll()); -X n = asa_cancel(); -X if (n < 0) -X perror("Write failed"); -X else -X printf("Stopped at %d bytes\n", n); -X } -X ioctl(afd, AUDIOCSETOUTGAIN, 0); -X asa_done(); -X exit(n < 0 ? 1 : 0); +X static char buf[10*16*1024]; /* 10 seconds of sound at 16K/sec */ +X int n; +X int afd; +X +X if ((afd = asa_init()) < 0) +X exit(1); +X ioctl(afd, AUDIOCSETRATE, 3); +X ioctl(afd, AUDIOCSETOUTGAIN, 0); +X printf("Poll returns %d\n", asa_poll()); +X go("Hit enter to start recording:\n"); +X asa_start_read(buf, sizeof buf); +X go("Hit enter to stop recording:\n"); +X /*printf("Poll returns %d\n", asa_poll());*/ +X n = asa_cancel(); +X if (n < 0) +X perror("Read failed"); +X else { +X printf("Got %d bytes\n", n); +X printf("Poll returns %d\n", asa_poll()); +X go("Hit enter to start playing:\n"); +X ioctl(afd, AUDIOCSETOUTGAIN, 50); +X asa_start_write(buf, n); +X go("Hit enter to stop playing:\n"); +X printf("Poll returns %d\n", asa_poll()); +X n = asa_cancel(); +X if (n < 0) +X perror("Write failed"); +X else +X printf("Stopped at %d bytes\n", n); +X } +X ioctl(afd, AUDIOCSETOUTGAIN, 0); +X asa_done(); +X exit(n < 0 ? 1 : 0); X} X Xgo(str) -X char *str; +X char *str; X{ -X char line[100]; -X -X sleep(1); -X fputs(str, stdout); -X fflush(stdout); -X fgets(line, sizeof line, stdin); +X char line[100]; +X +X sleep(1); +X fputs(str, stdout); +X fflush(stdout); +X fgets(line, sizeof line, stdin); X} X X#endif /* MAIN */ @@ -1482,12 +1482,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1519,479 +1519,479 @@ X#include "modsupport.h" X Xstatic object * Xbuiltin_abs(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X /* XXX This should be a method in the as_number struct in the type */ -X if (v == NULL) { -X /* */ -X } -X else if (is_intobject(v)) { -X long x = getintvalue(v); -X if (x < 0) -X x = -x; -X return newintobject(x); -X } -X else if (is_floatobject(v)) { -X double x = getfloatvalue(v); -X if (x < 0) -X x = -x; -X return newfloatobject(x); -X } -X err_setstr(TypeError, "abs() argument must be float or int"); -X return NULL; +X /* XXX This should be a method in the as_number struct in the type */ +X if (v == NULL) { +X /* */ +X } +X else if (is_intobject(v)) { +X long x = getintvalue(v); +X if (x < 0) +X x = -x; +X return newintobject(x); +X } +X else if (is_floatobject(v)) { +X double x = getfloatvalue(v); +X if (x < 0) +X x = -x; +X return newfloatobject(x); +X } +X err_setstr(TypeError, "abs() argument must be float or int"); +X return NULL; X} X Xstatic object * Xbuiltin_chr(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X long x; -X char s[1]; -X if (v == NULL || !is_intobject(v)) { -X err_setstr(TypeError, "chr() must have int argument"); -X return NULL; -X } -X x = getintvalue(v); -X if (x < 0 || x >= 256) { -X err_setstr(RuntimeError, "chr() arg not in range(256)"); -X return NULL; -X } -X s[0] = x; -X return newsizedstringobject(s, 1); +X long x; +X char s[1]; +X if (v == NULL || !is_intobject(v)) { +X err_setstr(TypeError, "chr() must have int argument"); +X return NULL; +X } +X x = getintvalue(v); +X if (x < 0 || x >= 256) { +X err_setstr(RuntimeError, "chr() arg not in range(256)"); +X return NULL; +X } +X s[0] = x; +X return newsizedstringobject(s, 1); X} X Xstatic object * Xbuiltin_dir(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X object *d; -X if (v == NULL) { -X d = getlocals(); -X } -X else { -X if (!is_moduleobject(v)) { -X err_setstr(TypeError, -X "dir() argument, must be module or absent"); -X return NULL; -X } -X d = getmoduledict(v); -X } -X v = getdictkeys(d); -X if (sortlist(v) != 0) { -X DECREF(v); -X v = NULL; -X } -X return v; +X object *d; +X if (v == NULL) { +X d = getlocals(); +X } +X else { +X if (!is_moduleobject(v)) { +X err_setstr(TypeError, +X "dir() argument, must be module or absent"); +X return NULL; +X } +X d = getmoduledict(v); +X } +X v = getdictkeys(d); +X if (sortlist(v) != 0) { +X DECREF(v); +X v = NULL; +X } +X return v; X} X Xstatic object * Xbuiltin_divmod(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X object *x, *y; -X long xi, yi, xdivy, xmody; -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X err_setstr(TypeError, "divmod() requires 2 int arguments"); -X return NULL; -X } -X x = gettupleitem(v, 0); -X y = gettupleitem(v, 1); -X if (!is_intobject(x) || !is_intobject(y)) { -X err_setstr(TypeError, "divmod() requires 2 int arguments"); -X return NULL; -X } -X xi = getintvalue(x); -X yi = getintvalue(y); -X if (yi == 0) { -X err_setstr(TypeError, "divmod() division by zero"); -X return NULL; -X } -X if (yi < 0) { -X xdivy = -xi / -yi; -X } -X else { -X xdivy = xi / yi; -X } -X xmody = xi - xdivy*yi; -X if (xmody < 0 && yi > 0 || xmody > 0 && yi < 0) { -X xmody += yi; -X xdivy -= 1; -X } -X v = newtupleobject(2); -X x = newintobject(xdivy); -X y = newintobject(xmody); -X if (v == NULL || x == NULL || y == NULL || -X settupleitem(v, 0, x) != 0 || -X settupleitem(v, 1, y) != 0) { -X XDECREF(v); -X XDECREF(x); -X XDECREF(y); -X return NULL; -X } -X return v; +X object *x, *y; +X long xi, yi, xdivy, xmody; +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X err_setstr(TypeError, "divmod() requires 2 int arguments"); +X return NULL; +X } +X x = gettupleitem(v, 0); +X y = gettupleitem(v, 1); +X if (!is_intobject(x) || !is_intobject(y)) { +X err_setstr(TypeError, "divmod() requires 2 int arguments"); +X return NULL; +X } +X xi = getintvalue(x); +X yi = getintvalue(y); +X if (yi == 0) { +X err_setstr(TypeError, "divmod() division by zero"); +X return NULL; +X } +X if (yi < 0) { +X xdivy = -xi / -yi; +X } +X else { +X xdivy = xi / yi; +X } +X xmody = xi - xdivy*yi; +X if (xmody < 0 && yi > 0 || xmody > 0 && yi < 0) { +X xmody += yi; +X xdivy -= 1; +X } +X v = newtupleobject(2); +X x = newintobject(xdivy); +X y = newintobject(xmody); +X if (v == NULL || x == NULL || y == NULL || +X settupleitem(v, 0, x) != 0 || +X settupleitem(v, 1, y) != 0) { +X XDECREF(v); +X XDECREF(x); +X XDECREF(y); +X return NULL; +X } +X return v; X} X Xstatic object * Xexec_eval(v, start) -X object *v; -X int start; +X object *v; +X int start; X{ -X object *str = NULL, *globals = NULL, *locals = NULL; -X int n; -X if (v != NULL) { -X if (is_stringobject(v)) -X str = v; -X else if (is_tupleobject(v) && -X ((n = gettuplesize(v)) == 2 || n == 3)) { -X str = gettupleitem(v, 0); -X globals = gettupleitem(v, 1); -X if (n == 3) -X locals = gettupleitem(v, 2); -X } -X } -X if (str == NULL || !is_stringobject(str) || -X globals != NULL && !is_dictobject(globals) || -X locals != NULL && !is_dictobject(locals)) { -X err_setstr(TypeError, -X "exec/eval arguments must be string[,dict[,dict]]"); -X return NULL; -X } -X return run_string(getstringvalue(str), start, globals, locals); +X object *str = NULL, *globals = NULL, *locals = NULL; +X int n; +X if (v != NULL) { +X if (is_stringobject(v)) +X str = v; +X else if (is_tupleobject(v) && +X ((n = gettuplesize(v)) == 2 || n == 3)) { +X str = gettupleitem(v, 0); +X globals = gettupleitem(v, 1); +X if (n == 3) +X locals = gettupleitem(v, 2); +X } +X } +X if (str == NULL || !is_stringobject(str) || +X globals != NULL && !is_dictobject(globals) || +X locals != NULL && !is_dictobject(locals)) { +X err_setstr(TypeError, +X "exec/eval arguments must be string[,dict[,dict]]"); +X return NULL; +X } +X return run_string(getstringvalue(str), start, globals, locals); X} X Xstatic object * Xbuiltin_eval(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X return exec_eval(v, eval_input); +X return exec_eval(v, eval_input); X} X Xstatic object * Xbuiltin_exec(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X return exec_eval(v, file_input); +X return exec_eval(v, file_input); X} X Xstatic object * Xbuiltin_float(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X if (v == NULL) { -X /* */ -X } -X else if (is_floatobject(v)) { -X INCREF(v); -X return v; -X } -X else if (is_intobject(v)) { -X long x = getintvalue(v); -X return newfloatobject((double)x); -X } -X err_setstr(TypeError, "float() argument must be float or int"); -X return NULL; +X if (v == NULL) { +X /* */ +X } +X else if (is_floatobject(v)) { +X INCREF(v); +X return v; +X } +X else if (is_intobject(v)) { +X long x = getintvalue(v); +X return newfloatobject((double)x); +X } +X err_setstr(TypeError, "float() argument must be float or int"); +X return NULL; X} X Xstatic object * Xbuiltin_input(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X FILE *in = sysgetfile("stdin", stdin); -X FILE *out = sysgetfile("stdout", stdout); -X node *n; -X int err; -X object *m, *d; -X flushline(); -X if (v != NULL) -X printobject(v, out, PRINT_RAW); -X m = add_module("__main__"); -X d = getmoduledict(m); -X return run_file(in, "<stdin>", expr_input, d, d); +X FILE *in = sysgetfile("stdin", stdin); +X FILE *out = sysgetfile("stdout", stdout); +X node *n; +X int err; +X object *m, *d; +X flushline(); +X if (v != NULL) +X printobject(v, out, PRINT_RAW); +X m = add_module("__main__"); +X d = getmoduledict(m); +X return run_file(in, "<stdin>", expr_input, d, d); X} X Xstatic object * Xbuiltin_int(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X if (v == NULL) { -X /* */ -X } -X else if (is_intobject(v)) { -X INCREF(v); -X return v; -X } -X else if (is_floatobject(v)) { -X double x = getfloatvalue(v); -X return newintobject((long)x); -X } -X err_setstr(TypeError, "int() argument must be float or int"); -X return NULL; +X if (v == NULL) { +X /* */ +X } +X else if (is_intobject(v)) { +X INCREF(v); +X return v; +X } +X else if (is_floatobject(v)) { +X double x = getfloatvalue(v); +X return newintobject((long)x); +X } +X err_setstr(TypeError, "int() argument must be float or int"); +X return NULL; X} X Xstatic object * Xbuiltin_len(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X long len; -X typeobject *tp; -X if (v == NULL) { -X err_setstr(TypeError, "len() without argument"); -X return NULL; -X } -X tp = v->ob_type; -X if (tp->tp_as_sequence != NULL) { -X len = (*tp->tp_as_sequence->sq_length)(v); -X } -X else if (tp->tp_as_mapping != NULL) { -X len = (*tp->tp_as_mapping->mp_length)(v); -X } -X else { -X err_setstr(TypeError, "len() of unsized object"); -X return NULL; -X } -X return newintobject(len); +X long len; +X typeobject *tp; +X if (v == NULL) { +X err_setstr(TypeError, "len() without argument"); +X return NULL; +X } +X tp = v->ob_type; +X if (tp->tp_as_sequence != NULL) { +X len = (*tp->tp_as_sequence->sq_length)(v); +X } +X else if (tp->tp_as_mapping != NULL) { +X len = (*tp->tp_as_mapping->mp_length)(v); +X } +X else { +X err_setstr(TypeError, "len() of unsized object"); +X return NULL; +X } +X return newintobject(len); X} X Xstatic object * Xmin_max(v, sign) -X object *v; -X int sign; +X object *v; +X int sign; X{ -X int i, n, cmp; -X object *w, *x; -X sequence_methods *sq; -X if (v == NULL) { -X err_setstr(TypeError, "min() or max() without argument"); -X return NULL; -X } -X sq = v->ob_type->tp_as_sequence; -X if (sq == NULL) { -X err_setstr(TypeError, "min() or max() of non-sequence"); -X return NULL; -X } -X n = (*sq->sq_length)(v); -X if (n == 0) { -X err_setstr(RuntimeError, "min() or max() of empty sequence"); -X return NULL; -X } -X w = (*sq->sq_item)(v, 0); /* Implies INCREF */ -X for (i = 1; i < n; i++) { -X x = (*sq->sq_item)(v, i); /* Implies INCREF */ -X cmp = cmpobject(x, w); -X if (cmp * sign > 0) { -X DECREF(w); -X w = x; -X } -X else -X DECREF(x); -X } -X return w; +X int i, n, cmp; +X object *w, *x; +X sequence_methods *sq; +X if (v == NULL) { +X err_setstr(TypeError, "min() or max() without argument"); +X return NULL; +X } +X sq = v->ob_type->tp_as_sequence; +X if (sq == NULL) { +X err_setstr(TypeError, "min() or max() of non-sequence"); +X return NULL; +X } +X n = (*sq->sq_length)(v); +X if (n == 0) { +X err_setstr(RuntimeError, "min() or max() of empty sequence"); +X return NULL; +X } +X w = (*sq->sq_item)(v, 0); /* Implies INCREF */ +X for (i = 1; i < n; i++) { +X x = (*sq->sq_item)(v, i); /* Implies INCREF */ +X cmp = cmpobject(x, w); +X if (cmp * sign > 0) { +X DECREF(w); +X w = x; +X } +X else +X DECREF(x); +X } +X return w; X} X Xstatic object * Xbuiltin_min(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X return min_max(v, -1); +X return min_max(v, -1); X} X Xstatic object * Xbuiltin_max(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X return min_max(v, 1); +X return min_max(v, 1); X} X Xstatic object * Xbuiltin_open(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X object *name, *mode; -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2 || -X !is_stringobject(name = gettupleitem(v, 0)) || -X !is_stringobject(mode = gettupleitem(v, 1))) { -X err_setstr(TypeError, "open() requires 2 string arguments"); -X return NULL; -X } -X v = newfileobject(getstringvalue(name), getstringvalue(mode)); -X return v; +X object *name, *mode; +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2 || +X !is_stringobject(name = gettupleitem(v, 0)) || +X !is_stringobject(mode = gettupleitem(v, 1))) { +X err_setstr(TypeError, "open() requires 2 string arguments"); +X return NULL; +X } +X v = newfileobject(getstringvalue(name), getstringvalue(mode)); +X return v; X} X Xstatic object * Xbuiltin_ord(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X if (v == NULL || !is_stringobject(v)) { -X err_setstr(TypeError, "ord() must have string argument"); -X return NULL; -X } -X if (getstringsize(v) != 1) { -X err_setstr(RuntimeError, "ord() arg must have length 1"); -X return NULL; -X } -X return newintobject((long)(getstringvalue(v)[0] & 0xff)); +X if (v == NULL || !is_stringobject(v)) { +X err_setstr(TypeError, "ord() must have string argument"); +X return NULL; +X } +X if (getstringsize(v) != 1) { +X err_setstr(RuntimeError, "ord() arg must have length 1"); +X return NULL; +X } +X return newintobject((long)(getstringvalue(v)[0] & 0xff)); X} X Xstatic object * Xbuiltin_range(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X static char *errmsg = "range() requires 1-3 int arguments"; -X int i, n; -X long ilow, ihigh, istep; -X if (v != NULL && is_intobject(v)) { -X ilow = 0; ihigh = getintvalue(v); istep = 1; -X } -X else if (v == NULL || !is_tupleobject(v)) { -X err_setstr(TypeError, errmsg); -X return NULL; -X } -X else { -X n = gettuplesize(v); -X if (n < 1 || n > 3) { -X err_setstr(TypeError, errmsg); -X return NULL; -X } -X for (i = 0; i < n; i++) { -X if (!is_intobject(gettupleitem(v, i))) { -X err_setstr(TypeError, errmsg); -X return NULL; -X } -X } -X if (n == 3) { -X istep = getintvalue(gettupleitem(v, 2)); -X --n; -X } -X else -X istep = 1; -X ihigh = getintvalue(gettupleitem(v, --n)); -X if (n > 0) -X ilow = getintvalue(gettupleitem(v, 0)); -X else -X ilow = 0; -X } -X if (istep == 0) { -X err_setstr(RuntimeError, "zero step for range()"); -X return NULL; -X } -X /* XXX ought to check overflow of subtraction */ -X if (istep > 0) -X n = (ihigh - ilow + istep - 1) / istep; -X else -X n = (ihigh - ilow + istep + 1) / istep; -X if (n < 0) -X n = 0; -X v = newlistobject(n); -X if (v == NULL) -X return NULL; -X for (i = 0; i < n; i++) { -X object *w = newintobject(ilow); -X if (w == NULL) { -X DECREF(v); -X return NULL; -X } -X setlistitem(v, i, w); -X ilow += istep; -X } -X return v; +X static char *errmsg = "range() requires 1-3 int arguments"; +X int i, n; +X long ilow, ihigh, istep; +X if (v != NULL && is_intobject(v)) { +X ilow = 0; ihigh = getintvalue(v); istep = 1; +X } +X else if (v == NULL || !is_tupleobject(v)) { +X err_setstr(TypeError, errmsg); +X return NULL; +X } +X else { +X n = gettuplesize(v); +X if (n < 1 || n > 3) { +X err_setstr(TypeError, errmsg); +X return NULL; +X } +X for (i = 0; i < n; i++) { +X if (!is_intobject(gettupleitem(v, i))) { +X err_setstr(TypeError, errmsg); +X return NULL; +X } +X } +X if (n == 3) { +X istep = getintvalue(gettupleitem(v, 2)); +X --n; +X } +X else +X istep = 1; +X ihigh = getintvalue(gettupleitem(v, --n)); +X if (n > 0) +X ilow = getintvalue(gettupleitem(v, 0)); +X else +X ilow = 0; +X } +X if (istep == 0) { +X err_setstr(RuntimeError, "zero step for range()"); +X return NULL; +X } +X /* XXX ought to check overflow of subtraction */ +X if (istep > 0) +X n = (ihigh - ilow + istep - 1) / istep; +X else +X n = (ihigh - ilow + istep + 1) / istep; +X if (n < 0) +X n = 0; +X v = newlistobject(n); +X if (v == NULL) +X return NULL; +X for (i = 0; i < n; i++) { +X object *w = newintobject(ilow); +X if (w == NULL) { +X DECREF(v); +X return NULL; +X } +X setlistitem(v, i, w); +X ilow += istep; +X } +X return v; X} X Xstatic object * Xbuiltin_raw_input(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X FILE *in = sysgetfile("stdin", stdin); -X FILE *out = sysgetfile("stdout", stdout); -X char *p; -X int err; -X int n = 1000; -X flushline(); -X if (v != NULL) -X printobject(v, out, PRINT_RAW); -X v = newsizedstringobject((char *)NULL, n); -X if (v != NULL) { -X if ((err = fgets_intr(getstringvalue(v), n+1, in)) != E_OK) { -X err_input(err); -X DECREF(v); -X return NULL; -X } -X else { -X n = strlen(getstringvalue(v)); -X if (n > 0 && getstringvalue(v)[n-1] == '\n') -X n--; -X resizestring(&v, n); -X } -X } -X return v; +X FILE *in = sysgetfile("stdin", stdin); +X FILE *out = sysgetfile("stdout", stdout); +X char *p; +X int err; +X int n = 1000; +X flushline(); +X if (v != NULL) +X printobject(v, out, PRINT_RAW); +X v = newsizedstringobject((char *)NULL, n); +X if (v != NULL) { +X if ((err = fgets_intr(getstringvalue(v), n+1, in)) != E_OK) { +X err_input(err); +X DECREF(v); +X return NULL; +X } +X else { +X n = strlen(getstringvalue(v)); +X if (n > 0 && getstringvalue(v)[n-1] == '\n') +X n--; +X resizestring(&v, n); +X } +X } +X return v; X} X Xstatic object * Xbuiltin_reload(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X return reload_module(v); +X return reload_module(v); X} X Xstatic object * Xbuiltin_type(self, v) -X object *self; -X object *v; +X object *self; +X object *v; X{ -X if (v == NULL) { -X err_setstr(TypeError, "type() requres an argument"); -X return NULL; -X } -X v = (object *)v->ob_type; -X INCREF(v); -X return v; +X if (v == NULL) { +X err_setstr(TypeError, "type() requres an argument"); +X return NULL; +X } +X v = (object *)v->ob_type; +X INCREF(v); +X return v; X} X Xstatic struct methodlist builtin_methods[] = { -X {"abs", builtin_abs}, -X {"chr", builtin_chr}, -X {"dir", builtin_dir}, -X {"divmod", builtin_divmod}, -X {"eval", builtin_eval}, -X {"exec", builtin_exec}, -X {"float", builtin_float}, -X {"input", builtin_input}, -X {"int", builtin_int}, -X {"len", builtin_len}, -X {"max", builtin_max}, -X {"min", builtin_min}, -X {"open", builtin_open}, /* XXX move to OS module */ -X {"ord", builtin_ord}, -X {"range", builtin_range}, -X {"raw_input", builtin_raw_input}, -X {"reload", builtin_reload}, -X {"type", builtin_type}, -X {NULL, NULL}, +X {"abs", builtin_abs}, +X {"chr", builtin_chr}, +X {"dir", builtin_dir}, +X {"divmod", builtin_divmod}, +X {"eval", builtin_eval}, +X {"exec", builtin_exec}, +X {"float", builtin_float}, +X {"input", builtin_input}, +X {"int", builtin_int}, +X {"len", builtin_len}, +X {"max", builtin_max}, +X {"min", builtin_min}, +X {"open", builtin_open}, /* XXX move to OS module */ +X {"ord", builtin_ord}, +X {"range", builtin_range}, +X {"raw_input", builtin_raw_input}, +X {"reload", builtin_reload}, +X {"type", builtin_type}, +X {NULL, NULL}, X}; X Xstatic object *builtin_dict; X Xobject * Xgetbuiltin(name) -X char *name; +X char *name; X{ -X return dictlookup(builtin_dict, name); +X return dictlookup(builtin_dict, name); X} X X/* Predefined exceptions */ @@ -2006,36 +2006,36 @@ Xobject *KeyboardInterrupt; X Xstatic object * Xnewstdexception(name, message) -X char *name, *message; +X char *name, *message; X{ -X object *v = newstringobject(message); -X if (v == NULL || dictinsert(builtin_dict, name, v) != 0) -X fatal("no mem for new standard exception"); -X return v; +X object *v = newstringobject(message); +X if (v == NULL || dictinsert(builtin_dict, name, v) != 0) +X fatal("no mem for new standard exception"); +X return v; X} X Xstatic void Xiniterrors() X{ -X RuntimeError = newstdexception("RuntimeError", "run-time error"); -X EOFError = newstdexception("EOFError", "end-of-file read"); -X TypeError = newstdexception("TypeError", "type error"); -X MemoryError = newstdexception("MemoryError", "out of memory"); -X NameError = newstdexception("NameError", "undefined name"); -X SystemError = newstdexception("SystemError", "system error"); -X KeyboardInterrupt = -X newstdexception("KeyboardInterrupt", "keyboard interrupt"); +X RuntimeError = newstdexception("RuntimeError", "run-time error"); +X EOFError = newstdexception("EOFError", "end-of-file read"); +X TypeError = newstdexception("TypeError", "type error"); +X MemoryError = newstdexception("MemoryError", "out of memory"); +X NameError = newstdexception("NameError", "undefined name"); +X SystemError = newstdexception("SystemError", "system error"); +X KeyboardInterrupt = +X newstdexception("KeyboardInterrupt", "keyboard interrupt"); X} X Xvoid Xinitbuiltin() X{ -X object *m; -X m = initmodule("builtin", builtin_methods); -X builtin_dict = getmoduledict(m); -X INCREF(builtin_dict); -X initerrors(); -X (void) dictinsert(builtin_dict, "None", None); +X object *m; +X m = initmodule("builtin", builtin_methods); +X builtin_dict = getmoduledict(m); +X INCREF(builtin_dict); +X initerrors(); +X (void) dictinsert(builtin_dict, "None", None); X} EOF fi @@ -2058,14 +2058,14 @@ X X# Function to print to stderr X# Xdef err(args): -X savestdout = sys.stdout -X try: -X sys.stdout = sys.stderr -X for i in args: -X print i, -X print -X finally: -X sys.stdout = savestdout +X savestdout = sys.stdout +X try: +X sys.stdout = sys.stderr +X for i in args: +X print i, +X print +X finally: +X sys.stdout = savestdout X X X# The set of digits that form a number @@ -2078,20 +2078,20 @@ X# Returns the leading string of digits and the remaining string. X# If no number is found, returns '' and the original string. X# Xdef getnum(s): -X n = '' -X while s and s[0] in digits: -X n = n + s[0] -X s = s[1:] -X return n, s +X n = '' +X while s and s[0] in digits: +X n = n + s[0] +X s = s[1:] +X return n, s X X X# Function to check if a string is a number X# Xdef isnum(s): -X if not s: return 0 -X for c in s: -X if not c in digits: return 0 -X return 1 +X if not s: return 0 +X for c in s: +X if not c in digits: return 0 +X return 1 X X X# Allowed function return types @@ -2105,26 +2105,26 @@ Xarg_types = ['char', 'string', 'short', 'float', 'long', 'double'] X X X# Need to classify arguments as follows -X# simple input variable -X# simple output variable -X# input array -X# output array -X# input giving size of some array +X# simple input variable +X# simple output variable +X# input array +X# output array +X# input giving size of some array X# X# Array dimensions can be specified as follows -X# constant -X# argN -X# constant * argN -X# retval -X# constant * retval +X# constant +X# argN +X# constant * argN +X# retval +X# constant * retval X# X# The dimensions given as constants * something are really X# arrays of points where points are 2- 3- or 4-tuples X# X# We have to consider three lists: -X# python input arguments -X# C stub arguments (in & out) -X# python output arguments (really return values) +X# python input arguments +X# C stub arguments (in & out) +X# python output arguments (really return values) X# X# There is a mapping from python input arguments to the input arguments X# of the C stub, and a further mapping from C stub arguments to the @@ -2142,67 +2142,67 @@ X# Raises arg_error if something's wrong. X# Return type, mode, factor, rest of subscript; factor and rest may be empty. X# Xdef checkarg(type, arg): -X # -X # Turn "char *x" into "string x". -X # -X if type = 'char' and arg[0] = '*': -X type = 'string' -X arg = arg[1:] -X # -X # Check that the type is supported. -X # -X if type not in arg_types: -X raise arg_error, ('bad type', type) -X # -X # Split it in the mode (first character) and the rest. -X # -X mode, rest = arg[:1], arg[1:] -X # -X # The mode must be 's' for send (= input) or 'r' for return argument. -X # -X if mode not in ('r', 's'): -X raise arg_error, ('bad arg mode', mode) -X # -X # Is it a simple argument: if so, we are done. -X # -X if not rest: -X return type, mode, '', '' -X # -X # Not a simple argument; must be an array. -X # The 'rest' must be a subscript enclosed in [ and ]. -X # The subscript must be one of the following forms, -X # otherwise we don't handle it (where N is a number): -X # N -X # argN -X # retval -X # N*argN -X # N*retval -X # -X if rest[:1] <> '[' or rest[-1:] <> ']': -X raise arg_error, ('subscript expected', rest) -X sub = rest[1:-1] -X # -X # Is there a leading number? -X # -X num, sub = getnum(sub) -X if num: -X # There is a leading number -X if not sub: -X # The subscript is just a number -X return type, mode, num, '' -X if sub[:1] = '*': -X # There is a factor prefix -X sub = sub[1:] -X else: -X raise arg_error, ('\'*\' expected', sub) -X if sub = 'retval': -X # size is retval -- must be a reply argument -X if mode <> 'r': -X raise arg_error, ('non-r mode with [retval]', mode) -X elif sub[:3] <> 'arg' or not isnum(sub[3:]): -X raise arg_error, ('bad subscript', sub) -X # -X return type, mode, num, sub +X # +X # Turn "char *x" into "string x". +X # +X if type = 'char' and arg[0] = '*': +X type = 'string' +X arg = arg[1:] +X # +X # Check that the type is supported. +X # +X if type not in arg_types: +X raise arg_error, ('bad type', type) +X # +X # Split it in the mode (first character) and the rest. +X # +X mode, rest = arg[:1], arg[1:] +X # +X # The mode must be 's' for send (= input) or 'r' for return argument. +X # +X if mode not in ('r', 's'): +X raise arg_error, ('bad arg mode', mode) +X # +X # Is it a simple argument: if so, we are done. +X # +X if not rest: +X return type, mode, '', '' +X # +X # Not a simple argument; must be an array. +X # The 'rest' must be a subscript enclosed in [ and ]. +X # The subscript must be one of the following forms, +X # otherwise we don't handle it (where N is a number): +X # N +X # argN +X # retval +X # N*argN +X # N*retval +X # +X if rest[:1] <> '[' or rest[-1:] <> ']': +X raise arg_error, ('subscript expected', rest) +X sub = rest[1:-1] +X # +X # Is there a leading number? +X # +X num, sub = getnum(sub) +X if num: +X # There is a leading number +X if not sub: +X # The subscript is just a number +X return type, mode, num, '' +X if sub[:1] = '*': +X # There is a factor prefix +X sub = sub[1:] +X else: +X raise arg_error, ('\'*\' expected', sub) +X if sub = 'retval': +X # size is retval -- must be a reply argument +X if mode <> 'r': +X raise arg_error, ('non-r mode with [retval]', mode) +X elif sub[:3] <> 'arg' or not isnum(sub[3:]): +X raise arg_error, ('bad subscript', sub) +X # +X return type, mode, num, sub X X X# List of functions for which we have generated stubs @@ -2214,208 +2214,208 @@ X# Generate the stub for the given function, using the database of argument X# information build by successive calls to checkarg() X# Xdef generate(type, func, database): -X # -X # Check that we can handle this case: -X # no variable size reply arrays yet -X # -X n_in_args = 0 -X n_out_args = 0 -X # -X for a_type, a_mode, a_factor, a_sub in database: -X if a_mode = 's': -X n_in_args = n_in_args + 1 -X elif a_mode = 'r': -X n_out_args = n_out_args + 1 -X else: -X # Can't happen -X raise arg_error, ('bad a_mode', a_mode) -X if (a_mode = 'r' and a_sub) or a_sub = 'retval': -X e = 'Function', func, 'too complicated:' -X err(e + (a_type, a_mode, a_factor, a_sub)) -X print '/* XXX Too complicated to generate code for */' -X return -X # -X functions.append(func) -X # -X # Stub header -X # -X print -X print 'static object *' -X print 'gl_' + func + '(self, args)' -X print '\tobject *self;' -X print '\tobject *args;' -X print '{' -X # -X # Declare return value if any -X # -X if type <> 'void': -X print '\t' + type, 'retval;' -X # -X # Declare arguments -X # -X for i in range(len(database)): -X a_type, a_mode, a_factor, a_sub = database[i] -X print '\t' + a_type, -X if a_sub: -X print '*', -X print 'arg' + `i+1`, -X if a_factor and not a_sub: -X print '[', a_factor, ']', -X print ';' -X # -X # Find input arguments derived from array sizes -X # -X for i in range(len(database)): -X a_type, a_mode, a_factor, a_sub = database[i] -X if a_mode = 's' and a_sub[:3] = 'arg' and isnum(a_sub[3:]): -X # Sending a variable-length array -X n = eval(a_sub[3:]) -X if 1 <= n <= len(database): -X b_type, b_mode, b_factor, b_sub = database[n-1] -X if b_mode = 's': -X database[n-1] = b_type, 'i', a_factor, `i` -X n_in_args = n_in_args - 1 -X # -X # Assign argument positions in the Python argument list -X # -X in_pos = [] -X i_in = 0 -X for i in range(len(database)): -X a_type, a_mode, a_factor, a_sub = database[i] -X if a_mode = 's': -X in_pos.append(i_in) -X i_in = i_in + 1 -X else: -X in_pos.append(-1) -X # -X # Get input arguments -X # -X for i in range(len(database)): -X a_type, a_mode, a_factor, a_sub = database[i] -X if a_mode = 'i': -X # -X # Implicit argument; -X # a_factor is divisor if present, -X # a_sub indicates which arg (`database index`) -X # -X j = eval(a_sub) -X print '\tif', -X print '(!geti' + a_type + 'arraysize(args,', -X print `n_in_args` + ',', -X print `in_pos[j]` + ',', -X print '&arg' + `i+1` + '))' -X print '\t\treturn NULL;' -X if a_factor: -X print '\targ' + `i+1`, -X print '= arg' + `i+1`, -X print '/', a_factor + ';' -X elif a_mode = 's': -X if a_sub: # Allocate memory for varsize array -X print '\tif ((arg' + `i+1`, '=', -X print 'NEW(' + a_type + ',', -X if a_factor: print a_factor, '*', -X print a_sub, ')) == NULL)' -X print '\t\treturn err_nomem();' -X print '\tif', -X if a_factor or a_sub: # Get a fixed-size array array -X print '(!geti' + a_type + 'array(args,', -X print `n_in_args` + ',', -X print `in_pos[i]` + ',', -X if a_factor: print a_factor, -X if a_factor and a_sub: print '*', -X if a_sub: print a_sub, -X print ', arg' + `i+1` + '))' -X else: # Get a simple variable -X print '(!geti' + a_type + 'arg(args,', -X print `n_in_args` + ',', -X print `in_pos[i]` + ',', -X print '&arg' + `i+1` + '))' -X print '\t\treturn NULL;' -X # -X # Begin of function call -X # -X if type <> 'void': -X print '\tretval =', func + '(', -X else: -X print '\t' + func + '(', -X # -X # Argument list -X # -X for i in range(len(database)): -X if i > 0: print ',', -X a_type, a_mode, a_factor, a_sub = database[i] -X if a_mode = 'r' and not a_factor: -X print '&', -X print 'arg' + `i+1`, -X # -X # End of function call -X # -X print ');' -X # -X # Free varsize arrays -X # -X for i in range(len(database)): -X a_type, a_mode, a_factor, a_sub = database[i] -X if a_mode = 's' and a_sub: -X print '\tDEL(arg' + `i+1` + ');' -X # -X # Return -X # -X if n_out_args: -X # -X # Multiple return values -- construct a tuple -X # -X if type <> 'void': -X n_out_args = n_out_args + 1 -X if n_out_args = 1: -X for i in range(len(database)): -X a_type, a_mode, a_factor, a_sub = database[i] -X if a_mode = 'r': -X break -X else: -X raise arg_error, 'expected r arg not found' -X print '\treturn', -X print mkobject(a_type, 'arg' + `i+1`) + ';' -X else: -X print '\t{ object *v = newtupleobject(', -X print n_out_args, ');' -X print '\t if (v == NULL) return NULL;' -X i_out = 0 -X if type <> 'void': -X print '\t settupleitem(v,', -X print `i_out` + ',', -X print mkobject(type, 'retval') + ');' -X i_out = i_out + 1 -X for i in range(len(database)): -X a_type, a_mode, a_factor, a_sub = database[i] -X if a_mode = 'r': -X print '\t settupleitem(v,', -X print `i_out` + ',', -X s = mkobject(a_type, 'arg' + `i+1`) -X print s + ');' -X i_out = i_out + 1 -X print '\t return v;' -X print '\t}' -X else: -X # -X # Simple function return -X # Return None or return value -X # -X if type = 'void': -X print '\tINCREF(None);' -X print '\treturn None;' -X else: -X print '\treturn', mkobject(type, 'retval') + ';' -X # -X # Stub body closing brace -X # -X print '}' +X # +X # Check that we can handle this case: +X # no variable size reply arrays yet +X # +X n_in_args = 0 +X n_out_args = 0 +X # +X for a_type, a_mode, a_factor, a_sub in database: +X if a_mode = 's': +X n_in_args = n_in_args + 1 +X elif a_mode = 'r': +X n_out_args = n_out_args + 1 +X else: +X # Can't happen +X raise arg_error, ('bad a_mode', a_mode) +X if (a_mode = 'r' and a_sub) or a_sub = 'retval': +X e = 'Function', func, 'too complicated:' +X err(e + (a_type, a_mode, a_factor, a_sub)) +X print '/* XXX Too complicated to generate code for */' +X return +X # +X functions.append(func) +X # +X # Stub header +X # +X print +X print 'static object *' +X print 'gl_' + func + '(self, args)' +X print '\tobject *self;' +X print '\tobject *args;' +X print '{' +X # +X # Declare return value if any +X # +X if type <> 'void': +X print '\t' + type, 'retval;' +X # +X # Declare arguments +X # +X for i in range(len(database)): +X a_type, a_mode, a_factor, a_sub = database[i] +X print '\t' + a_type, +X if a_sub: +X print '*', +X print 'arg' + `i+1`, +X if a_factor and not a_sub: +X print '[', a_factor, ']', +X print ';' +X # +X # Find input arguments derived from array sizes +X # +X for i in range(len(database)): +X a_type, a_mode, a_factor, a_sub = database[i] +X if a_mode = 's' and a_sub[:3] = 'arg' and isnum(a_sub[3:]): +X # Sending a variable-length array +X n = eval(a_sub[3:]) +X if 1 <= n <= len(database): +X b_type, b_mode, b_factor, b_sub = database[n-1] +X if b_mode = 's': +X database[n-1] = b_type, 'i', a_factor, `i` +X n_in_args = n_in_args - 1 +X # +X # Assign argument positions in the Python argument list +X # +X in_pos = [] +X i_in = 0 +X for i in range(len(database)): +X a_type, a_mode, a_factor, a_sub = database[i] +X if a_mode = 's': +X in_pos.append(i_in) +X i_in = i_in + 1 +X else: +X in_pos.append(-1) +X # +X # Get input arguments +X # +X for i in range(len(database)): +X a_type, a_mode, a_factor, a_sub = database[i] +X if a_mode = 'i': +X # +X # Implicit argument; +X # a_factor is divisor if present, +X # a_sub indicates which arg (`database index`) +X # +X j = eval(a_sub) +X print '\tif', +X print '(!geti' + a_type + 'arraysize(args,', +X print `n_in_args` + ',', +X print `in_pos[j]` + ',', +X print '&arg' + `i+1` + '))' +X print '\t\treturn NULL;' +X if a_factor: +X print '\targ' + `i+1`, +X print '= arg' + `i+1`, +X print '/', a_factor + ';' +X elif a_mode = 's': +X if a_sub: # Allocate memory for varsize array +X print '\tif ((arg' + `i+1`, '=', +X print 'NEW(' + a_type + ',', +X if a_factor: print a_factor, '*', +X print a_sub, ')) == NULL)' +X print '\t\treturn err_nomem();' +X print '\tif', +X if a_factor or a_sub: # Get a fixed-size array array +X print '(!geti' + a_type + 'array(args,', +X print `n_in_args` + ',', +X print `in_pos[i]` + ',', +X if a_factor: print a_factor, +X if a_factor and a_sub: print '*', +X if a_sub: print a_sub, +X print ', arg' + `i+1` + '))' +X else: # Get a simple variable +X print '(!geti' + a_type + 'arg(args,', +X print `n_in_args` + ',', +X print `in_pos[i]` + ',', +X print '&arg' + `i+1` + '))' +X print '\t\treturn NULL;' +X # +X # Begin of function call +X # +X if type <> 'void': +X print '\tretval =', func + '(', +X else: +X print '\t' + func + '(', +X # +X # Argument list +X # +X for i in range(len(database)): +X if i > 0: print ',', +X a_type, a_mode, a_factor, a_sub = database[i] +X if a_mode = 'r' and not a_factor: +X print '&', +X print 'arg' + `i+1`, +X # +X # End of function call +X # +X print ');' +X # +X # Free varsize arrays +X # +X for i in range(len(database)): +X a_type, a_mode, a_factor, a_sub = database[i] +X if a_mode = 's' and a_sub: +X print '\tDEL(arg' + `i+1` + ');' +X # +X # Return +X # +X if n_out_args: +X # +X # Multiple return values -- construct a tuple +X # +X if type <> 'void': +X n_out_args = n_out_args + 1 +X if n_out_args = 1: +X for i in range(len(database)): +X a_type, a_mode, a_factor, a_sub = database[i] +X if a_mode = 'r': +X break +X else: +X raise arg_error, 'expected r arg not found' +X print '\treturn', +X print mkobject(a_type, 'arg' + `i+1`) + ';' +X else: +X print '\t{ object *v = newtupleobject(', +X print n_out_args, ');' +X print '\t if (v == NULL) return NULL;' +X i_out = 0 +X if type <> 'void': +X print '\t settupleitem(v,', +X print `i_out` + ',', +X print mkobject(type, 'retval') + ');' +X i_out = i_out + 1 +X for i in range(len(database)): +X a_type, a_mode, a_factor, a_sub = database[i] +X if a_mode = 'r': +X print '\t settupleitem(v,', +X print `i_out` + ',', +X s = mkobject(a_type, 'arg' + `i+1`) +X print s + ');' +X i_out = i_out + 1 +X print '\t return v;' +X print '\t}' +X else: +X # +X # Simple function return +X # Return None or return value +X # +X if type = 'void': +X print '\tINCREF(None);' +X print '\treturn None;' +X else: +X print '\treturn', mkobject(type, 'retval') + ';' +X # +X # Stub body closing brace +X # +X print '}' X X X# Subroutine to return a function call to mknew<type>object(<arg>) X# Xdef mkobject(type, arg): -X return 'mknew' + type + 'object(' + arg + ')' +X return 'mknew' + type + 'object(' + arg + ')' X X X# Input line number @@ -2423,8 +2423,8 @@ Xlno = 0 X X X# Input is divided in two parts, separated by a line containing '%%'. -X# <part1> -- literally copied to stdout -X# <part2> -- stub definitions +X# <part1> -- literally copied to stdout +X# <part2> -- stub definitions X X# Variable indicating the current input part. X# @@ -2433,68 +2433,68 @@ X X# Main loop over the input X# Xwhile 1: -X try: -X line = raw_input() -X except EOFError: -X break -X # -X lno = lno+1 -X words = string.split(line) -X # -X if part = 1: -X # -X # In part 1, copy everything literally -X # except look for a line of just '%%' -X # -X if words = ['%%']: -X part = part + 1 -X else: -X # -X # Look for names of manually written -X # stubs: a single percent followed by the name -X # of the function in Python. -X # The stub name is derived by prefixing 'gl_'. -X # -X if words and words[0][0] = '%': -X func = words[0][1:] -X if (not func) and words[1:]: -X func = words[1] -X if func: -X functions.append(func) -X else: -X print line -X elif not words: -X pass # skip empty line -X elif words[0] = '#include': -X print line -X elif words[0][:1] = '#': -X pass # ignore comment -X elif words[0] not in return_types: -X err('Line', lno, ': bad return type :', words[0]) -X elif len(words) < 2: -X err('Line', lno, ': no funcname :', line) -X else: -X if len(words) % 2 <> 0: -X err('Line', lno, ': odd argument list :', words[2:]) -X else: -X database = [] -X try: -X for i in range(2, len(words), 2): -X x = checkarg(words[i], words[i+1]) -X database.append(x) -X print -X print '/*', -X for w in words: print w, -X print '*/' -X generate(words[0], words[1], database) -X except arg_error, msg: -X err('Line', lno, ':', msg) +X try: +X line = raw_input() +X except EOFError: +X break +X # +X lno = lno+1 +X words = string.split(line) +X # +X if part = 1: +X # +X # In part 1, copy everything literally +X # except look for a line of just '%%' +X # +X if words = ['%%']: +X part = part + 1 +X else: +X # +X # Look for names of manually written +X # stubs: a single percent followed by the name +X # of the function in Python. +X # The stub name is derived by prefixing 'gl_'. +X # +X if words and words[0][0] = '%': +X func = words[0][1:] +X if (not func) and words[1:]: +X func = words[1] +X if func: +X functions.append(func) +X else: +X print line +X elif not words: +X pass # skip empty line +X elif words[0] = '#include': +X print line +X elif words[0][:1] = '#': +X pass # ignore comment +X elif words[0] not in return_types: +X err('Line', lno, ': bad return type :', words[0]) +X elif len(words) < 2: +X err('Line', lno, ': no funcname :', line) +X else: +X if len(words) % 2 <> 0: +X err('Line', lno, ': odd argument list :', words[2:]) +X else: +X database = [] +X try: +X for i in range(2, len(words), 2): +X x = checkarg(words[i], words[i+1]) +X database.append(x) +X print +X print '/*', +X for w in words: print w, +X print '*/' +X generate(words[0], words[1], database) +X except arg_error, msg: +X err('Line', lno, ':', msg) X X Xprint Xprint 'static struct methodlist gl_methods[] = {' Xfor func in functions: -X print '\t{"' + func + '", gl_' + func + '},' +X print '\t{"' + func + '", gl_' + func + '},' Xprint '\t{NULL, NULL} /* Sentinel */' Xprint '};' Xprint @@ -2505,4 +2505,4 @@ Xprint '}' EOF fi echo 'Part 10 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-11-21.shar b/shar/python-0.9.1-11-21.shar index 59aa0a2..847e47f 100644 --- a/shar/python-0.9.1-11-21.shar +++ b/shar/python-0.9.1-11-21.shar @@ -30,374 +30,374 @@ X X# LabelAppearance provides defaults for all appearance methods. X# selected state not visible X# disabled --> crossed out -X# hilited --> inverted +X# hilited --> inverted X# Xclass LabelAppearance(): -X # -X # Initialization -X # -X def init_appearance(self): -X self.bounds = _rect.empty -X self.enabled = 1 -X self.hilited = 0 -X self.selected = 0 -X self.text = '' -X # -X # Size enquiry -X # -X def minsize(self, m): -X try: -X self.text = self.text -X except NameError: -X self.text = '' -X return m.textwidth(self.text) + 6, m.lineheight() + 6 -X # -X def getbounds(self): -X return self.bounds -X # -X # Changing the parameters -X # -X def settext(self, text): -X self.text = text -X if self.bounds <> _rect.empty: -X self.recalctextpos() -X self.redraw() -X # -X def setbounds(self, bounds): -X if self.bounds <> _rect.empty: -X self.parent.change(self.bounds) -X self.bounds = bounds -X if self.bounds <> _rect.empty: -X self.recalc() -X self.parent.change(bounds) -X # -X # Changing the state bits -X # -X def enable(self, flag): -X if flag <> self.enabled: -X self.enabled = flag -X if self.bounds <> _rect.empty: -X self.flipenable(self.parent.begindrawing()) -X # -X def hilite(self, flag): -X if flag <> self.hilited: -X self.hilited = flag -X if self.bounds <> _rect.empty: -X self.fliphilite(self.parent.begindrawing()) -X # -X def select(self, flag): -X if flag <> self.selected: -X self.selected = flag -X if self.bounds <> _rect.empty: -X self.redraw() -X # -X # Recalculate the box bounds and text position. -X # This can be overridden by buttons that draw different boxes -X # or want their text in a different position. -X # -X def recalc(self): -X if self.bounds <> _rect.empty: -X self.recalcbounds() -X self.recalctextpos() -X # -X def recalcbounds(self): -X self.hilitebounds = _rect.inset(self.bounds, (3, 3)) -X self.crossbounds = self.bounds -X # -X def recalctextpos(self): -X (left, top), (right, bottom) = self.bounds -X m = self.parent.beginmeasuring() -X h = (left + right - m.textwidth(self.text)) / 2 -X v = (top + bottom - m.lineheight()) / 2 -X self.textpos = h, v -X # -X # Generic drawing interface. -X # Do not override redraw() or draw() methods; override drawit() c.s. -X # -X def redraw(self): -X if self.bounds <> _rect.empty: -X self.draw(self.parent.begindrawing(), self.bounds) -X # -X def draw(self, (d, area)): -X area = _rect.intersect(area, self.bounds) -X if area = _rect.empty: -X return -X d.cliprect(area) -X d.erase(self.bounds) -X self.drawit(d) -X d.noclip() -X # -X # The drawit() method is fairly generic but may be overridden. -X # -X def drawit(self, d): -X self.drawpict(d) -X if self.text: -X d.text(self.textpos, self.text) -X if not self.enabled: -X self.flipenable(d) -X if self.hilited: -X self.fliphilite(d) -X # -X # Default drawing detail functions. -X # Overriding these is normally sufficient to get different -X # appearances. -X # -X def drawpict(self, d): -X pass -X # -X def flipenable(self, d): -X _xorcross(d, self.crossbounds) -X # -X def fliphilite(self, d): -X d.invert(self.hilitebounds) +X # +X # Initialization +X # +X def init_appearance(self): +X self.bounds = _rect.empty +X self.enabled = 1 +X self.hilited = 0 +X self.selected = 0 +X self.text = '' +X # +X # Size enquiry +X # +X def minsize(self, m): +X try: +X self.text = self.text +X except NameError: +X self.text = '' +X return m.textwidth(self.text) + 6, m.lineheight() + 6 +X # +X def getbounds(self): +X return self.bounds +X # +X # Changing the parameters +X # +X def settext(self, text): +X self.text = text +X if self.bounds <> _rect.empty: +X self.recalctextpos() +X self.redraw() +X # +X def setbounds(self, bounds): +X if self.bounds <> _rect.empty: +X self.parent.change(self.bounds) +X self.bounds = bounds +X if self.bounds <> _rect.empty: +X self.recalc() +X self.parent.change(bounds) +X # +X # Changing the state bits +X # +X def enable(self, flag): +X if flag <> self.enabled: +X self.enabled = flag +X if self.bounds <> _rect.empty: +X self.flipenable(self.parent.begindrawing()) +X # +X def hilite(self, flag): +X if flag <> self.hilited: +X self.hilited = flag +X if self.bounds <> _rect.empty: +X self.fliphilite(self.parent.begindrawing()) +X # +X def select(self, flag): +X if flag <> self.selected: +X self.selected = flag +X if self.bounds <> _rect.empty: +X self.redraw() +X # +X # Recalculate the box bounds and text position. +X # This can be overridden by buttons that draw different boxes +X # or want their text in a different position. +X # +X def recalc(self): +X if self.bounds <> _rect.empty: +X self.recalcbounds() +X self.recalctextpos() +X # +X def recalcbounds(self): +X self.hilitebounds = _rect.inset(self.bounds, (3, 3)) +X self.crossbounds = self.bounds +X # +X def recalctextpos(self): +X (left, top), (right, bottom) = self.bounds +X m = self.parent.beginmeasuring() +X h = (left + right - m.textwidth(self.text)) / 2 +X v = (top + bottom - m.lineheight()) / 2 +X self.textpos = h, v +X # +X # Generic drawing interface. +X # Do not override redraw() or draw() methods; override drawit() c.s. +X # +X def redraw(self): +X if self.bounds <> _rect.empty: +X self.draw(self.parent.begindrawing(), self.bounds) +X # +X def draw(self, (d, area)): +X area = _rect.intersect(area, self.bounds) +X if area = _rect.empty: +X return +X d.cliprect(area) +X d.erase(self.bounds) +X self.drawit(d) +X d.noclip() +X # +X # The drawit() method is fairly generic but may be overridden. +X # +X def drawit(self, d): +X self.drawpict(d) +X if self.text: +X d.text(self.textpos, self.text) +X if not self.enabled: +X self.flipenable(d) +X if self.hilited: +X self.fliphilite(d) +X # +X # Default drawing detail functions. +X # Overriding these is normally sufficient to get different +X # appearances. +X # +X def drawpict(self, d): +X pass +X # +X def flipenable(self, d): +X _xorcross(d, self.crossbounds) +X # +X def fliphilite(self, d): +X d.invert(self.hilitebounds) X X X# ButtonAppearance displays a centered string in a box. X# selected --> bold border X# disabled --> crossed out -X# hilited --> inverted +X# hilited --> inverted X# Xclass ButtonAppearance() = LabelAppearance(): -X # -X def drawpict(self, d): -X d.box(_rect.inset(self.bounds, (1, 1))) -X if self.selected: -X # Make a thicker box -X d.box(self.bounds) -X d.box(_rect.inset(self.bounds, (2, 2))) -X d.box(_rect.inset(self.bounds, (3, 3))) -X # +X # +X def drawpict(self, d): +X d.box(_rect.inset(self.bounds, (1, 1))) +X if self.selected: +X # Make a thicker box +X d.box(self.bounds) +X d.box(_rect.inset(self.bounds, (2, 2))) +X d.box(_rect.inset(self.bounds, (3, 3))) +X # X X X# CheckAppearance displays a small square box and a left-justified string. X# selected --> a cross appears in the box X# disabled --> whole button crossed out -X# hilited --> box is inverted +X# hilited --> box is inverted X# Xclass CheckAppearance() = LabelAppearance(): -X # -X def minsize(self, m): -X width, height = m.textwidth(self.text) + 6, m.lineheight() + 6 -X return width + height + m.textwidth(' '), height -X # -X def drawpict(self, d): -X d.box(self.boxbounds) -X if self.selected: _xorcross(d, self.boxbounds) -X # -X def recalcbounds(self): -X LabelAppearance.recalcbounds(self) -X (left, top), (right, bottom) = self.bounds -X self.size = bottom - top - 4 -X self.boxbounds = (left+2, top+2), (left+2+self.size, bottom-2) -X self.hilitebounds = self.boxbounds -X # -X def recalctextpos(self): -X m = self.parent.beginmeasuring() -X (left, top), (right, bottom) = self.boxbounds -X h = right + m.textwidth(' ') -X v = top + (self.size - m.lineheight()) / 2 -X self.textpos = h, v -X # +X # +X def minsize(self, m): +X width, height = m.textwidth(self.text) + 6, m.lineheight() + 6 +X return width + height + m.textwidth(' '), height +X # +X def drawpict(self, d): +X d.box(self.boxbounds) +X if self.selected: _xorcross(d, self.boxbounds) +X # +X def recalcbounds(self): +X LabelAppearance.recalcbounds(self) +X (left, top), (right, bottom) = self.bounds +X self.size = bottom - top - 4 +X self.boxbounds = (left+2, top+2), (left+2+self.size, bottom-2) +X self.hilitebounds = self.boxbounds +X # +X def recalctextpos(self): +X m = self.parent.beginmeasuring() +X (left, top), (right, bottom) = self.boxbounds +X h = right + m.textwidth(' ') +X v = top + (self.size - m.lineheight()) / 2 +X self.textpos = h, v +X # X X X# RadioAppearance displays a round indicator and a left-justified string. X# selected --> a dot appears in the indicator X# disabled --> whole button crossed out -X# hilited --> indicator is inverted +X# hilited --> indicator is inverted X# Xclass RadioAppearance() = CheckAppearance(): -X # -X def drawpict(self, d): -X (left, top), (right, bottom) = self.boxbounds -X radius = self.size / 2 -X h, v = left + radius, top + radius -X d.circle((h, v), radius) -X if self.selected: -X some = radius/3 -X d.paint((h-some, v-some), (h+some, v+some)) -X # +X # +X def drawpict(self, d): +X (left, top), (right, bottom) = self.boxbounds +X radius = self.size / 2 +X h, v = left + radius, top + radius +X d.circle((h, v), radius) +X if self.selected: +X some = radius/3 +X d.paint((h-some, v-some), (h+some, v+some)) +X # X X X# NoReactivity ignores mouse events. X# Xclass NoReactivity(): -X def init_reactivity(self): pass +X def init_reactivity(self): pass X X X# BaseReactivity defines hooks and asks for mouse events, X# but provides only dummy mouse event handlers. X# The trigger methods call the corresponding hooks set by the user. X# Hooks (and triggers) mean the following: -X# down_hook called on some mouse-down events -X# move_hook called on some mouse-move events -X# up_hook called on mouse-up events -X# on_hook called for buttons with on/off state, when it goes on -X# hook called when a button 'fires' or a radiobutton goes on +X# down_hook called on some mouse-down events +X# move_hook called on some mouse-move events +X# up_hook called on mouse-up events +X# on_hook called for buttons with on/off state, when it goes on +X# hook called when a button 'fires' or a radiobutton goes on X# There are usually extra conditions, e.g., hooks are only called X# when the button is enabled, or active, or selected (on). X# Xclass BaseReactivity(): -X # -X def init_reactivity(self): -X self.down_hook = self.move_hook = self.up_hook = \ -X self.on_hook = self.off_hook = \ -X self.hook = self.active = 0 -X self.parent.need_mouse(self) -X # -X def mousetest(self, hv): -X return _rect.pointinrect(hv, self.bounds) -X # -X def mouse_down(self, detail): -X pass -X # -X def mouse_move(self, detail): -X pass -X # -X def mouse_up(self, detail): -X pass -X # -X def down_trigger(self): -X if self.down_hook: self.down_hook(self) -X # -X def move_trigger(self): -X if self.move_hook: self.move_hook(self) -X # -X def up_trigger(self): -X if self.up_hook: self.up_hook(self) -X # -X def on_trigger(self): -X if self.on_hook: self.on_hook(self) -X # -X def off_trigger(self): -X if self.off_hook: self.off_hook(self) -X # -X def trigger(self): -X if self.hook: self.hook(self) +X # +X def init_reactivity(self): +X self.down_hook = self.move_hook = self.up_hook = \ +X self.on_hook = self.off_hook = \ +X self.hook = self.active = 0 +X self.parent.need_mouse(self) +X # +X def mousetest(self, hv): +X return _rect.pointinrect(hv, self.bounds) +X # +X def mouse_down(self, detail): +X pass +X # +X def mouse_move(self, detail): +X pass +X # +X def mouse_up(self, detail): +X pass +X # +X def down_trigger(self): +X if self.down_hook: self.down_hook(self) +X # +X def move_trigger(self): +X if self.move_hook: self.move_hook(self) +X # +X def up_trigger(self): +X if self.up_hook: self.up_hook(self) +X # +X def on_trigger(self): +X if self.on_hook: self.on_hook(self) +X # +X def off_trigger(self): +X if self.off_hook: self.off_hook(self) +X # +X def trigger(self): +X if self.hook: self.hook(self) X X X# ToggleReactivity acts like a simple pushbutton. X# It toggles its hilite state on mouse down events. X# Xclass ToggleReactivity() = BaseReactivity(): -X # -X def mouse_down(self, detail): -X if self.enabled and self.mousetest(detail[_HV]): -X self.active = 1 -X self.hilite(not self.hilited) -X self.down_trigger() -X # -X def mouse_move(self, detail): -X if self.active: -X self.move_trigger() -X # -X def mouse_up(self, detail): -X if self.active: -X self.up_trigger() -X self.active = 0 -X # -X def down_trigger(self): -X if self.hilited: -X self.on_trigger() -X else: -X self.off_trigger() -X self.trigger() -X # +X # +X def mouse_down(self, detail): +X if self.enabled and self.mousetest(detail[_HV]): +X self.active = 1 +X self.hilite(not self.hilited) +X self.down_trigger() +X # +X def mouse_move(self, detail): +X if self.active: +X self.move_trigger() +X # +X def mouse_up(self, detail): +X if self.active: +X self.up_trigger() +X self.active = 0 +X # +X def down_trigger(self): +X if self.hilited: +X self.on_trigger() +X else: +X self.off_trigger() +X self.trigger() +X # X X X# TriggerReactivity acts like a fancy pushbutton. X# It hilites itself while the mouse is down within its bounds. X# Xclass TriggerReactivity() = BaseReactivity(): -X # -X def mouse_down(self, detail): -X if self.enabled and self.mousetest(detail[_HV]): -X self.active = 1 -X self.hilite(1) -X self.down_trigger() -X # -X def mouse_move(self, detail): -X if self.active: -X self.hilite(self.mousetest(detail[_HV])) -X if self.hilited: -X self.move_trigger() -X # -X def mouse_up(self, detail): -X if self.active: -X self.hilite(self.mousetest(detail[_HV])) -X if self.hilited: -X self.up_trigger() -X self.trigger() -X self.active = 0 -X self.hilite(0) -X # +X # +X def mouse_down(self, detail): +X if self.enabled and self.mousetest(detail[_HV]): +X self.active = 1 +X self.hilite(1) +X self.down_trigger() +X # +X def mouse_move(self, detail): +X if self.active: +X self.hilite(self.mousetest(detail[_HV])) +X if self.hilited: +X self.move_trigger() +X # +X def mouse_up(self, detail): +X if self.active: +X self.hilite(self.mousetest(detail[_HV])) +X if self.hilited: +X self.up_trigger() +X self.trigger() +X self.active = 0 +X self.hilite(0) +X # X X X# CheckReactivity handles mouse events like TriggerReactivity, X# It overrides the up_trigger method to flip its selected state. X# Xclass CheckReactivity() = TriggerReactivity(): -X # -X def up_trigger(self): -X self.select(not self.selected) -X if self.selected: -X self.on_trigger() -X else: -X self.off_trigger() -X self.trigger() +X # +X def up_trigger(self): +X self.select(not self.selected) +X if self.selected: +X self.on_trigger() +X else: +X self.off_trigger() +X self.trigger() X X X# RadioReactivity turns itself on and the other buttons in its group X# off when its up_trigger method is called. X# Xclass RadioReactivity() = TriggerReactivity(): -X # -X def init_reactivity(self): -X TriggerReactivity.init_reactivity(self) -X self.group = [] -X # -X def up_trigger(self): -X for b in self.group: -X if b <> self: -X if b.selected: -X b.select(0) -X b.off_trigger() -X self.select(1) -X self.on_trigger() -X self.trigger() +X # +X def init_reactivity(self): +X TriggerReactivity.init_reactivity(self) +X self.group = [] +X # +X def up_trigger(self): +X for b in self.group: +X if b <> self: +X if b.selected: +X b.select(0) +X b.off_trigger() +X self.select(1) +X self.on_trigger() +X self.trigger() X X X# Auxiliary class for 'define' method. X# Call the initializers in the right order. X# Xclass Define(): -X # -X def define(self, parent): -X self.parent = parent -X parent.addchild(self) -X self.init_appearance() -X self.init_reactivity() -X return self -X # -X def destroy(self): -X self.parent = 0 -X # -X def definetext(self, (parent, text)): -X self = self.define(parent) -X self.settext(text) -X return self +X # +X def define(self, parent): +X self.parent = parent +X parent.addchild(self) +X self.init_appearance() +X self.init_reactivity() +X return self +X # +X def destroy(self): +X self.parent = 0 +X # +X def definetext(self, (parent, text)): +X self = self.define(parent) +X self.settext(text) +X return self X X X# Subroutine to cross out a rectangle. X# Xdef _xorcross(d, bounds): -X ((left, top), (right, bottom)) = bounds -X # This is s bit funny to make it look better -X left = left + 2 -X right = right - 2 -X top = top + 2 -X bottom = bottom - 3 -X d.xorline(((left, top), (right, bottom))) -X d.xorline((left, bottom), (right, top)) +X ((left, top), (right, bottom)) = bounds +X # This is s bit funny to make it look better +X left = left + 2 +X right = right - 2 +X top = top + 2 +X bottom = bottom - 3 +X d.xorline(((left, top), (right, bottom))) +X d.xorline((left, bottom), (right, top)) X X X# Ready-made button classes. @@ -428,7 +428,7 @@ X# A few functions have multiple return values. X X X# For efficiency, the Tcl "tokenizing" routines used pre-compiled -X# regular expressions. This is less readable but should be much faster +X# regular expressions. This is less readable but should be much faster X# than scanning the string a character at a time. X# X# The global variables @@ -437,9 +437,9 @@ X# an indication of the function that uses them. X# X# The patterns always X# have the form <something>* so they always match at the start of the -X# search buffer---maybe with the empty string. This makes it possible +X# search buffer---maybe with the empty string. This makes it possible X# to use the expression "_foo_prog.exec(str, i)[0][1]" to find the first -X# character beyond the matched string. Note that this may be beyond the +X# character beyond the matched string. Note that this may be beyond the X# end variable -- where this matters, "min(i, end)" is used. X X# Constructs that cannot @@ -449,19 +449,19 @@ X# braces. X# X# Many regular expressions contain an expression that matches X# a Tcl backslash sequence as a subpart: -X# \\\\C?M?(.|\n) +X# \\\\C?M?(.|\n) X# X# This is a bit hard to X# read because the backslash contained in it must be doubled twice: X# once to get past Python's backslash mechanism, once to get past that -X# of regular expressions. It uses (.|\n) to match absolutely +X# of regular expressions. It uses (.|\n) to match absolutely X# *every character*, becase the MULTILINE regular expression package does X# not accept '\n' as a match for '.'. X# X# There is also a simplification in the pattern for backslashes: X# *any* single character following a backslash is escaped, X# so hex and octal -X# excapes are not scanned fully. The forms \Cx, \Mx and \CMx are +X# excapes are not scanned fully. The forms \Cx, \Mx and \CMx are X# scanned correctly, as these may hide a special character. X# (This does not invalidate the recognition of strings, although the X# match is effectuated in a different way than by the Backslash function.) @@ -485,28 +485,28 @@ X X_varname_prog = regexp.compile('[a-zA-Z0-9_]*') X Xdef FindVarName(str, i, end): -X if i < end and str[i] = '{': return BalanceBraces(str, i, end) -X i = _varname_prog.exec(str, i)[0][1] -X return min(i, end) +X if i < end and str[i] = '{': return BalanceBraces(str, i, end) +X i = _varname_prog.exec(str, i)[0][1] +X return min(i, end) X X X# Split a list into its elements. X# Return a list of elements (strings). X Xdef SplitList(str): -X i, end = 0, len(str) -X list = [] -X while 1: -X i = SkipSpaces(str, i, end) -X if i >= end: break -X j = i -X i = FindNextElement(str, i, end) -X if str[j] = '{' and str[i-1] = '}': -X element = str[j+1:i-1] -X else: -X element = Collapse(str[j:i]) -X list.append(element) -X return list +X i, end = 0, len(str) +X list = [] +X while 1: +X i = SkipSpaces(str, i, end) +X if i >= end: break +X j = i +X i = FindNextElement(str, i, end) +X if str[j] = '{' and str[i-1] = '}': +X element = str[j+1:i-1] +X else: +X element = Collapse(str[j:i]) +X list.append(element) +X return list X X X# Find the next element from a list. @@ -514,13 +514,13 @@ X X_element_prog = regexp.compile('([^ \t\n\\]+|\\\\C?M?(.|\n))*') X Xdef FindNextElement(str, i, end): -X if i < end and str[i] = '{': -X i = BalanceBraces(str, i, end) -X if i < end and str[i] not in ' \t\n': -X raise TclSyntaxError, 'Garbage after } in list' -X return i -X i = _element_prog.exec(str, i)[0][1] -X return min(i, end) +X if i < end and str[i] = '{': +X i = BalanceBraces(str, i, end) +X if i < end and str[i] not in ' \t\n': +X raise TclSyntaxError, 'Garbage after } in list' +X return i +X i = _element_prog.exec(str, i)[0][1] +X return min(i, end) X X X# Copy a string, expanding all backslash sequences. @@ -528,19 +528,19 @@ X X_collapse_prog = regexp.compile('(\n|[^\\]+)*') X Xdef Collapse(str): -X if '\\' not in str: return str -X i, end = 0, len(str) -X result = '' -X while i < end: -X j = _collapse_prog.exec(str, i)[0][1] -X j = min(j, end) -X result = result + str[i:j] -X if j >= end: break -X c = str[j] -X if c <> '\\': raise TclAssertError, 'collapse error' -X x, i = Backslash(str, j, end) -X result = result + x -X return result +X if '\\' not in str: return str +X i, end = 0, len(str) +X result = '' +X while i < end: +X j = _collapse_prog.exec(str, i)[0][1] +X j = min(j, end) +X result = result + str[i:j] +X if j >= end: break +X c = str[j] +X if c <> '\\': raise TclAssertError, 'collapse error' +X x, i = Backslash(str, j, end) +X result = result + x +X return result X X X# Find the next full command. @@ -554,25 +554,25 @@ X X_eol_prog = regexp.compile('[^\n]*') X Xdef FindNextCommand(str, i, end, bracketed): -X i = SkipSpaces(str, i, end) -X if i >= end: return [], end -X if str[i] = '#': -X i = _eol_prog.exec(str, i) -X i = min(i, end) -X if i < end and str[i] = '\n': i = i+1 -X return [], i -X if bracketed: terminators = [';'] -X else: terminators = [';', '\n'] -X list = [] -X while i < end: -X j = FindNextWord(str, i, end) -X word = str[i:j] -X if word in terminators: -X i = j -X break -X if word <> '\n': list.append(i, j) -X i = SkipSpaces(str, j, end) -X return list, i +X i = SkipSpaces(str, i, end) +X if i >= end: return [], end +X if str[i] = '#': +X i = _eol_prog.exec(str, i) +X i = min(i, end) +X if i < end and str[i] = '\n': i = i+1 +X return [], i +X if bracketed: terminators = [';'] +X else: terminators = [';', '\n'] +X list = [] +X while i < end: +X j = FindNextWord(str, i, end) +X word = str[i:j] +X if word in terminators: +X i = j +X break +X if word <> '\n': list.append(i, j) +X i = SkipSpaces(str, j, end) +X return list, i X X X# Find the next word of a command. @@ -583,26 +583,26 @@ X X_word_prog = regexp.compile('([^ \t\n;[\\]+|\\\\C?M?(.|\n))*') X Xdef FindNextWord(str, i, end): -X if i >= end: return end -X if str[i] in '{"': -X if str[i] = '{': i = BalanceBraces(str, i, end) -X else: i = BalanceQuotes(str, i, end) -X if i >= end or str[i] in ' \t\n;': return min(i, end) -X raise TclSyntaxError, 'Garbage after } or "' -X begin = i -X while i < end: -X i = _word_prog.exec(str, i)[0][1] -X if i >= end: -X i = end -X break -X c = str[i] -X if c in ' \t': break -X if c in ';\n': -X if i = begin: i = i+1 -X break -X if c = '[': i = BalanceBrackets(str, i, end) -X else: raise TclAssertError, 'word error' -X return i +X if i >= end: return end +X if str[i] in '{"': +X if str[i] = '{': i = BalanceBraces(str, i, end) +X else: i = BalanceQuotes(str, i, end) +X if i >= end or str[i] in ' \t\n;': return min(i, end) +X raise TclSyntaxError, 'Garbage after } or "' +X begin = i +X while i < end: +X i = _word_prog.exec(str, i)[0][1] +X if i >= end: +X i = end +X break +X c = str[i] +X if c in ' \t': break +X if c in ';\n': +X if i = begin: i = i+1 +X break +X if c = '[': i = BalanceBrackets(str, i, end) +X else: raise TclAssertError, 'word error' +X return i X X X# Parse balanced brackets from str[i:end]. @@ -613,22 +613,22 @@ X X_brackets_prog = regexp.compile('([^][{\\]+|\n|\\\\C?M?(.|\n))*') X Xdef BalanceBrackets(str, i, end): -X if i >= end or str[i] <> '[': -X raise TclAssertError, 'BalanceBrackets' -X nesting = 0 -X while i < end: -X i = _brackets_prog.exec(str, i)[0][1] -X if i >= end: break -X c = str[i] -X if c = '{': i = BalanceBraces(str, i, end) -X else: -X i = i+1 -X if c = '[': nesting = nesting + 1 -X elif c = ']': -X nesting = nesting - 1 -X if nesting = 0: return i -X else: raise TclAssertError, 'brackets error' -X raise TclMatchingError, 'Unmatched bracket ([)' +X if i >= end or str[i] <> '[': +X raise TclAssertError, 'BalanceBrackets' +X nesting = 0 +X while i < end: +X i = _brackets_prog.exec(str, i)[0][1] +X if i >= end: break +X c = str[i] +X if c = '{': i = BalanceBraces(str, i, end) +X else: +X i = i+1 +X if c = '[': nesting = nesting + 1 +X elif c = ']': +X nesting = nesting - 1 +X if nesting = 0: return i +X else: raise TclAssertError, 'brackets error' +X raise TclMatchingError, 'Unmatched bracket ([)' X X X# Parse balanced braces from str[i:end]. @@ -639,20 +639,20 @@ X X_braces_prog = regexp.compile('([^{}\\]+|\n|\\\\C?M?(.|\n))*') X Xdef BalanceBraces(str, i, end): -X if i >= end or str[i] <> '{': -X raise TclAssertError, 'BalanceBraces' -X nesting = 0 -X while i < end: -X i = _braces_prog.exec(str, i)[0][1] -X if i >= end: break -X c = str[i] -X i = i+1 -X if c = '{': nesting = nesting + 1 -X elif c = '}': -X nesting = nesting - 1 -X if nesting = 0: return i -X else: raise TclAssertError, 'braces error' -X raise TclMatchingError, 'Unmatched brace ({)' +X if i >= end or str[i] <> '{': +X raise TclAssertError, 'BalanceBraces' +X nesting = 0 +X while i < end: +X i = _braces_prog.exec(str, i)[0][1] +X if i >= end: break +X c = str[i] +X i = i+1 +X if c = '{': nesting = nesting + 1 +X elif c = '}': +X nesting = nesting - 1 +X if nesting = 0: return i +X else: raise TclAssertError, 'braces error' +X raise TclMatchingError, 'Unmatched brace ({)' X X X# Parse double quotes from str[i:end]. @@ -662,11 +662,11 @@ X X_quotes_prog = regexp.compile('([^"\\]+|\n|\\\\C?M?(.|\n))*') X Xdef BalanceQuotes(str, i, end): -X if i >= end or str[i] <> '"': -X raise TclAssertError, 'BalanceQuotes' -X i = _quotes_prog.exec(str, i+1)[0][1] -X if i < end and str[i] = '"': return i+1 -X raise TclMatchingError, 'Unmatched quote (")' +X if i >= end or str[i] <> '"': +X raise TclAssertError, 'BalanceQuotes' +X i = _quotes_prog.exec(str, i+1)[0][1] +X if i < end and str[i] = '"': return i+1 +X raise TclMatchingError, 'Unmatched quote (")' X X X# Static data used by Backslash() @@ -688,44 +688,44 @@ X# Unrecognized or incomplete backslash sequences are not errors; X# this takes only the backslash itself off the string. X Xdef Backslash(str, i, end): -X if i >= end or str[i] <> '\\': -X raise TclAssertError, 'Backslash' -X i = i+1 -X if i = end: return '\\', i -X c = str[i] -X i = i+1 -X if _bstab.has_key(c): return _bstab[c], i -X if c = 'C': -X if i = end: return '\\', i-1 -X c = str[i] -X i = i+1 -X if c = 'M': -X if i = end: return '\\', i-2 -X c = str[i] -X i = i+1 -X x = ord(c) % 040 + 0200 -X else: -X x = ord(c) % 040 -X return chr(x), i -X elif c = 'M': -X if i = end: return '\\', i-1 -X c = str[i] -X i = i+1 -X x = ord(c) -X if x < 0200: x = x + 0200 -X return chr(x), i -X elif c and c in '0123456789': -X x = ord(c) - ord('0') -X end = min(end, i+2) -X while i < end: -X c = str[i] -X if c not in '0123456789': break -X i = i+1 -X x = x*8 + ord(c) - ord('0') -X return ord(x), i -X else: -X # Not something that we recognize -X return '\\', i-1 +X if i >= end or str[i] <> '\\': +X raise TclAssertError, 'Backslash' +X i = i+1 +X if i = end: return '\\', i +X c = str[i] +X i = i+1 +X if _bstab.has_key(c): return _bstab[c], i +X if c = 'C': +X if i = end: return '\\', i-1 +X c = str[i] +X i = i+1 +X if c = 'M': +X if i = end: return '\\', i-2 +X c = str[i] +X i = i+1 +X x = ord(c) % 040 + 0200 +X else: +X x = ord(c) % 040 +X return chr(x), i +X elif c = 'M': +X if i = end: return '\\', i-1 +X c = str[i] +X i = i+1 +X x = ord(c) +X if x < 0200: x = x + 0200 +X return chr(x), i +X elif c and c in '0123456789': +X x = ord(c) - ord('0') +X end = min(end, i+2) +X while i < end: +X c = str[i] +X if c not in '0123456789': break +X i = i+1 +X x = x*8 + ord(c) - ord('0') +X return ord(x), i +X else: +X # Not something that we recognize +X return '\\', i-1 X X X# Skip over spaces and tabs (but not newlines). @@ -733,64 +733,64 @@ X X_spaces_prog = regexp.compile('[ \t]*') X Xdef SkipSpaces(str, i, end): -X i = _spaces_prog.exec(str, i)[0][1] -X return min(i, end) +X i = _spaces_prog.exec(str, i)[0][1] +X return min(i, end) X X X# Concatenate the elements of a list with intervening spaces. X Xdef Concat(argv): -X result = '' -X sep = '' -X for arg in argv: -X result = result + (sep + arg) -X sep = ' ' -X return result +X result = '' +X sep = '' +X for arg in argv: +X result = result + (sep + arg) +X sep = ' ' +X return result X X X# Concatenate list elements, adding braces etc. to make them parseable X# again with SplitList. X Xdef BuildList(argv): -X result = '' -X sep = '' -X for arg in argv: -X arg = AddBraces(arg) -X result = result + (sep + arg) -X sep = ' ' -X return result +X result = '' +X sep = '' +X for arg in argv: +X arg = AddBraces(arg) +X result = result + (sep + arg) +X sep = ' ' +X return result X X X# Add braces around a string if necessary to make it parseable by SplitList. X Xdef AddBraces(str): -X # Special case for empty string -X if str = '': return '{}' -X # See if it contains balanced braces -X res = '{' + str + '}' -X if TryNextElement(res): -X # See if it would survive unquoted -X # XXX should escape [] and $ as well??? -X if TryNextElement(str) and Collapse(str) = str: return str -X # No -- return with added braces -X return res -X # Unbalanced braces. Add backslashes before suspect characters -X res = '' -X for c in str: -X if c in '$\\[]{} ;': c = '\\' + c -X elif c = '\n': c = '\\n' -X elif c = '\t': c = '\\t' -X res = res + c -X return res +X # Special case for empty string +X if str = '': return '{}' +X # See if it contains balanced braces +X res = '{' + str + '}' +X if TryNextElement(res): +X # See if it would survive unquoted +X # XXX should escape [] and $ as well??? +X if TryNextElement(str) and Collapse(str) = str: return str +X # No -- return with added braces +X return res +X # Unbalanced braces. Add backslashes before suspect characters +X res = '' +X for c in str: +X if c in '$\\[]{} ;': c = '\\' + c +X elif c = '\n': c = '\\n' +X elif c = '\t': c = '\\t' +X res = res + c +X return res X X Xdef TryNextElement(str): -X end = len(str) -X try: -X i = FindNextElement(str, 0, end) -X return i = end -X except (TclSyntaxError, TclMatchingError): -X return 0 +X end = len(str) +X try: +X i = FindNextElement(str, 0, end) +X return i = end +X except (TclSyntaxError, TclMatchingError): +X return 0 EOF fi if test -s 'lib/testall.py' @@ -801,20 +801,20 @@ sed 's/^X//' > 'lib/testall.py' << 'EOF' X# Module 'testall' X# X# Python test set, should exercise: -X# - all lexical and grammatical constructs -X# - all opcodes from "opcode.h" -X# - all operations on all object types -X# - all builtin functions +X# - all lexical and grammatical constructs +X# - all opcodes from "opcode.h" +X# - all operations on all object types +X# - all builtin functions X# Ideally also: -X# - all possible exception situations (Thank God we've got 'try') -X# - all boundary cases +X# - all possible exception situations (Thank God we've got 'try') +X# - all boundary cases X X -XTestFailed = 'testall -- test failed' # Exception +XTestFailed = 'testall -- test failed' # Exception X X X######################################################### -X# Part 1. Test all lexical and grammatical constructs. +X# Part 1. Test all lexical and grammatical constructs. X# This just tests whether the parser accepts them all. X######################################################### X @@ -867,7 +867,7 @@ Xdef f3(two, arguments): pass Xdef f4(two, (compound, (arguments))): pass X X### stmt: simple_stmt | compound_stmt -X### simple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt +X### simple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt X# Tested below X Xprint 'expr_stmt' # (exprlist '=')* exprlist NEWLINE @@ -972,16 +972,16 @@ X Xprint 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT Xif 1: pass Xif 1: -X pass +X pass Xif 1: -X # -X # -X # -X pass -X pass -X # -X pass -X # +X # +X # +X # +X pass +X pass +X # +X pass +X # X Xprint 'test' # and_test ('or' and_test)* X### and_test: not_test ('and' not_test)* @@ -1053,13 +1053,13 @@ Xclass C1() = B(): pass Xclass C2() = B(): pass Xclass D() = C1(), C2(), B(): pass Xclass C(): -X def meth1(self): pass -X def meth2(self, arg): pass -X def meth3(self, (a1, a2)): pass +X def meth1(self): pass +X def meth2(self, arg): pass +X def meth3(self, (a1, a2)): pass X X X######################################################### -X# Part 2. Test all opcodes from "opcode.h" +X# Part 2. Test all opcodes from "opcode.h" X######################################################### X Xprint '2. Opcodes' @@ -1068,23 +1068,23 @@ X Xprint '2.1 try inside for loop' Xn = 0 Xfor i in range(10): -X n = n+i -X try: 1/0 -X except NameError: pass -X except RuntimeError: pass -X except TypeError: pass -X finally: pass -X try: pass -X except: pass -X try: pass -X finally: pass -X n = n+i +X n = n+i +X try: 1/0 +X except NameError: pass +X except RuntimeError: pass +X except TypeError: pass +X finally: pass +X try: pass +X except: pass +X try: pass +X finally: pass +X n = n+i Xif n <> 90: -X raise TestFailed, 'try inside for' +X raise TestFailed, 'try inside for' X X X######################################################### -X# Part 3. Test all operations on all object types +X# Part 3. Test all operations on all object types X######################################################### X Xprint '3. Object types' @@ -1092,7 +1092,7 @@ Xprint 'XXX Not yet implemented' X X X######################################################### -X# Part 4. Test all built-in functions +X# Part 4. Test all built-in functions X######################################################### X Xprint '4. Built-in functions' @@ -1164,7 +1164,7 @@ Xfp.close() Xdel fp Xfp = open('@test', 'r') Xif fp.readline() <> 'The quick brown fox jumps over the lazy dog.\n': -X raise TestFailed, 'readline()' +X raise TestFailed, 'readline()' Xif fp.readline(4) <> 'Dear': raise TestFailed, 'readline(4) # short' Xif fp.readline(100) <> ' John\n': raise TestFailed, 'readline(100)' Xif fp.read(300) <> 'XXX'*100: raise TestFailed, 'read(300)' @@ -1183,13 +1183,13 @@ X Xprint 'raw_input' Xsavestdin = sys.stdin Xtry: -X sys.stdin = open('@test', 'r') -X if raw_input() <> 'The quick brown fox jumps over the lazy dog.': -X raise TestFailed, 'raw_input()' -X if raw_input('testing\n') <> 'Dear John': -X raise TestFailed, 'raw_input(\'testing\\n\')' +X sys.stdin = open('@test', 'r') +X if raw_input() <> 'The quick brown fox jumps over the lazy dog.': +X raise TestFailed, 'raw_input()' +X if raw_input('testing\n') <> 'Dear John': +X raise TestFailed, 'raw_input(\'testing\\n\')' Xfinally: -X sys.stdin = savestdin +X sys.stdin = savestdin X Xprint 'reload' Ximport string @@ -1197,20 +1197,20 @@ Xreload(string) X Xprint 'type' Xif type('') <> type('123') or type('') = type(()): -X raise TestFailed, 'type()' +X raise TestFailed, 'type()' X X Xprint 'Passed all tests.' X Xtry: -X import mac -X unlink = mac.unlink +X import mac +X unlink = mac.unlink Xexcept NameError: -X try: -X import posix -X unlink = posix.unlink -X except NameError: -X pass +X try: +X import posix +X unlink = posix.unlink +X except NameError: +X pass X Xunlink('@test') Xprint 'Unlinked @test' @@ -1225,12 +1225,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1251,494 +1251,494 @@ X#include "allobjects.h" X Xobject * Xnewlistobject(size) -X int size; +X int size; X{ -X int i; -X listobject *op; -X if (size < 0) { -X err_badcall(); -X return NULL; -X } -X op = (listobject *) malloc(sizeof(listobject)); -X if (op == NULL) { -X return err_nomem(); -X } -X if (size <= 0) { -X op->ob_item = NULL; -X } -X else { -X op->ob_item = (object **) malloc(size * sizeof(object *)); -X if (op->ob_item == NULL) { -X free((ANY *)op); -X return err_nomem(); -X } -X } -X NEWREF(op); -X op->ob_type = &Listtype; -X op->ob_size = size; -X for (i = 0; i < size; i++) -X op->ob_item[i] = NULL; -X return (object *) op; +X int i; +X listobject *op; +X if (size < 0) { +X err_badcall(); +X return NULL; +X } +X op = (listobject *) malloc(sizeof(listobject)); +X if (op == NULL) { +X return err_nomem(); +X } +X if (size <= 0) { +X op->ob_item = NULL; +X } +X else { +X op->ob_item = (object **) malloc(size * sizeof(object *)); +X if (op->ob_item == NULL) { +X free((ANY *)op); +X return err_nomem(); +X } +X } +X NEWREF(op); +X op->ob_type = &Listtype; +X op->ob_size = size; +X for (i = 0; i < size; i++) +X op->ob_item[i] = NULL; +X return (object *) op; X} X Xint Xgetlistsize(op) -X object *op; +X object *op; X{ -X if (!is_listobject(op)) { -X err_badcall(); -X return -1; -X } -X else -X return ((listobject *)op) -> ob_size; +X if (!is_listobject(op)) { +X err_badcall(); +X return -1; +X } +X else +X return ((listobject *)op) -> ob_size; X} X Xobject * Xgetlistitem(op, i) -X object *op; -X int i; +X object *op; +X int i; X{ -X if (!is_listobject(op)) { -X err_badcall(); -X return NULL; -X } -X if (i < 0 || i >= ((listobject *)op) -> ob_size) { -X err_setstr(IndexError, "list index out of range"); -X return NULL; -X } -X return ((listobject *)op) -> ob_item[i]; +X if (!is_listobject(op)) { +X err_badcall(); +X return NULL; +X } +X if (i < 0 || i >= ((listobject *)op) -> ob_size) { +X err_setstr(IndexError, "list index out of range"); +X return NULL; +X } +X return ((listobject *)op) -> ob_item[i]; X} X Xint Xsetlistitem(op, i, newitem) -X register object *op; -X register int i; -X register object *newitem; +X register object *op; +X register int i; +X register object *newitem; X{ -X register object *olditem; -X if (!is_listobject(op)) { -X if (newitem != NULL) -X DECREF(newitem); -X err_badcall(); -X return -1; -X } -X if (i < 0 || i >= ((listobject *)op) -> ob_size) { -X if (newitem != NULL) -X DECREF(newitem); -X err_setstr(IndexError, "list assignment index out of range"); -X return -1; -X } -X olditem = ((listobject *)op) -> ob_item[i]; -X ((listobject *)op) -> ob_item[i] = newitem; -X if (olditem != NULL) -X DECREF(olditem); -X return 0; +X register object *olditem; +X if (!is_listobject(op)) { +X if (newitem != NULL) +X DECREF(newitem); +X err_badcall(); +X return -1; +X } +X if (i < 0 || i >= ((listobject *)op) -> ob_size) { +X if (newitem != NULL) +X DECREF(newitem); +X err_setstr(IndexError, "list assignment index out of range"); +X return -1; +X } +X olditem = ((listobject *)op) -> ob_item[i]; +X ((listobject *)op) -> ob_item[i] = newitem; +X if (olditem != NULL) +X DECREF(olditem); +X return 0; X} X Xstatic int Xins1(self, where, v) -X listobject *self; -X int where; -X object *v; +X listobject *self; +X int where; +X object *v; X{ -X int i; -X object **items; -X if (v == NULL) { -X err_badcall(); -X return -1; -X } -X items = self->ob_item; -X RESIZE(items, object *, self->ob_size+1); -X if (items == NULL) { -X err_nomem(); -X return -1; -X } -X if (where < 0) -X where = 0; -X if (where > self->ob_size) -X where = self->ob_size; -X for (i = self->ob_size; --i >= where; ) -X items[i+1] = items[i]; -X INCREF(v); -X items[where] = v; -X self->ob_item = items; -X self->ob_size++; -X return 0; +X int i; +X object **items; +X if (v == NULL) { +X err_badcall(); +X return -1; +X } +X items = self->ob_item; +X RESIZE(items, object *, self->ob_size+1); +X if (items == NULL) { +X err_nomem(); +X return -1; +X } +X if (where < 0) +X where = 0; +X if (where > self->ob_size) +X where = self->ob_size; +X for (i = self->ob_size; --i >= where; ) +X items[i+1] = items[i]; +X INCREF(v); +X items[where] = v; +X self->ob_item = items; +X self->ob_size++; +X return 0; X} X Xint Xinslistitem(op, where, newitem) -X object *op; -X int where; -X object *newitem; +X object *op; +X int where; +X object *newitem; X{ -X if (!is_listobject(op)) { -X err_badcall(); -X return -1; -X } -X return ins1((listobject *)op, where, newitem); +X if (!is_listobject(op)) { +X err_badcall(); +X return -1; +X } +X return ins1((listobject *)op, where, newitem); X} X Xint Xaddlistitem(op, newitem) -X object *op; -X object *newitem; +X object *op; +X object *newitem; X{ -X if (!is_listobject(op)) { -X err_badcall(); -X return -1; -X } -X return ins1((listobject *)op, -X (int) ((listobject *)op)->ob_size, newitem); +X if (!is_listobject(op)) { +X err_badcall(); +X return -1; +X } +X return ins1((listobject *)op, +X (int) ((listobject *)op)->ob_size, newitem); X} X X/* Methods */ X Xstatic void Xlist_dealloc(op) -X listobject *op; +X listobject *op; X{ -X int i; -X for (i = 0; i < op->ob_size; i++) { -X if (op->ob_item[i] != NULL) -X DECREF(op->ob_item[i]); -X } -X if (op->ob_item != NULL) -X free((ANY *)op->ob_item); -X free((ANY *)op); +X int i; +X for (i = 0; i < op->ob_size; i++) { +X if (op->ob_item[i] != NULL) +X DECREF(op->ob_item[i]); +X } +X if (op->ob_item != NULL) +X free((ANY *)op->ob_item); +X free((ANY *)op); X} X Xstatic void Xlist_print(op, fp, flags) -X listobject *op; -X FILE *fp; -X int flags; +X listobject *op; +X FILE *fp; +X int flags; X{ -X int i; -X fprintf(fp, "["); -X for (i = 0; i < op->ob_size && !StopPrint; i++) { -X if (i > 0) { -X fprintf(fp, ", "); -X } -X printobject(op->ob_item[i], fp, flags); -X } -X fprintf(fp, "]"); +X int i; +X fprintf(fp, "["); +X for (i = 0; i < op->ob_size && !StopPrint; i++) { +X if (i > 0) { +X fprintf(fp, ", "); +X } +X printobject(op->ob_item[i], fp, flags); +X } +X fprintf(fp, "]"); X} X Xobject * Xlist_repr(v) -X listobject *v; +X listobject *v; X{ -X object *s, *t, *comma; -X int i; -X s = newstringobject("["); -X comma = newstringobject(", "); -X for (i = 0; i < v->ob_size && s != NULL; i++) { -X if (i > 0) -X joinstring(&s, comma); -X t = reprobject(v->ob_item[i]); -X joinstring(&s, t); -X DECREF(t); -X } -X DECREF(comma); -X t = newstringobject("]"); -X joinstring(&s, t); -X DECREF(t); -X return s; +X object *s, *t, *comma; +X int i; +X s = newstringobject("["); +X comma = newstringobject(", "); +X for (i = 0; i < v->ob_size && s != NULL; i++) { +X if (i > 0) +X joinstring(&s, comma); +X t = reprobject(v->ob_item[i]); +X joinstring(&s, t); +X DECREF(t); +X } +X DECREF(comma); +X t = newstringobject("]"); +X joinstring(&s, t); +X DECREF(t); +X return s; X} X Xstatic int Xlist_compare(v, w) -X listobject *v, *w; +X listobject *v, *w; X{ -X int len = (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; -X int i; -X for (i = 0; i < len; i++) { -X int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); -X if (cmp != 0) -X return cmp; -X } -X return v->ob_size - w->ob_size; +X int len = (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; +X int i; +X for (i = 0; i < len; i++) { +X int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); +X if (cmp != 0) +X return cmp; +X } +X return v->ob_size - w->ob_size; X} X Xstatic int Xlist_length(a) -X listobject *a; +X listobject *a; X{ -X return a->ob_size; +X return a->ob_size; X} X Xstatic object * Xlist_item(a, i) -X listobject *a; -X int i; +X listobject *a; +X int i; X{ -X if (i < 0 || i >= a->ob_size) { -X err_setstr(IndexError, "list index out of range"); -X return NULL; -X } -X INCREF(a->ob_item[i]); -X return a->ob_item[i]; +X if (i < 0 || i >= a->ob_size) { +X err_setstr(IndexError, "list index out of range"); +X return NULL; +X } +X INCREF(a->ob_item[i]); +X return a->ob_item[i]; X} X Xstatic object * Xlist_slice(a, ilow, ihigh) -X listobject *a; -X int ilow, ihigh; +X listobject *a; +X int ilow, ihigh; X{ -X listobject *np; -X int i; -X if (ilow < 0) -X ilow = 0; -X else if (ilow > a->ob_size) -X ilow = a->ob_size; -X if (ihigh < 0) -X ihigh = 0; -X if (ihigh < ilow) -X ihigh = ilow; -X else if (ihigh > a->ob_size) -X ihigh = a->ob_size; -X np = (listobject *) newlistobject(ihigh - ilow); -X if (np == NULL) -X return NULL; -X for (i = ilow; i < ihigh; i++) { -X object *v = a->ob_item[i]; -X INCREF(v); -X np->ob_item[i - ilow] = v; -X } -X return (object *)np; +X listobject *np; +X int i; +X if (ilow < 0) +X ilow = 0; +X else if (ilow > a->ob_size) +X ilow = a->ob_size; +X if (ihigh < 0) +X ihigh = 0; +X if (ihigh < ilow) +X ihigh = ilow; +X else if (ihigh > a->ob_size) +X ihigh = a->ob_size; +X np = (listobject *) newlistobject(ihigh - ilow); +X if (np == NULL) +X return NULL; +X for (i = ilow; i < ihigh; i++) { +X object *v = a->ob_item[i]; +X INCREF(v); +X np->ob_item[i - ilow] = v; +X } +X return (object *)np; X} X Xstatic object * Xlist_concat(a, bb) -X listobject *a; -X object *bb; +X listobject *a; +X object *bb; X{ -X int size; -X int i; -X listobject *np; -X if (!is_listobject(bb)) { -X err_badarg(); -X return NULL; -X } +X int size; +X int i; +X listobject *np; +X if (!is_listobject(bb)) { +X err_badarg(); +X return NULL; +X } X#define b ((listobject *)bb) -X size = a->ob_size + b->ob_size; -X np = (listobject *) newlistobject(size); -X if (np == NULL) { -X return err_nomem(); -X } -X for (i = 0; i < a->ob_size; i++) { -X object *v = a->ob_item[i]; -X INCREF(v); -X np->ob_item[i] = v; -X } -X for (i = 0; i < b->ob_size; i++) { -X object *v = b->ob_item[i]; -X INCREF(v); -X np->ob_item[i + a->ob_size] = v; -X } -X return (object *)np; +X size = a->ob_size + b->ob_size; +X np = (listobject *) newlistobject(size); +X if (np == NULL) { +X return err_nomem(); +X } +X for (i = 0; i < a->ob_size; i++) { +X object *v = a->ob_item[i]; +X INCREF(v); +X np->ob_item[i] = v; +X } +X for (i = 0; i < b->ob_size; i++) { +X object *v = b->ob_item[i]; +X INCREF(v); +X np->ob_item[i + a->ob_size] = v; +X } +X return (object *)np; X#undef b X} X Xstatic int Xlist_ass_item(a, i, v) -X listobject *a; -X int i; -X object *v; +X listobject *a; +X int i; +X object *v; X{ -X if (i < 0 || i >= a->ob_size) { -X err_setstr(IndexError, "list assignment index out of range"); -X return -1; -X } -X if (v == NULL) -X return list_ass_slice(a, i, i+1, v); -X INCREF(v); -X DECREF(a->ob_item[i]); -X a->ob_item[i] = v; -X return 0; +X if (i < 0 || i >= a->ob_size) { +X err_setstr(IndexError, "list assignment index out of range"); +X return -1; +X } +X if (v == NULL) +X return list_ass_slice(a, i, i+1, v); +X INCREF(v); +X DECREF(a->ob_item[i]); +X a->ob_item[i] = v; +X return 0; X} X Xstatic int Xlist_ass_slice(a, ilow, ihigh, v) -X listobject *a; -X int ilow, ihigh; -X object *v; +X listobject *a; +X int ilow, ihigh; +X object *v; X{ -X object **item; -X int n; /* Size of replacement list */ -X int d; /* Change in size */ -X int k; /* Loop index */ +X object **item; +X int n; /* Size of replacement list */ +X int d; /* Change in size */ +X int k; /* Loop index */ X#define b ((listobject *)v) -X if (v == NULL) -X n = 0; -X else if (is_listobject(v)) -X n = b->ob_size; -X else { -X err_badarg(); -X return -1; -X } -X if (ilow < 0) -X ilow = 0; -X else if (ilow > a->ob_size) -X ilow = a->ob_size; -X if (ihigh < 0) -X ihigh = 0; -X if (ihigh < ilow) -X ihigh = ilow; -X else if (ihigh > a->ob_size) -X ihigh = a->ob_size; -X item = a->ob_item; -X d = n - (ihigh-ilow); -X if (d <= 0) { /* Delete -d items; DECREF ihigh-ilow items */ -X for (k = ilow; k < ihigh; k++) -X DECREF(item[k]); -X if (d < 0) { -X for (/*k = ihigh*/; k < a->ob_size; k++) -X item[k+d] = item[k]; -X a->ob_size += d; -X RESIZE(item, object *, a->ob_size); /* Can't fail */ -X a->ob_item = item; -X } -X } -X else { /* Insert d items; DECREF ihigh-ilow items */ -X RESIZE(item, object *, a->ob_size + d); -X if (item == NULL) { -X err_nomem(); -X return -1; -X } -X for (k = a->ob_size; --k >= ihigh; ) -X item[k+d] = item[k]; -X for (/*k = ihigh-1*/; k >= ilow; --k) -X DECREF(item[k]); -X a->ob_item = item; -X a->ob_size += d; -X } -X for (k = 0; k < n; k++, ilow++) { -X object *w = b->ob_item[k]; -X INCREF(w); -X item[ilow] = w; -X } -X return 0; +X if (v == NULL) +X n = 0; +X else if (is_listobject(v)) +X n = b->ob_size; +X else { +X err_badarg(); +X return -1; +X } +X if (ilow < 0) +X ilow = 0; +X else if (ilow > a->ob_size) +X ilow = a->ob_size; +X if (ihigh < 0) +X ihigh = 0; +X if (ihigh < ilow) +X ihigh = ilow; +X else if (ihigh > a->ob_size) +X ihigh = a->ob_size; +X item = a->ob_item; +X d = n - (ihigh-ilow); +X if (d <= 0) { /* Delete -d items; DECREF ihigh-ilow items */ +X for (k = ilow; k < ihigh; k++) +X DECREF(item[k]); +X if (d < 0) { +X for (/*k = ihigh*/; k < a->ob_size; k++) +X item[k+d] = item[k]; +X a->ob_size += d; +X RESIZE(item, object *, a->ob_size); /* Can't fail */ +X a->ob_item = item; +X } +X } +X else { /* Insert d items; DECREF ihigh-ilow items */ +X RESIZE(item, object *, a->ob_size + d); +X if (item == NULL) { +X err_nomem(); +X return -1; +X } +X for (k = a->ob_size; --k >= ihigh; ) +X item[k+d] = item[k]; +X for (/*k = ihigh-1*/; k >= ilow; --k) +X DECREF(item[k]); +X a->ob_item = item; +X a->ob_size += d; +X } +X for (k = 0; k < n; k++, ilow++) { +X object *w = b->ob_item[k]; +X INCREF(w); +X item[ilow] = w; +X } +X return 0; X#undef b X} X Xstatic object * Xins(self, where, v) -X listobject *self; -X int where; -X object *v; +X listobject *self; +X int where; +X object *v; X{ -X if (ins1(self, where, v) != 0) -X return NULL; -X INCREF(None); -X return None; +X if (ins1(self, where, v) != 0) +X return NULL; +X INCREF(None); +X return None; X} X Xstatic object * Xlistinsert(self, args) -X listobject *self; -X object *args; +X listobject *self; +X object *args; X{ -X int i; -X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { -X err_badarg(); -X return NULL; -X } -X if (!getintarg(gettupleitem(args, 0), &i)) -X return NULL; -X return ins(self, i, gettupleitem(args, 1)); +X int i; +X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { +X err_badarg(); +X return NULL; +X } +X if (!getintarg(gettupleitem(args, 0), &i)) +X return NULL; +X return ins(self, i, gettupleitem(args, 1)); X} X Xstatic object * Xlistappend(self, args) -X listobject *self; -X object *args; +X listobject *self; +X object *args; X{ -X return ins(self, (int) self->ob_size, args); +X return ins(self, (int) self->ob_size, args); X} X Xstatic int Xcmp(v, w) -X char *v, *w; +X char *v, *w; X{ -X return cmpobject(* (object **) v, * (object **) w); +X return cmpobject(* (object **) v, * (object **) w); X} X Xstatic object * Xlistsort(self, args) -X listobject *self; -X object *args; +X listobject *self; +X object *args; X{ -X if (args != NULL) { -X err_badarg(); -X return NULL; -X } -X err_clear(); -X if (self->ob_size > 1) -X qsort((char *)self->ob_item, -X (int) self->ob_size, sizeof(object *), cmp); -X if (err_occurred()) -X return NULL; -X INCREF(None); -X return None; +X if (args != NULL) { +X err_badarg(); +X return NULL; +X } +X err_clear(); +X if (self->ob_size > 1) +X qsort((char *)self->ob_item, +X (int) self->ob_size, sizeof(object *), cmp); +X if (err_occurred()) +X return NULL; +X INCREF(None); +X return None; X} X Xint Xsortlist(v) -X object *v; +X object *v; X{ -X if (v == NULL || !is_listobject(v)) { -X err_badcall(); -X return -1; -X } -X v = listsort((listobject *)v, (object *)NULL); -X if (v == NULL) -X return -1; -X DECREF(v); -X return 0; +X if (v == NULL || !is_listobject(v)) { +X err_badcall(); +X return -1; +X } +X v = listsort((listobject *)v, (object *)NULL); +X if (v == NULL) +X return -1; +X DECREF(v); +X return 0; X} X Xstatic struct methodlist list_methods[] = { -X {"append", listappend}, -X {"insert", listinsert}, -X {"sort", listsort}, -X {NULL, NULL} /* sentinel */ +X {"append", listappend}, +X {"insert", listinsert}, +X {"sort", listsort}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xlist_getattr(f, name) -X listobject *f; -X char *name; +X listobject *f; +X char *name; X{ -X return findmethod(list_methods, (object *)f, name); +X return findmethod(list_methods, (object *)f, name); X} X Xstatic sequence_methods list_as_sequence = { -X list_length, /*sq_length*/ -X list_concat, /*sq_concat*/ -X 0, /*sq_repeat*/ -X list_item, /*sq_item*/ -X list_slice, /*sq_slice*/ -X list_ass_item, /*sq_ass_item*/ -X list_ass_slice, /*sq_ass_slice*/ +X list_length, /*sq_length*/ +X list_concat, /*sq_concat*/ +X 0, /*sq_repeat*/ +X list_item, /*sq_item*/ +X list_slice, /*sq_slice*/ +X list_ass_item, /*sq_ass_item*/ +X list_ass_slice, /*sq_ass_slice*/ X}; X Xtypeobject Listtype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "list", -X sizeof(listobject), -X 0, -X list_dealloc, /*tp_dealloc*/ -X list_print, /*tp_print*/ -X list_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X list_compare, /*tp_compare*/ -X list_repr, /*tp_repr*/ -X 0, /*tp_as_number*/ -X &list_as_sequence, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "list", +X sizeof(listobject), +X 0, +X list_dealloc, /*tp_dealloc*/ +X list_print, /*tp_print*/ +X list_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X list_compare, /*tp_compare*/ +X list_repr, /*tp_repr*/ +X 0, /*tp_as_number*/ +X &list_as_sequence, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; EOF fi @@ -1751,12 +1751,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1800,9 +1800,9 @@ Xstatic void s_reset PROTO((stack *)); X Xstatic void Xs_reset(s) -X stack *s; +X stack *s; X{ -X s->s_top = &s->s_base[MAXSTACK]; +X s->s_top = &s->s_base[MAXSTACK]; X} X X#define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) @@ -1811,20 +1811,20 @@ Xstatic int s_push PROTO((stack *, dfa *, node *)); X Xstatic int Xs_push(s, d, parent) -X register stack *s; -X dfa *d; -X node *parent; +X register stack *s; +X dfa *d; +X node *parent; X{ -X register stackentry *top; -X if (s->s_top == s->s_base) { -X fprintf(stderr, "s_push: parser stack overflow\n"); -X return -1; -X } -X top = --s->s_top; -X top->s_dfa = d; -X top->s_parent = parent; -X top->s_state = 0; -X return 0; +X register stackentry *top; +X if (s->s_top == s->s_base) { +X fprintf(stderr, "s_push: parser stack overflow\n"); +X return -1; +X } +X top = --s->s_top; +X top->s_dfa = d; +X top->s_parent = parent; +X top->s_state = 0; +X return 0; X} X X#ifdef DEBUG @@ -1833,13 +1833,13 @@ Xstatic void s_pop PROTO((stack *)); X Xstatic void Xs_pop(s) -X register stack *s; +X register stack *s; X{ -X if (s_empty(s)) { -X fprintf(stderr, "s_pop: parser stack underflow -- FATAL\n"); -X abort(); -X } -X s->s_top++; +X if (s_empty(s)) { +X fprintf(stderr, "s_pop: parser stack underflow -- FATAL\n"); +X abort(); +X } +X s->s_top++; X} X X#else /* !DEBUG */ @@ -1853,35 +1853,35 @@ X/* PARSER CREATION */ X Xparser_state * Xnewparser(g, start) -X grammar *g; -X int start; +X grammar *g; +X int start; X{ -X parser_state *ps; -X -X if (!g->g_accel) -X addaccelerators(g); -X ps = NEW(parser_state, 1); -X if (ps == NULL) -X return NULL; -X ps->p_grammar = g; -X ps->p_tree = newtree(start); -X if (ps->p_tree == NULL) { -X DEL(ps); -X return NULL; -X } -X s_reset(&ps->p_stack); -X (void) s_push(&ps->p_stack, finddfa(g, start), ps->p_tree); -X return ps; +X parser_state *ps; +X +X if (!g->g_accel) +X addaccelerators(g); +X ps = NEW(parser_state, 1); +X if (ps == NULL) +X return NULL; +X ps->p_grammar = g; +X ps->p_tree = newtree(start); +X if (ps->p_tree == NULL) { +X DEL(ps); +X return NULL; +X } +X s_reset(&ps->p_stack); +X (void) s_push(&ps->p_stack, finddfa(g, start), ps->p_tree); +X return ps; X} X Xvoid Xdelparser(ps) -X parser_state *ps; +X parser_state *ps; X{ -X /* NB If you want to save the parse tree, -X you must set p_tree to NULL before calling delparser! */ -X freetree(ps->p_tree); -X DEL(ps); +X /* NB If you want to save the parse tree, +X you must set p_tree to NULL before calling delparser! */ +X freetree(ps->p_tree); +X DEL(ps); X} X X @@ -1891,40 +1891,40 @@ Xstatic int shift PROTO((stack *, int, char *, int, int)); X Xstatic int Xshift(s, type, str, newstate, lineno) -X register stack *s; -X int type; -X char *str; -X int newstate; -X int lineno; +X register stack *s; +X int type; +X char *str; +X int newstate; +X int lineno; X{ -X assert(!s_empty(s)); -X if (addchild(s->s_top->s_parent, type, str, lineno) == NULL) { -X fprintf(stderr, "shift: no mem in addchild\n"); -X return -1; -X } -X s->s_top->s_state = newstate; -X return 0; +X assert(!s_empty(s)); +X if (addchild(s->s_top->s_parent, type, str, lineno) == NULL) { +X fprintf(stderr, "shift: no mem in addchild\n"); +X return -1; +X } +X s->s_top->s_state = newstate; +X return 0; X} X Xstatic int push PROTO((stack *, int, dfa *, int, int)); X Xstatic int Xpush(s, type, d, newstate, lineno) -X register stack *s; -X int type; -X dfa *d; -X int newstate; -X int lineno; +X register stack *s; +X int type; +X dfa *d; +X int newstate; +X int lineno; X{ -X register node *n; -X n = s->s_top->s_parent; -X assert(!s_empty(s)); -X if (addchild(n, type, (char *)NULL, lineno) == NULL) { -X fprintf(stderr, "push: no mem in addchild\n"); -X return -1; -X } -X s->s_top->s_state = newstate; -X return s_push(s, d, CHILD(n, NCH(n)-1)); +X register node *n; +X n = s->s_top->s_parent; +X assert(!s_empty(s)); +X if (addchild(n, type, (char *)NULL, lineno) == NULL) { +X fprintf(stderr, "push: no mem in addchild\n"); +X return -1; +X } +X s->s_top->s_state = newstate; +X return s_push(s, d, CHILD(n, NCH(n)-1)); X} X X @@ -1934,122 +1934,122 @@ Xstatic int classify PROTO((grammar *, int, char *)); X Xstatic int Xclassify(g, type, str) -X grammar *g; -X register int type; -X char *str; +X grammar *g; +X register int type; +X char *str; X{ -X register int n = g->g_ll.ll_nlabels; -X -X if (type == NAME) { -X register char *s = str; -X register label *l = g->g_ll.ll_label; -X register int i; -X for (i = n; i > 0; i--, l++) { -X if (l->lb_type == NAME && l->lb_str != NULL && -X l->lb_str[0] == s[0] && -X strcmp(l->lb_str, s) == 0) { -X D(printf("It's a keyword\n")); -X return n - i; -X } -X } -X } -X -X { -X register label *l = g->g_ll.ll_label; -X register int i; -X for (i = n; i > 0; i--, l++) { -X if (l->lb_type == type && l->lb_str == NULL) { -X D(printf("It's a token we know\n")); -X return n - i; -X } -X } -X } -X -X D(printf("Illegal token\n")); -X return -1; +X register int n = g->g_ll.ll_nlabels; +X +X if (type == NAME) { +X register char *s = str; +X register label *l = g->g_ll.ll_label; +X register int i; +X for (i = n; i > 0; i--, l++) { +X if (l->lb_type == NAME && l->lb_str != NULL && +X l->lb_str[0] == s[0] && +X strcmp(l->lb_str, s) == 0) { +X D(printf("It's a keyword\n")); +X return n - i; +X } +X } +X } +X +X { +X register label *l = g->g_ll.ll_label; +X register int i; +X for (i = n; i > 0; i--, l++) { +X if (l->lb_type == type && l->lb_str == NULL) { +X D(printf("It's a token we know\n")); +X return n - i; +X } +X } +X } +X +X D(printf("Illegal token\n")); +X return -1; X} X Xint Xaddtoken(ps, type, str, lineno) -X register parser_state *ps; -X register int type; -X char *str; -X int lineno; +X register parser_state *ps; +X register int type; +X char *str; +X int lineno; X{ -X register int ilabel; -X -X D(printf("Token %s/'%s' ... ", tok_name[type], str)); -X -X /* Find out which label this token is */ -X ilabel = classify(ps->p_grammar, type, str); -X if (ilabel < 0) -X return E_SYNTAX; -X -X /* Loop until the token is shifted or an error occurred */ -X for (;;) { -X /* Fetch the current dfa and state */ -X register dfa *d = ps->p_stack.s_top->s_dfa; -X register state *s = &d->d_state[ps->p_stack.s_top->s_state]; -X -X D(printf(" DFA '%s', state %d:", -X d->d_name, ps->p_stack.s_top->s_state)); -X -X /* Check accelerator */ -X if (s->s_lower <= ilabel && ilabel < s->s_upper) { -X register int x = s->s_accel[ilabel - s->s_lower]; -X if (x != -1) { -X if (x & (1<<7)) { -X /* Push non-terminal */ -X int nt = (x >> 8) + NT_OFFSET; -X int arrow = x & ((1<<7)-1); -X dfa *d1 = finddfa(ps->p_grammar, nt); -X if (push(&ps->p_stack, nt, d1, -X arrow, lineno) < 0) { -X D(printf(" MemError: push.\n")); -X return E_NOMEM; -X } -X D(printf(" Push ...\n")); -X continue; -X } -X -X /* Shift the token */ -X if (shift(&ps->p_stack, type, str, -X x, lineno) < 0) { -X D(printf(" MemError: shift.\n")); -X return E_NOMEM; -X } -X D(printf(" Shift.\n")); -X /* Pop while we are in an accept-only state */ -X while (s = &d->d_state -X [ps->p_stack.s_top->s_state], -X s->s_accept && s->s_narcs == 1) { -X D(printf(" Direct pop.\n")); -X s_pop(&ps->p_stack); -X if (s_empty(&ps->p_stack)) { -X D(printf(" ACCEPT.\n")); -X return E_DONE; -X } -X d = ps->p_stack.s_top->s_dfa; -X } -X return E_OK; -X } -X } -X -X if (s->s_accept) { -X /* Pop this dfa and try again */ -X s_pop(&ps->p_stack); -X D(printf(" Pop ...\n")); -X if (s_empty(&ps->p_stack)) { -X D(printf(" Error: bottom of stack.\n")); -X return E_SYNTAX; -X } -X continue; -X } -X -X /* Stuck, report syntax error */ -X D(printf(" Error.\n")); -X return E_SYNTAX; -X } +X register int ilabel; +X +X D(printf("Token %s/'%s' ... ", tok_name[type], str)); +X +X /* Find out which label this token is */ +X ilabel = classify(ps->p_grammar, type, str); +X if (ilabel < 0) +X return E_SYNTAX; +X +X /* Loop until the token is shifted or an error occurred */ +X for (;;) { +X /* Fetch the current dfa and state */ +X register dfa *d = ps->p_stack.s_top->s_dfa; +X register state *s = &d->d_state[ps->p_stack.s_top->s_state]; +X +X D(printf(" DFA '%s', state %d:", +X d->d_name, ps->p_stack.s_top->s_state)); +X +X /* Check accelerator */ +X if (s->s_lower <= ilabel && ilabel < s->s_upper) { +X register int x = s->s_accel[ilabel - s->s_lower]; +X if (x != -1) { +X if (x & (1<<7)) { +X /* Push non-terminal */ +X int nt = (x >> 8) + NT_OFFSET; +X int arrow = x & ((1<<7)-1); +X dfa *d1 = finddfa(ps->p_grammar, nt); +X if (push(&ps->p_stack, nt, d1, +X arrow, lineno) < 0) { +X D(printf(" MemError: push.\n")); +X return E_NOMEM; +X } +X D(printf(" Push ...\n")); +X continue; +X } +X +X /* Shift the token */ +X if (shift(&ps->p_stack, type, str, +X x, lineno) < 0) { +X D(printf(" MemError: shift.\n")); +X return E_NOMEM; +X } +X D(printf(" Shift.\n")); +X /* Pop while we are in an accept-only state */ +X while (s = &d->d_state +X [ps->p_stack.s_top->s_state], +X s->s_accept && s->s_narcs == 1) { +X D(printf(" Direct pop.\n")); +X s_pop(&ps->p_stack); +X if (s_empty(&ps->p_stack)) { +X D(printf(" ACCEPT.\n")); +X return E_DONE; +X } +X d = ps->p_stack.s_top->s_dfa; +X } +X return E_OK; +X } +X } +X +X if (s->s_accept) { +X /* Pop this dfa and try again */ +X s_pop(&ps->p_stack); +X D(printf(" Pop ...\n")); +X if (s_empty(&ps->p_stack)) { +X D(printf(" Error: bottom of stack.\n")); +X return E_SYNTAX; +X } +X continue; +X } +X +X /* Stuck, report syntax error */ +X D(printf(" Error.\n")); +X return E_SYNTAX; +X } X} X X @@ -2059,68 +2059,68 @@ X/* DEBUG OUTPUT */ X Xvoid Xdumptree(g, n) -X grammar *g; -X node *n; +X grammar *g; +X node *n; X{ -X int i; -X -X if (n == NULL) -X printf("NIL"); -X else { -X label l; -X l.lb_type = TYPE(n); -X l.lb_str = TYPE(str); -X printf("%s", labelrepr(&l)); -X if (ISNONTERMINAL(TYPE(n))) { -X printf("("); -X for (i = 0; i < NCH(n); i++) { -X if (i > 0) -X printf(","); -X dumptree(g, CHILD(n, i)); -X } -X printf(")"); -X } -X } +X int i; +X +X if (n == NULL) +X printf("NIL"); +X else { +X label l; +X l.lb_type = TYPE(n); +X l.lb_str = TYPE(str); +X printf("%s", labelrepr(&l)); +X if (ISNONTERMINAL(TYPE(n))) { +X printf("("); +X for (i = 0; i < NCH(n); i++) { +X if (i > 0) +X printf(","); +X dumptree(g, CHILD(n, i)); +X } +X printf(")"); +X } +X } X} X Xvoid Xshowtree(g, n) -X grammar *g; -X node *n; +X grammar *g; +X node *n; X{ -X int i; -X -X if (n == NULL) -X return; -X if (ISNONTERMINAL(TYPE(n))) { -X for (i = 0; i < NCH(n); i++) -X showtree(g, CHILD(n, i)); -X } -X else if (ISTERMINAL(TYPE(n))) { -X printf("%s", tok_name[TYPE(n)]); -X if (TYPE(n) == NUMBER || TYPE(n) == NAME) -X printf("(%s)", STR(n)); -X printf(" "); -X } -X else -X printf("? "); +X int i; +X +X if (n == NULL) +X return; +X if (ISNONTERMINAL(TYPE(n))) { +X for (i = 0; i < NCH(n); i++) +X showtree(g, CHILD(n, i)); +X } +X else if (ISTERMINAL(TYPE(n))) { +X printf("%s", tok_name[TYPE(n)]); +X if (TYPE(n) == NUMBER || TYPE(n) == NAME) +X printf("(%s)", STR(n)); +X printf(" "); +X } +X else +X printf("? "); X} X Xvoid Xprinttree(ps) -X parser_state *ps; +X parser_state *ps; X{ -X if (debugging) { -X printf("Parse tree:\n"); -X dumptree(ps->p_grammar, ps->p_tree); -X printf("\n"); -X printf("Tokens:\n"); -X showtree(ps->p_grammar, ps->p_tree); -X printf("\n"); -X } -X printf("Listing:\n"); -X listtree(ps->p_tree); -X printf("\n"); +X if (debugging) { +X printf("Parse tree:\n"); +X dumptree(ps->p_grammar, ps->p_tree); +X printf("\n"); +X printf("Tokens:\n"); +X showtree(ps->p_grammar, ps->p_tree); +X printf("\n"); +X } +X printf("Listing:\n"); +X listtree(ps->p_tree); +X printf("\n"); X} X X#endif /* DEBUG */ @@ -2131,39 +2131,39 @@ XDescription X----------- X XThe parser's interface is different than usual: the function addtoken() -Xmust be called for each token in the input. This makes it possible to -Xturn it into an incremental parsing system later. The parsing system +Xmust be called for each token in the input. This makes it possible to +Xturn it into an incremental parsing system later. The parsing system Xconstructs a parse tree as it goes. X XA parsing rule is represented as a Deterministic Finite-state Automaton -X(DFA). A node in a DFA represents a state of the parser; an arc represents -Xa transition. Transitions are either labeled with terminal symbols or -Xwith non-terminals. When the parser decides to follow an arc labeled +X(DFA). A node in a DFA represents a state of the parser; an arc represents +Xa transition. Transitions are either labeled with terminal symbols or +Xwith non-terminals. When the parser decides to follow an arc labeled Xwith a non-terminal, it is invoked recursively with the DFA representing Xthe parsing rule for that as its initial state; when that DFA accepts, -Xthe parser that invoked it continues. The parse tree constructed by the +Xthe parser that invoked it continues. The parse tree constructed by the Xrecursively called parser is inserted as a child in the current parse tree. X XThe DFA's can be constructed automatically from a more conventional -Xlanguage description. An extended LL(1) grammar (ELL(1)) is suitable. +Xlanguage description. An extended LL(1) grammar (ELL(1)) is suitable. XCertain restrictions make the parser's life easier: rules that can produce Xthe empty string should be outlawed (there are other ways to put loops -Xor optional parts in the language). To avoid the need to construct +Xor optional parts in the language). To avoid the need to construct XFIRST sets, we can require that all but the last alternative of a rule X(really: arc going out of a DFA's state) must begin with a terminal Xsymbol. X XAs an example, consider this grammar: X -Xexpr: term (OP term)* -Xterm: CONSTANT | '(' expr ')' +Xexpr: term (OP term)* +Xterm: CONSTANT | '(' expr ')' X XThe DFA corresponding to the rule for expr is: X X------->.---term-->.-------> -X ^ | -X | | -X \----OP----/ +X ^ | +X | | +X \----OP----/ X XThe parse tree generated for the input a+b is: X @@ -2189,12 +2189,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2241,28 +2241,28 @@ X Xstatic object * Xconvertenviron() X{ -X object *d; -X char **e; -X d = newdictobject(); -X if (d == NULL) -X return NULL; -X if (environ == NULL) -X return d; -X /* XXX This part ignores errors */ -X for (e = environ; *e != NULL; e++) { -X object *v; -X char *p = strchr(*e, '='); -X if (p == NULL) -X continue; -X v = newstringobject(p+1); -X if (v == NULL) -X continue; -X *p = '\0'; -X (void) dictinsert(d, *e, v); -X *p = '='; -X DECREF(v); -X } -X return d; +X object *d; +X char **e; +X d = newdictobject(); +X if (d == NULL) +X return NULL; +X if (environ == NULL) +X return d; +X /* XXX This part ignores errors */ +X for (e = environ; *e != NULL; e++) { +X object *v; +X char *p = strchr(*e, '='); +X if (p == NULL) +X continue; +X v = newstringobject(p+1); +X if (v == NULL) +X continue; +X *p = '\0'; +X (void) dictinsert(d, *e, v); +X *p = '='; +X DECREF(v); +X } +X return d; X} X X @@ -2273,7 +2273,7 @@ X Xstatic object * Xposix_error() X{ -X return err_errno(PosixError); +X return err_errno(PosixError); X} X X @@ -2281,80 +2281,80 @@ X/* POSIX generic methods */ X Xstatic object * Xposix_1str(args, func) -X object *args; -X int (*func) FPROTO((const char *)); +X object *args; +X int (*func) FPROTO((const char *)); X{ -X object *path1; -X if (!getstrarg(args, &path1)) -X return NULL; -X if ((*func)(getstringvalue(path1)) < 0) -X return posix_error(); -X INCREF(None); -X return None; +X object *path1; +X if (!getstrarg(args, &path1)) +X return NULL; +X if ((*func)(getstringvalue(path1)) < 0) +X return posix_error(); +X INCREF(None); +X return None; X} X Xstatic object * Xposix_2str(args, func) -X object *args; -X int (*func) FPROTO((const char *, const char *)); +X object *args; +X int (*func) FPROTO((const char *, const char *)); X{ -X object *path1, *path2; -X if (!getstrstrarg(args, &path1, &path2)) -X return NULL; -X if ((*func)(getstringvalue(path1), getstringvalue(path2)) < 0) -X return posix_error(); -X INCREF(None); -X return None; +X object *path1, *path2; +X if (!getstrstrarg(args, &path1, &path2)) +X return NULL; +X if ((*func)(getstringvalue(path1), getstringvalue(path2)) < 0) +X return posix_error(); +X INCREF(None); +X return None; X} X Xstatic object * Xposix_strint(args, func) -X object *args; -X int (*func) FPROTO((const char *, int)); +X object *args; +X int (*func) FPROTO((const char *, int)); X{ -X object *path1; -X int i; -X if (!getstrintarg(args, &path1, &i)) -X return NULL; -X if ((*func)(getstringvalue(path1), i) < 0) -X return posix_error(); -X INCREF(None); -X return None; +X object *path1; +X int i; +X if (!getstrintarg(args, &path1, &i)) +X return NULL; +X if ((*func)(getstringvalue(path1), i) < 0) +X return posix_error(); +X INCREF(None); +X return None; X} X Xstatic object * Xposix_do_stat(self, args, statfunc) -X object *self; -X object *args; -X int (*statfunc) FPROTO((const char *, struct stat *)); +X object *self; +X object *args; +X int (*statfunc) FPROTO((const char *, struct stat *)); X{ -X struct stat st; -X object *path; -X object *v; -X if (!getstrarg(args, &path)) -X return NULL; -X if ((*statfunc)(getstringvalue(path), &st) != 0) -X return posix_error(); -X v = newtupleobject(10); -X if (v == NULL) -X return NULL; +X struct stat st; +X object *path; +X object *v; +X if (!getstrarg(args, &path)) +X return NULL; +X if ((*statfunc)(getstringvalue(path), &st) != 0) +X return posix_error(); +X v = newtupleobject(10); +X if (v == NULL) +X return NULL; X#define SET(i, st_member) settupleitem(v, i, newintobject((long)st.st_member)) -X SET(0, st_mode); -X SET(1, st_ino); -X SET(2, st_dev); -X SET(3, st_nlink); -X SET(4, st_uid); -X SET(5, st_gid); -X SET(6, st_size); -X SET(7, st_atime); -X SET(8, st_mtime); -X SET(9, st_ctime); +X SET(0, st_mode); +X SET(1, st_ino); +X SET(2, st_dev); +X SET(3, st_nlink); +X SET(4, st_uid); +X SET(5, st_gid); +X SET(6, st_size); +X SET(7, st_atime); +X SET(8, st_mtime); +X SET(9, st_ctime); X#undef SET -X if (err_occurred()) { -X DECREF(v); -X return NULL; -X } -X return v; +X if (err_occurred()) { +X DECREF(v); +X return NULL; +X } +X return v; X} X X @@ -2362,172 +2362,172 @@ X/* POSIX methods */ X Xstatic object * Xposix_chdir(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int chdir PROTO((const char *)); -X return posix_1str(args, chdir); +X extern int chdir PROTO((const char *)); +X return posix_1str(args, chdir); X} X Xstatic object * Xposix_chmod(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int chmod PROTO((const char *, mode_t)); -X return posix_strint(args, chmod); +X extern int chmod PROTO((const char *, mode_t)); +X return posix_strint(args, chmod); X} X Xstatic object * Xposix_getcwd(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X char buf[1026]; -X extern char *getcwd PROTO((char *, int)); -X if (!getnoarg(args)) -X return NULL; -X if (getcwd(buf, sizeof buf) == NULL) -X return posix_error(); -X return newstringobject(buf); +X char buf[1026]; +X extern char *getcwd PROTO((char *, int)); +X if (!getnoarg(args)) +X return NULL; +X if (getcwd(buf, sizeof buf) == NULL) +X return posix_error(); +X return newstringobject(buf); X} X Xstatic object * Xposix_link(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int link PROTO((const char *, const char *)); -X return posix_2str(args, link); +X extern int link PROTO((const char *, const char *)); +X return posix_2str(args, link); X} X Xstatic object * Xposix_listdir(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *name, *d, *v; -X DIR *dirp; -X struct direct *ep; -X if (!getstrarg(args, &name)) -X return NULL; -X if ((dirp = opendir(getstringvalue(name))) == NULL) -X return posix_error(); -X if ((d = newlistobject(0)) == NULL) { -X closedir(dirp); -X return NULL; -X } -X while ((ep = readdir(dirp)) != NULL) { -X v = newstringobject(ep->d_name); -X if (v == NULL) { -X DECREF(d); -X d = NULL; -X break; -X } -X if (addlistitem(d, v) != 0) { -X DECREF(v); -X DECREF(d); -X d = NULL; -X break; -X } -X DECREF(v); -X } -X closedir(dirp); -X return d; +X object *name, *d, *v; +X DIR *dirp; +X struct direct *ep; +X if (!getstrarg(args, &name)) +X return NULL; +X if ((dirp = opendir(getstringvalue(name))) == NULL) +X return posix_error(); +X if ((d = newlistobject(0)) == NULL) { +X closedir(dirp); +X return NULL; +X } +X while ((ep = readdir(dirp)) != NULL) { +X v = newstringobject(ep->d_name); +X if (v == NULL) { +X DECREF(d); +X d = NULL; +X break; +X } +X if (addlistitem(d, v) != 0) { +X DECREF(v); +X DECREF(d); +X d = NULL; +X break; +X } +X DECREF(v); +X } +X closedir(dirp); +X return d; X} X Xstatic object * Xposix_mkdir(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int mkdir PROTO((const char *, mode_t)); -X return posix_strint(args, mkdir); +X extern int mkdir PROTO((const char *, mode_t)); +X return posix_strint(args, mkdir); X} X Xstatic object * Xposix_rename(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int rename PROTO((const char *, const char *)); -X return posix_2str(args, rename); +X extern int rename PROTO((const char *, const char *)); +X return posix_2str(args, rename); X} X Xstatic object * Xposix_rmdir(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int rmdir PROTO((const char *)); -X return posix_1str(args, rmdir); +X extern int rmdir PROTO((const char *)); +X return posix_1str(args, rmdir); X} X Xstatic object * Xposix_stat(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int stat PROTO((const char *, struct stat *)); -X return posix_do_stat(self, args, stat); +X extern int stat PROTO((const char *, struct stat *)); +X return posix_do_stat(self, args, stat); X} X Xstatic object * Xposix_system(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *command; -X int sts; -X if (!getstrarg(args, &command)) -X return NULL; -X sts = system(getstringvalue(command)); -X return newintobject((long)sts); +X object *command; +X int sts; +X if (!getstrarg(args, &command)) +X return NULL; +X sts = system(getstringvalue(command)); +X return newintobject((long)sts); X} X Xstatic object * Xposix_umask(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int i; -X if (!getintarg(args, &i)) -X return NULL; -X i = umask(i); -X if (i < 0) -X return posix_error(); -X return newintobject((long)i); +X int i; +X if (!getintarg(args, &i)) +X return NULL; +X i = umask(i); +X if (i < 0) +X return posix_error(); +X return newintobject((long)i); X} X Xstatic object * Xposix_unlink(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int unlink PROTO((const char *)); -X return posix_1str(args, unlink); +X extern int unlink PROTO((const char *)); +X return posix_1str(args, unlink); X} X Xstatic object * Xposix_utimes(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *path; -X struct timeval tv[2]; -X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { -X err_badarg(); -X return NULL; -X } -X if (!getstrarg(gettupleitem(args, 0), &path) || -X !getlonglongargs(gettupleitem(args, 1), -X &tv[0].tv_sec, &tv[1].tv_sec)) -X return NULL; -X tv[0].tv_usec = tv[1].tv_usec = 0; -X if (utimes(getstringvalue(path), tv) < 0) -X return posix_error(); -X INCREF(None); -X return None; +X object *path; +X struct timeval tv[2]; +X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) { +X err_badarg(); +X return NULL; +X } +X if (!getstrarg(gettupleitem(args, 0), &path) || +X !getlonglongargs(gettupleitem(args, 1), +X &tv[0].tv_sec, &tv[1].tv_sec)) +X return NULL; +X tv[0].tv_usec = tv[1].tv_usec = 0; +X if (utimes(getstringvalue(path), tv) < 0) +X return posix_error(); +X INCREF(None); +X return None; X} X X @@ -2535,84 +2535,84 @@ X#ifndef NO_LSTAT X Xstatic object * Xposix_lstat(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int lstat PROTO((const char *, struct stat *)); -X return posix_do_stat(self, args, lstat); +X extern int lstat PROTO((const char *, struct stat *)); +X return posix_do_stat(self, args, lstat); X} X Xstatic object * Xposix_readlink(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X char buf[1024]; /* XXX Should use MAXPATHLEN */ -X object *path; -X int n; -X if (!getstrarg(args, &path)) -X return NULL; -X n = readlink(getstringvalue(path), buf, sizeof buf); -X if (n < 0) -X return posix_error(); -X return newsizedstringobject(buf, n); +X char buf[1024]; /* XXX Should use MAXPATHLEN */ +X object *path; +X int n; +X if (!getstrarg(args, &path)) +X return NULL; +X n = readlink(getstringvalue(path), buf, sizeof buf); +X if (n < 0) +X return posix_error(); +X return newsizedstringobject(buf, n); X} X Xstatic object * Xposix_symlink(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern int symlink PROTO((const char *, const char *)); -X return posix_2str(args, symlink); +X extern int symlink PROTO((const char *, const char *)); +X return posix_2str(args, symlink); X} X X#endif /* NO_LSTAT */ X X Xstatic struct methodlist posix_methods[] = { -X {"chdir", posix_chdir}, -X {"chmod", posix_chmod}, -X {"getcwd", posix_getcwd}, -X {"link", posix_link}, -X {"listdir", posix_listdir}, -X {"mkdir", posix_mkdir}, -X {"rename", posix_rename}, -X {"rmdir", posix_rmdir}, -X {"stat", posix_stat}, -X {"system", posix_system}, -X {"umask", posix_umask}, -X {"unlink", posix_unlink}, -X {"utimes", posix_utimes}, +X {"chdir", posix_chdir}, +X {"chmod", posix_chmod}, +X {"getcwd", posix_getcwd}, +X {"link", posix_link}, +X {"listdir", posix_listdir}, +X {"mkdir", posix_mkdir}, +X {"rename", posix_rename}, +X {"rmdir", posix_rmdir}, +X {"stat", posix_stat}, +X {"system", posix_system}, +X {"umask", posix_umask}, +X {"unlink", posix_unlink}, +X {"utimes", posix_utimes}, X#ifndef NO_LSTAT -X {"lstat", posix_lstat}, -X {"readlink", posix_readlink}, -X {"symlink", posix_symlink}, +X {"lstat", posix_lstat}, +X {"readlink", posix_readlink}, +X {"symlink", posix_symlink}, X#endif -X {NULL, NULL} /* Sentinel */ +X {NULL, NULL} /* Sentinel */ X}; X X Xvoid Xinitposix() X{ -X object *m, *d, *v; -X -X m = initmodule("posix", posix_methods); -X d = getmoduledict(m); -X -X /* Initialize posix.environ dictionary */ -X v = convertenviron(); -X if (v == NULL || dictinsert(d, "environ", v) != 0) -X fatal("can't define posix.environ"); -X DECREF(v); -X -X /* Initialize posix.error exception */ -X PosixError = newstringobject("posix.error"); -X if (PosixError == NULL || dictinsert(d, "error", PosixError) != 0) -X fatal("can't define posix.error"); +X object *m, *d, *v; +X +X m = initmodule("posix", posix_methods); +X d = getmoduledict(m); +X +X /* Initialize posix.environ dictionary */ +X v = convertenviron(); +X if (v == NULL || dictinsert(d, "environ", v) != 0) +X fatal("can't define posix.environ"); +X DECREF(v); +X +X /* Initialize posix.error exception */ +X PosixError = newstringobject("posix.error"); +X if (PosixError == NULL || dictinsert(d, "error", PosixError) != 0) +X fatal("can't define posix.error"); X} EOF fi echo 'Part 11 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-12-21.shar b/shar/python-0.9.1-12-21.shar index adb9780..5e995d5 100644 --- a/shar/python-0.9.1-12-21.shar +++ b/shar/python-0.9.1-12-21.shar @@ -17,370 +17,370 @@ Ximport DEVICE, time Ximport objectdef, light, panel, material X Xdef fixmatact (p) : -X p.diffR.fixact () -X p.diffG.fixact () -X p.diffB.fixact () -X p.specR.fixact () -X p.specG.fixact () -X p.specB.fixact () -X p.shine.fixact () +X p.diffR.fixact () +X p.diffG.fixact () +X p.diffB.fixact () +X p.specR.fixact () +X p.specG.fixact () +X p.specB.fixact () +X p.shine.fixact () X Xdef fixlichtact (p) : -X p.R.fixact () -X p.G.fixact () -X p.B.fixact () -X p.X.fixact () -X p.Y.fixact () -X p.Z.fixact () -X p.local.fixact () +X p.R.fixact () +X p.G.fixact () +X p.B.fixact () +X p.X.fixact () +X p.Y.fixact () +X p.Z.fixact () +X p.local.fixact () X Xdef cbsetlight (a) : -X p = a.back -X setlight (p, a.label) +X p = a.back +X setlight (p, a.label) X Xdef cbsetmaterial (a) : -X p = a.back -X setmaterial (p, a.label) +X p = a.back +X setmaterial (p, a.label) X Xmater = [0] Xlicht = [0] X Xdef setmaterial (p, mname) : -X # -X mater [0:1] = [material.materdict [mname]] -X # -X p.diffR.val = mater [0][1] -X p.diffG.val = mater [0][2] -X p.diffB.val = mater [0][3] -X # -X p.specR.val = mater [0][5] -X p.specG.val = mater [0][6] -X p.specB.val = mater [0][7] -X # -X p.shine.val = mater [0][9] / 128.0 -X fixmatact (p) +X # +X mater [0:1] = [material.materdict [mname]] +X # +X p.diffR.val = mater [0][1] +X p.diffG.val = mater [0][2] +X p.diffB.val = mater [0][3] +X # +X p.specR.val = mater [0][5] +X p.specG.val = mater [0][6] +X p.specB.val = mater [0][7] +X # +X p.shine.val = mater [0][9] / 128.0 +X fixmatact (p) X Xdef setlight (p, mname) : -X # -X licht [0:1] = [material.lichtdict [mname]] -X # -X p.R.val = licht [0][1] -X p.G.val = licht [0][2] -X p.B.val = licht [0][3] -X # -X p.X.val = (licht [0][5] + 10.0) / 20.0 -X p.Y.val = (licht [0][6] + 10.0) / 20.0 -X p.Z.val = (licht [0][7] + 10.0) / 20.0 -X # -X p.local.val = licht [0][8] -X # -X fixlichtact (p) +X # +X licht [0:1] = [material.lichtdict [mname]] +X # +X p.R.val = licht [0][1] +X p.G.val = licht [0][2] +X p.B.val = licht [0][3] +X # +X p.X.val = (licht [0][5] + 10.0) / 20.0 +X p.Y.val = (licht [0][6] + 10.0) / 20.0 +X p.Z.val = (licht [0][7] + 10.0) / 20.0 +X # +X p.local.val = licht [0][8] +X # +X fixlichtact (p) X Xdef cbmaterial (a) : -X # -X if mater[0] = 0 : return -X # -X p = a.back -X mater [0][5:8] = [p.diffR.val, p.diffG.val, p.diffB.val] -X mater [0][1:4] = [p.specR.val, p.specG.val, p.specB.val] -X mater [0][9:10] = [128.0 * p.shine.val] -X light.bindlight (0) +X # +X if mater[0] = 0 : return +X # +X p = a.back +X mater [0][5:8] = [p.diffR.val, p.diffG.val, p.diffB.val] +X mater [0][1:4] = [p.specR.val, p.specG.val, p.specB.val] +X mater [0][9:10] = [128.0 * p.shine.val] +X light.bindlight (0) X Xdef cblight (a) : -X # -X if licht[0] = 0 : return -X # -X p = a.back -X licht [0][1:4] = [p.R.val, p.G.val, p.B.val] -X 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] -X if p.local.val = 0.0 : -X licht [0][8:9] = [0.0] -X else: -X licht [0][8:9] = [1.0] -X # -X light.bindlight (0) +X # +X if licht[0] = 0 : return +X # +X p = a.back +X licht [0][1:4] = [p.R.val, p.G.val, p.B.val] +X 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] +X if p.local.val = 0.0 : +X licht [0][8:9] = [0.0] +X else: +X licht [0][8:9] = [1.0] +X # +X light.bindlight (0) X X# X# initgl : initialize window, pipeline, light, viewing X# Xdef initgl () : -X # -X # init window -X # -X foreground () -X keepaspect (1, 1) -X prefposition (100, 500, 100, 500) -X w = winopen ('flying objects') -X keepaspect (1, 1) -X winconstraints () -X # -X # configure pipline -X # -X doublebuffer () -X shademodel (GOURAUD) -X zbuffer (1) -X RGBmode () -X gconfig () -X # -X # init lighting -X # -X light.bindlight (1) -X # -X # set viewing -X # -X lookat (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0) -X # +X # +X # init window +X # +X foreground () +X keepaspect (1, 1) +X prefposition (100, 500, 100, 500) +X w = winopen ('flying objects') +X keepaspect (1, 1) +X winconstraints () +X # +X # configure pipline +X # +X doublebuffer () +X shademodel (GOURAUD) +X zbuffer (1) +X RGBmode () +X gconfig () +X # +X # init lighting +X # +X light.bindlight (1) +X # +X # set viewing +X # +X lookat (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0) +X # X X# X# drawit : draws the object with the given attributes. X# X# rfac : the rotation factor. -X# mat : the material identification -X# attr : a list of attributes : +X# mat : the material identification +X# attr : a list of attributes : X# -X# [[rotate vector ], [tranlate vector], [scale vector]] -X# i.e : -X# [[rX, rY, rZ], [tX, tY, tZ], [sX, sY, sZ]] +X# [[rotate vector ], [tranlate vector], [scale vector]] +X# i.e : +X# [[rX, rY, rZ], [tX, tY, tZ], [sX, sY, sZ]] X# Xdef drawit(object, rfac, attr, mat) : -X pushmatrix() -X rot (attr[0][0] * float (rfac), 'X') -X rot (attr[0][1] * float (rfac), 'Y') -X rot (attr[0][2] * float (rfac), 'Z') -X translate(attr[1][0], attr[1][1], attr[1][2]) -X scale(attr[2][0], attr[2][1], attr[2][2]) -X lmbind(MATERIAL, mat) -X objectdef.drawobject(object) -X popmatrix() +X pushmatrix() +X rot (attr[0][0] * float (rfac), 'X') +X rot (attr[0][1] * float (rfac), 'Y') +X rot (attr[0][2] * float (rfac), 'Z') +X translate(attr[1][0], attr[1][1], attr[1][2]) +X scale(attr[2][0], attr[2][1], attr[2][2]) +X lmbind(MATERIAL, mat) +X objectdef.drawobject(object) +X popmatrix() X Xdef callbacksphere (a) : -X putDict (objects, 'sphere', int (a.val)) +X putDict (objects, 'sphere', int (a.val)) X Xdef callbackcylinder (a) : -X putDict (objects, 'cylinder', int (a.val)) +X putDict (objects, 'cylinder', int (a.val)) X Xdef callbackcube (a) : -X putDict (objects, 'cube', int (a.val)) +X putDict (objects, 'cube', int (a.val)) X Xdef callbackicecream (a) : -X putDict (objects, 'icecream', int (a.val)) +X putDict (objects, 'icecream', int (a.val)) X Xdef callbackdisk (a) : -X putDict (objects, 'disk', int (a.val)) +X putDict (objects, 'disk', int (a.val)) X Xdef callbackdiamond (a) : -X putDict (objects, 'diamond', int (a.val)) +X putDict (objects, 'diamond', int (a.val)) X Xdef callbackglass (a) : -X putDict (objects, 'glass', int (a.val)) +X putDict (objects, 'glass', int (a.val)) X Xdef callbackpyramid (a) : -X putDict (objects, 'pyramid', int (a.val)) +X putDict (objects, 'pyramid', int (a.val)) X Xdef callbacktable (a) : -X putDict (objects, 'table', int (a.val)) +X putDict (objects, 'table', int (a.val)) X Xdef callbackflat (a) : -X shademodel(FLAT) +X shademodel(FLAT) X Xdef callbackgouraud (a) : -X shademodel(GOURAUD) +X shademodel(GOURAUD) X Xdef callbackwire (a) : -X objectdef.putFunc ([bgnclosedline, endclosedline]) +X objectdef.putFunc ([bgnclosedline, endclosedline]) X Xdef callbackfilled (a) : -X objectdef.putFunc ([bgnpolygon, endpolygon]) +X objectdef.putFunc ([bgnpolygon, endpolygon]) X Xdef callbackquit (a) : -X import sys -X sys.exit (-1) +X import sys +X sys.exit (-1) X Xdef allObjects(p, val) : -X p.sphere.val = val -X p.sphere.fixact () -X p.cube.val = val -X p.cube.fixact () -X p.cylinder.val = val -X p.cylinder.fixact () -X p.pyramid.val = val -X p.pyramid.fixact () -X p.disk.val = val -X p.disk.fixact () -X p.diamond.val = val -X p.diamond.fixact () -X p.icecream.val = val -X p.icecream.fixact () -X p.table.val = val -X p.table.fixact () -X p.fixpanel() -X +X p.sphere.val = val +X p.sphere.fixact () +X p.cube.val = val +X p.cube.fixact () +X p.cylinder.val = val +X p.cylinder.fixact () +X p.pyramid.val = val +X p.pyramid.fixact () +X p.disk.val = val +X p.disk.fixact () +X p.diamond.val = val +X p.diamond.fixact () +X p.icecream.val = val +X p.icecream.fixact () +X p.table.val = val +X p.table.fixact () +X p.fixpanel() +X X Xdef callbackshowall (a) : -X #print objects -X for key in objects.keys () : -X #print key -X putDict (objects, key, 1) -X allObjects (a.back, 1.0) +X #print objects +X for key in objects.keys () : +X #print key +X putDict (objects, key, 1) +X allObjects (a.back, 1.0) X Xdef callbackshownone (a) : -X for key in objects.keys () : -X putDict (objects, key, 0) -X allObjects (a.back, 0.0) +X for key in objects.keys () : +X putDict (objects, key, 0) +X allObjects (a.back, 0.0) X X# X# main : makeobjects, initialze graphics, and loop continuously. X# Xdef main () : -X # -X # iter keeps track of the iterations. It is used as the -X # (x, y, z) rotation increments to which the objects rotate. -X iter = 0 -X # -X # make the objects. the objects are put in the odict dictionary -X # -X od = objectdef.makeobjects () -X # -X # initialize gl -X # -X initgl () -X # -X # initialize time and iterations per second -X # -X time0 = time.time () # epoch-time of previous second -X fps = 0 # frames per second -X # -X # initialize panels -X # -X panel.needredraw() -X panels = panel.defpanellist('flying.s') #XXX -X p = panels[0] -X p.sphere.upfunc = callbacksphere -X p.cylinder.upfunc = callbackcylinder -X p.cube.upfunc = callbackcube -X p.icecream.upfunc = callbackicecream -X p.disk.upfunc = callbackdisk -X p.diamond.upfunc = callbackdiamond -X # NOT YET IMPLEMENTED p.glass.upfunc = callbackglass -X p.pyramid.upfunc = callbackpyramid -X p.table.upfunc = callbacktable -X p.wire.upfunc = callbackwire -X p.filled.upfunc = callbackfilled -X p.flat.upfunc = callbackflat -X p.gouraud.upfunc = callbackgouraud -X p.quit.upfunc = callbackquit -X p.showall.upfunc = callbackshowall -X p.shownone.upfunc = callbackshownone -X p.showall.back = p -X p.shownone.back = p -X # -X qanels = panel.defpanellist('freeze.s') #XXX -X q = qanels[0] -X # -X ranels = panel.defpanellist('materials.s') #XXX -X r = ranels[0] -X r.m9.upfunc = cbsetmaterial -X r.m8.upfunc = cbsetmaterial -X r.m7.upfunc = cbsetmaterial -X r.m6.upfunc = cbsetmaterial -X r.m5.upfunc = cbsetmaterial -X r.m4.upfunc = cbsetmaterial -X r.m3.upfunc = cbsetmaterial -X r.m2.upfunc = cbsetmaterial -X r.m1.upfunc = cbsetmaterial -X r.specR.activefunc = cbmaterial -X r.specG.activefunc = cbmaterial -X r.specB.activefunc = cbmaterial -X r.diffR.activefunc = cbmaterial -X r.diffG.activefunc = cbmaterial -X r.diffB.activefunc = cbmaterial -X r.shine.activefunc = cbmaterial -X r.m9.back = r -X r.m8.back = r -X r.m7.back = r -X r.m6.back = r -X r.m5.back = r -X r.m4.back = r -X r.m3.back = r -X r.m2.back = r -X r.m1.back = r -X r.diffR.back = r -X r.diffG.back = r -X r.diffB.back = r -X r.specR.back = r -X r.specG.back = r -X r.specB.back = r -X r.shine.back = r -X # -X sanels = panel.defpanellist('light.s') #XXX -X s = sanels[0] -X s.X.back = s -X s.Y.back = s -X s.Z.back = s -X s.R.back = s -X s.G.back = s -X s.B.back = s -X s.light1.back = s -X s.light2.back = s -X s.local.back = s -X s.light1.upfunc = cbsetlight -X s.light2.upfunc = cbsetlight -X s.R.activefunc = cblight -X s.G.activefunc = cblight -X s.B.activefunc = cblight -X s.X.activefunc = cblight -X s.Y.activefunc = cblight -X s.Z.activefunc = cblight -X # -X while 1 : -X # -X act = panel.dopanel() -X # -X wid = panel.userredraw () -X if wid : -X winset (wid) -X reshapeviewport() -X # -X # increment iter -X # -X if int (q.freeze.val) = 0 : -X iter = iter + 1 -X fps = fps + 1 -X if time.time() - time0 >= 1 : -X f = float(fps)/float(time.time()-time0) -X q.mystrip.val = f -X q.mystrip.fixact () -X q.fixpanel() -X time0 = time.time() -X fps = 0 -X # -X # clear the zbuffer and make the background light blue -X # -X zclear() -X c3i (LightBlue) -X clear() -X # -X # for each object in the objects dictionary -X # -X for key in objects.keys() : -X # -X # if the object should be displayed -X # -X if getDict (objects, key, 0) = ONE : -X loo = getDict (objects, key, 1) -X for o in loo : -X # -X # get attributes and materail -X # -X attr = o [1] -X mat = o [2] -X # -X # display the object -X # -X drawit(od[o[0]],iter,attr,mat) -X # -X swapbuffers() -X # +X # +X # iter keeps track of the iterations. It is used as the +X # (x, y, z) rotation increments to which the objects rotate. +X iter = 0 +X # +X # make the objects. the objects are put in the odict dictionary +X # +X od = objectdef.makeobjects () +X # +X # initialize gl +X # +X initgl () +X # +X # initialize time and iterations per second +X # +X time0 = time.time () # epoch-time of previous second +X fps = 0 # frames per second +X # +X # initialize panels +X # +X panel.needredraw() +X panels = panel.defpanellist('flying.s') #XXX +X p = panels[0] +X p.sphere.upfunc = callbacksphere +X p.cylinder.upfunc = callbackcylinder +X p.cube.upfunc = callbackcube +X p.icecream.upfunc = callbackicecream +X p.disk.upfunc = callbackdisk +X p.diamond.upfunc = callbackdiamond +X # NOT YET IMPLEMENTED p.glass.upfunc = callbackglass +X p.pyramid.upfunc = callbackpyramid +X p.table.upfunc = callbacktable +X p.wire.upfunc = callbackwire +X p.filled.upfunc = callbackfilled +X p.flat.upfunc = callbackflat +X p.gouraud.upfunc = callbackgouraud +X p.quit.upfunc = callbackquit +X p.showall.upfunc = callbackshowall +X p.shownone.upfunc = callbackshownone +X p.showall.back = p +X p.shownone.back = p +X # +X qanels = panel.defpanellist('freeze.s') #XXX +X q = qanels[0] +X # +X ranels = panel.defpanellist('materials.s') #XXX +X r = ranels[0] +X r.m9.upfunc = cbsetmaterial +X r.m8.upfunc = cbsetmaterial +X r.m7.upfunc = cbsetmaterial +X r.m6.upfunc = cbsetmaterial +X r.m5.upfunc = cbsetmaterial +X r.m4.upfunc = cbsetmaterial +X r.m3.upfunc = cbsetmaterial +X r.m2.upfunc = cbsetmaterial +X r.m1.upfunc = cbsetmaterial +X r.specR.activefunc = cbmaterial +X r.specG.activefunc = cbmaterial +X r.specB.activefunc = cbmaterial +X r.diffR.activefunc = cbmaterial +X r.diffG.activefunc = cbmaterial +X r.diffB.activefunc = cbmaterial +X r.shine.activefunc = cbmaterial +X r.m9.back = r +X r.m8.back = r +X r.m7.back = r +X r.m6.back = r +X r.m5.back = r +X r.m4.back = r +X r.m3.back = r +X r.m2.back = r +X r.m1.back = r +X r.diffR.back = r +X r.diffG.back = r +X r.diffB.back = r +X r.specR.back = r +X r.specG.back = r +X r.specB.back = r +X r.shine.back = r +X # +X sanels = panel.defpanellist('light.s') #XXX +X s = sanels[0] +X s.X.back = s +X s.Y.back = s +X s.Z.back = s +X s.R.back = s +X s.G.back = s +X s.B.back = s +X s.light1.back = s +X s.light2.back = s +X s.local.back = s +X s.light1.upfunc = cbsetlight +X s.light2.upfunc = cbsetlight +X s.R.activefunc = cblight +X s.G.activefunc = cblight +X s.B.activefunc = cblight +X s.X.activefunc = cblight +X s.Y.activefunc = cblight +X s.Z.activefunc = cblight +X # +X while 1 : +X # +X act = panel.dopanel() +X # +X wid = panel.userredraw () +X if wid : +X winset (wid) +X reshapeviewport() +X # +X # increment iter +X # +X if int (q.freeze.val) = 0 : +X iter = iter + 1 +X fps = fps + 1 +X if time.time() - time0 >= 1 : +X f = float(fps)/float(time.time()-time0) +X q.mystrip.val = f +X q.mystrip.fixact () +X q.fixpanel() +X time0 = time.time() +X fps = 0 +X # +X # clear the zbuffer and make the background light blue +X # +X zclear() +X c3i (LightBlue) +X clear() +X # +X # for each object in the objects dictionary +X # +X for key in objects.keys() : +X # +X # if the object should be displayed +X # +X if getDict (objects, key, 0) = ONE : +X loo = getDict (objects, key, 1) +X for o in loo : +X # +X # get attributes and materail +X # +X attr = o [1] +X mat = o [2] +X # +X # display the object +X # +X drawit(od[o[0]],iter,attr,mat) +X # +X swapbuffers() +X # X Xmain() EOF @@ -406,16 +406,16 @@ X# Copy of string.split() (to avoid loading all of string.py) X Xwhitespace = ' \t\n' Xdef split(s): -X res = [] -X i, n = 0, len(s) -X while i < n: -X while i < n and s[i] in whitespace: i = i+1 -X if i = n: break -X j = i -X while j < n and s[j] not in whitespace: j = j+1 -X res.append(s[i:j]) -X i = j -X return res +X res = [] +X i, n = 0, len(s) +X while i < n: +X while i < n and s[i] in whitespace: i = i+1 +X if i = n: break +X j = i +X while j < n and s[j] not in whitespace: j = j+1 +X res.append(s[i:j]) +X i = j +X return res X X X# Constants to name directions @@ -461,76 +461,76 @@ X X# Normalize a command, in place: truncate words to 6 chars, and expand aliases. X Xdef normalize(cmd): -X for i in range(len(cmd)): -X word = cmd[i][:6] -X if alias.has_key(word): -X word = alias[word] -X cmd[i] = word +X for i in range(len(cmd)): +X word = cmd[i][:6] +X if alias.has_key(word): +X word = alias[word] +X cmd[i] = word X X X# The Object class describes objects that the player can carry around. X Xclass Object(): -X def init(this, name): -X this.name = name -X return this -X def describe(this): -X print 'A', this.name + '.' -X def get(this, (player, room)): -X del room.objects[this.name] -X player.objects[this.name] = this -X def put(this, (player, room)): -X del player.objects[this.name] -X room.objects[this.name] = this +X def init(this, name): +X this.name = name +X return this +X def describe(this): +X print 'A', this.name + '.' +X def get(this, (player, room)): +X del room.objects[this.name] +X player.objects[this.name] = this +X def put(this, (player, room)): +X del player.objects[this.name] +X room.objects[this.name] = this X X X# The Player class embodies first person control. X Xclass Player(): -X # Set initial state, except current room. -X def init(self, initial_room): -X self.blind = 0 -X self.here = initial_room -X self.prev = nil -X self.objects = {} -X return self -X # Read and execute commands forever. -X def play(self): -X self.here.casualdescribe() -X while 1: -X self.move() -X # Read and execute one command. -X def move(self): -X next = self.here.parser() -X if next and next <> self.here: -X self.prev = self.here -X self.here = next -X if not self.blind: -X self.here.casualdescribe() -X # Print inventory. -X def inventory(self): -X if not self.objects: -X print 'You aren\'t carrying anything.' -X return -X print 'You are carrying:' -X for key in self.objects.keys(): -X self.objects[key].describe() -X # Go back to previous room. -X def back(self): -X if self.prev: return self.prev -X print 'You can\'t go back now.' -X # Get an object from the room. -X def get(self, name): -X if self.here.objects.has_key(name): -X self.here.objects[name].get(self, self.here) -X else: -X print 'I see no', name, 'here.' -X # Put an object in the room. -X def put(self, name): -X if self.objects.has_key(name): -X self.objects[name].put(self, self.here) -X else: -X print 'You have no', name, 'with you.' +X # Set initial state, except current room. +X def init(self, initial_room): +X self.blind = 0 +X self.here = initial_room +X self.prev = nil +X self.objects = {} +X return self +X # Read and execute commands forever. +X def play(self): +X self.here.casualdescribe() +X while 1: +X self.move() +X # Read and execute one command. +X def move(self): +X next = self.here.parser() +X if next and next <> self.here: +X self.prev = self.here +X self.here = next +X if not self.blind: +X self.here.casualdescribe() +X # Print inventory. +X def inventory(self): +X if not self.objects: +X print 'You aren\'t carrying anything.' +X return +X print 'You are carrying:' +X for key in self.objects.keys(): +X self.objects[key].describe() +X # Go back to previous room. +X def back(self): +X if self.prev: return self.prev +X print 'You can\'t go back now.' +X # Get an object from the room. +X def get(self, name): +X if self.here.objects.has_key(name): +X self.here.objects[name].get(self, self.here) +X else: +X print 'I see no', name, 'here.' +X # Put an object in the room. +X def put(self, name): +X if self.objects.has_key(name): +X self.objects[name].put(self, self.here) +X else: +X print 'You have no', name, 'with you.' X X X# The Room class describes a generic room. @@ -538,120 +538,120 @@ X# Rooms with special properties are defined by derived classes X# that override certain operations. X Xclass Room(): -X # Initialize a featureless room. -X def init(here, name): -X here.seen = 0 -X here.name = name -X here.exits = {} -X here.objects = {} -X here.description = [] -X return here -X # Add an object to the room. Used during initialization. -X def add(here, obj): -X here.objects[obj.name] = obj -X # Print a casual description. -X def casualdescribe(here): -X if here.seen: -X print here.name + '.' -X here.listobjects() -X return -X here.seen = 1 -X here.describe() -X # Print a full description, including all exits and objects seen. -X def describe(here): -X if not here.description: -X print here.name + '.' -X here.listexits() -X else: -X for line in here.description: print line -X here.listobjects() -X # List exits. -X def listexits(here): -X there = here.exits.keys() -X if there: -X if len(there) = 1: -X print 'There is an exit leading', -X else: -X print 'There are exits leading', -X for name in there[:-2]: -X print name + ',', -X print there[len(there)-2], 'and', -X print there[len(there)-1] + '.' -X # List objects -X def listobjects(here): -X if here.objects: -X print 'I see:' -X for key in here.objects.keys(): -X here.objects[key].describe() -X # Default parser. Returns next room (possibly the same) or nil. -X def parser(here): -X cmd = here.getcmd(here.prompt()) -X return here.decide(cmd) -X # Return default prompt string. -X def prompt(here): return '> ' -X # Default input routine. Returns a non-empty list of words. -X def getcmd(here, prompt): -X # Loop until non-empty command gotten -X # EOFError and KeyboardInterrupt may be caught elsewhere -X while 1: -X line = raw_input(prompt) -X cmd = split(line) -X if cmd: -X normalize(cmd) -X return cmd -X # Default decision routine. Override for room-specific commands. -X def decide(here, cmd): -X key, args = cmd[0], cmd[1:] -X if not args: -X if key = N: return here.north() -X if key = S: return here.south() -X if key = E: return here.east() -X if key = W: return here.west() -X if key = U: return here.up() -X if key = D: return here.down() -X if key = NW: return here.nw() -X if key = NE: return here.ne() -X if key = SW: return here.sw() -X if key = SE: return here.se() -X if key = LOOK: return here.look() -X if key = INVENT: return here.inventory() -X if key = BACK: return here.back() -X if here.objects.has_key(key): -X print 'What do you want to do with the', key+'?' -X else: -X print 'Huh?' -X return -X if key = GET: -X for arg in args: -X player.get(arg) -X return -X if key = PUT: -X for arg in args: -X player.put(arg) -X # Standard commands. -X def look(here): -X here.describe() -X def inventory(here): -X player.inventory() -X def back(here): -X return player.back() -X # Standard exits. -X def north(here): return here.take_exit(N) -X def south(here): return here.take_exit(S) -X def west(here): return here.take_exit(W) -X def east(here): return here.take_exit(E) -X def up(here): return here.take_exit(U) -X def down(here): return here.take_exit(D) -X def nw(here): return here.take_exit(NW) -X def ne(here): return here.take_exit(NE) -X def sw(here): return here.take_exit(SW) -X def se(here): return here.take_exit(SE) -X # Subroutine for standard exits. -X def take_exit(here, key): -X if here.exits.has_key(key): -X return here.exits[key] -X print 'You cannot go in that direction.' -X return here +X # Initialize a featureless room. +X def init(here, name): +X here.seen = 0 +X here.name = name +X here.exits = {} +X here.objects = {} +X here.description = [] +X return here +X # Add an object to the room. Used during initialization. +X def add(here, obj): +X here.objects[obj.name] = obj +X # Print a casual description. +X def casualdescribe(here): +X if here.seen: +X print here.name + '.' +X here.listobjects() +X return +X here.seen = 1 +X here.describe() +X # Print a full description, including all exits and objects seen. +X def describe(here): +X if not here.description: +X print here.name + '.' +X here.listexits() +X else: +X for line in here.description: print line +X here.listobjects() +X # List exits. +X def listexits(here): +X there = here.exits.keys() +X if there: +X if len(there) = 1: +X print 'There is an exit leading', +X else: +X print 'There are exits leading', +X for name in there[:-2]: +X print name + ',', +X print there[len(there)-2], 'and', +X print there[len(there)-1] + '.' +X # List objects +X def listobjects(here): +X if here.objects: +X print 'I see:' +X for key in here.objects.keys(): +X here.objects[key].describe() +X # Default parser. Returns next room (possibly the same) or nil. +X def parser(here): +X cmd = here.getcmd(here.prompt()) +X return here.decide(cmd) +X # Return default prompt string. +X def prompt(here): return '> ' +X # Default input routine. Returns a non-empty list of words. +X def getcmd(here, prompt): +X # Loop until non-empty command gotten +X # EOFError and KeyboardInterrupt may be caught elsewhere +X while 1: +X line = raw_input(prompt) +X cmd = split(line) +X if cmd: +X normalize(cmd) +X return cmd +X # Default decision routine. Override for room-specific commands. +X def decide(here, cmd): +X key, args = cmd[0], cmd[1:] +X if not args: +X if key = N: return here.north() +X if key = S: return here.south() +X if key = E: return here.east() +X if key = W: return here.west() +X if key = U: return here.up() +X if key = D: return here.down() +X if key = NW: return here.nw() +X if key = NE: return here.ne() +X if key = SW: return here.sw() +X if key = SE: return here.se() +X if key = LOOK: return here.look() +X if key = INVENT: return here.inventory() +X if key = BACK: return here.back() +X if here.objects.has_key(key): +X print 'What do you want to do with the', key+'?' +X else: +X print 'Huh?' +X return +X if key = GET: +X for arg in args: +X player.get(arg) +X return +X if key = PUT: +X for arg in args: +X player.put(arg) +X # Standard commands. +X def look(here): +X here.describe() +X def inventory(here): +X player.inventory() +X def back(here): +X return player.back() +X # Standard exits. +X def north(here): return here.take_exit(N) +X def south(here): return here.take_exit(S) +X def west(here): return here.take_exit(W) +X def east(here): return here.take_exit(E) +X def up(here): return here.take_exit(U) +X def down(here): return here.take_exit(D) +X def nw(here): return here.take_exit(NW) +X def ne(here): return here.take_exit(NE) +X def sw(here): return here.take_exit(SW) +X def se(here): return here.take_exit(SE) +X # Subroutine for standard exits. +X def take_exit(here, key): +X if here.exits.has_key(key): +X return here.exits[key] +X print 'You cannot go in that direction.' +X return here X X X# Create the objects we know about. @@ -664,10 +664,10 @@ X X# Subroutine to connect two rooms. X Xdef connect(rm1, rm2, dir1, dir2): -X if dir1: -X rm1.exits[dir1] = rm2 -X if dir2: -X rm2.exits[dir2] = rm1 +X if dir1: +X rm1.exits[dir1] = rm2 +X if dir2: +X rm2.exits[dir2] = rm1 X X X# Create the rooms and connect them together. @@ -676,34 +676,34 @@ X Xr_front = Room().init('Front of building') Xr_initial = r_front Xr_front.description = [ \ -X 'You are standing in front of a large, desolate building.', \ -X 'Huge neon letters spell "CWI". The "I" is blinking.', \ -X 'There are entrances north and west from where you are standing.', \ -X ] +X 'You are standing in front of a large, desolate building.', \ +X 'Huge neon letters spell "CWI". The "I" is blinking.', \ +X 'There are entrances north and west from where you are standing.', \ +X ] X Xr_entrance = Room().init('Entrance') Xr_entrance.description = [ \ -X 'You are standing in a small entrance room.', \ -X 'On the east side is a window to a reception room.', \ -X 'South is a door leading outside the building.', \ -X 'North is a large hall.' \ -X ] +X 'You are standing in a small entrance room.', \ +X 'On the east side is a window to a reception room.', \ +X 'South is a door leading outside the building.', \ +X 'North is a large hall.' \ +X ] X Xr_hall_s = Room().init('South of hall') Xr_hall_s.description = [ \ -X 'You are standing at the south side of a very large hall.', \ -X 'There are doors leading west, southwest, south and southeast,', \ -X 'and a corridor leads east.', \ -X 'The hall continues to the north.' \ -X ] +X 'You are standing at the south side of a very large hall.', \ +X 'There are doors leading west, southwest, south and southeast,', \ +X 'and a corridor leads east.', \ +X 'The hall continues to the north.' \ +X ] X Xr_hall_n = Room().init('North of hall') Xr_hall_n.description = [ \ -X 'You are stanting at the north side of a very large hall.', \ -X 'There are corridors leading west, northwest, northeast,', \ -X 'an elevator door north, and a door leading outside east.', \ -X 'There are stairs leading up, and the hall continues to the south.' \ -X ] +X 'You are stanting at the north side of a very large hall.', \ +X 'There are corridors leading west, northwest, northeast,', \ +X 'an elevator door north, and a door leading outside east.', \ +X 'There are stairs leading up, and the hall continues to the south.' \ +X ] X Xr_reception = Room().init('Reception') X @@ -742,7 +742,7 @@ Xr_reception.add(o_lamp) X X# Create an uninitialized player object. X# It is initialized by main(), but must be created here (as global) -X# since some Room methods reference it. (Though maybe they shouldn't?) +X# since some Room methods reference it. (Though maybe they shouldn't?) X Xplayer = Player() X @@ -750,11 +750,11 @@ X X# Play the game from the beginning. X Xdef main(): -X x = player.init(r_initial) -X try: -X player.play() -X except (EOFError, KeyboardInterrupt): -X pass +X x = player.init(r_initial) +X try: +X player.play() +X except (EOFError, KeyboardInterrupt): +X pass X Xmain() EOF @@ -769,11 +769,11 @@ X# X# Efficiently compare files, boolean outcome only (equal / not equal). X# X# Tricks (used in this order): -X# - Use the statcache module to avoid statting files more than once -X# - Files with identical type, size & mtime are assumed to be clones -X# - Files with different type or size cannot be identical -X# - We keep a cache of outcomes of earlier comparisons -X# - We don't fork a process to run 'cmp' but read the files ourselves +X# - Use the statcache module to avoid statting files more than once +X# - Files with identical type, size & mtime are assumed to be clones +X# - Files with different type or size cannot be identical +X# - We keep a cache of outcomes of earlier comparisons +X# - We don't fork a process to run 'cmp' but read the files ourselves X Ximport posix Xfrom stat import * @@ -789,49 +789,49 @@ X# Compare two files, use the cache if possible. X# May raise posix.error if a stat or open of either fails. X# Xdef cmp(f1, f2): -X # Return 1 for identical files, 0 for different. -X # Raise exceptions if either file could not be statted, read, etc. -X s1, s2 = sig(statcache.stat(f1)), sig(statcache.stat(f2)) -X if not S_ISREG(s1[0]) or not S_ISREG(s2[0]): -X # Either is a not a plain file -- always report as different -X return 0 -X if s1 = s2: -X # type, size & mtime match -- report same -X return 1 -X if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother -X # types or sizes differ -- report different -X return 0 -X # same type and size -- look in the cache -X key = f1 + ' ' + f2 -X if cache.has_key(key): -X cs1, cs2, outcome = cache[key] -X # cache hit -X if s1 = cs1 and s2 = cs2: -X # cached signatures match -X return outcome -X # stale cached signature(s) -X # really compare -X outcome = do_cmp(f1, f2) -X cache[key] = s1, s2, outcome -X return outcome +X # Return 1 for identical files, 0 for different. +X # Raise exceptions if either file could not be statted, read, etc. +X s1, s2 = sig(statcache.stat(f1)), sig(statcache.stat(f2)) +X if not S_ISREG(s1[0]) or not S_ISREG(s2[0]): +X # Either is a not a plain file -- always report as different +X return 0 +X if s1 = s2: +X # type, size & mtime match -- report same +X return 1 +X if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother +X # types or sizes differ -- report different +X return 0 +X # same type and size -- look in the cache +X key = f1 + ' ' + f2 +X if cache.has_key(key): +X cs1, cs2, outcome = cache[key] +X # cache hit +X if s1 = cs1 and s2 = cs2: +X # cached signatures match +X return outcome +X # stale cached signature(s) +X # really compare +X outcome = do_cmp(f1, f2) +X cache[key] = s1, s2, outcome +X return outcome X X# Return signature (i.e., type, size, mtime) from raw stat data. X# Xdef sig(st): -X return S_IFMT(st[ST_MODE]), st[ST_SIZE], st[ST_MTIME] +X return S_IFMT(st[ST_MODE]), st[ST_SIZE], st[ST_MTIME] X X# Compare two files, really. X# Xdef do_cmp(f1, f2): -X #print ' cmp', f1, f2 # XXX remove when debugged -X bufsize = 8096 # Could be tuned -X fp1 = open(f1, 'r') -X fp2 = open(f2, 'r') -X while 1: -X b1 = fp1.read(bufsize) -X b2 = fp2.read(bufsize) -X if b1 <> b2: return 0 -X if not b1: return 1 +X #print ' cmp', f1, f2 # XXX remove when debugged +X bufsize = 8096 # Could be tuned +X fp1 = open(f1, 'r') +X fp2 = open(f2, 'r') +X while 1: +X b1 = fp1.read(bufsize) +X b2 = fp2.read(bufsize) +X if b1 <> b2: return 0 +X if not b1: return 1 EOF fi if test -s 'lib/macshell.py' @@ -862,379 +862,379 @@ Xclass Struct(): pass XG = Struct() X Xdef reset(): -X G.debug = 0 -X G.ps1 = '$ ' -X G.homedir = mac.getcwd() -X G.commands = mkcmdtab() -X G.aliases = {} +X G.debug = 0 +X G.ps1 = '$ ' +X G.homedir = mac.getcwd() +X G.commands = mkcmdtab() +X G.aliases = {} X Xdef mkcmdtab(): -X tab = {} -X tab['alias'] = do_alias -X tab['cd'] = do_cd -X tab['debug'] = do_debug -X tab['grep'] = do_grep -X tab['help'] = do_help -X tab['ls'] = do_ls -X tab['mkdir'] = do_mkdir -X tab['mv'] = do_mv -X tab['page'] = do_page -X tab['pwd'] = do_pwd -X tab['reset'] = do_reset -X tab['rm'] = do_rm -X tab['rmdir'] = do_rmdir -X tab['sync'] = do_sync -X tab['unalias'] = do_unalias -X return tab +X tab = {} +X tab['alias'] = do_alias +X tab['cd'] = do_cd +X tab['debug'] = do_debug +X tab['grep'] = do_grep +X tab['help'] = do_help +X tab['ls'] = do_ls +X tab['mkdir'] = do_mkdir +X tab['mv'] = do_mv +X tab['page'] = do_page +X tab['pwd'] = do_pwd +X tab['reset'] = do_reset +X tab['rm'] = do_rm +X tab['rmdir'] = do_rmdir +X tab['sync'] = do_sync +X tab['unalias'] = do_unalias +X return tab X Xdef main(): -X while 1: -X try: -X line = raw_input(G.ps1) -X except EOFError: -X print '[EOF]' -X break -X except KeyboardInterrupt: -X print '[Intr]' -X line = '' -X if G.debug: -X print 'line:', `line` -X words = TclUtil.SplitList(line) -X if G.debug: -X print 'words:', words -X if words and words[0][0] <> '#': -X run(words) +X while 1: +X try: +X line = raw_input(G.ps1) +X except EOFError: +X print '[EOF]' +X break +X except KeyboardInterrupt: +X print '[Intr]' +X line = '' +X if G.debug: +X print 'line:', `line` +X words = TclUtil.SplitList(line) +X if G.debug: +X print 'words:', words +X if words and words[0][0] <> '#': +X run(words) X Xdef run(words): -X expandaliases(words) -X cmd = words[0] -X args = words[1:] -X if G.commands.has_key(cmd): -X if args: -X try: -X args = expandgloblist(args) -X except glob_error, msg: -X print cmd, ': glob error :', msg -X return -X G.commands[cmd](args) -X return -X if hasglobchar(cmd): -X if args: -X print cmd, ': cannot glob pattern with arguments' -X return -X try: -X words = expandglobword(cmd) -X except glob_error, msg: -X print cmd, ': glob error :', msg -X return -X if len(words) > 1: -X columnize(words) -X return -X cmd = words[0] -X print cmd -X if isfile(cmd): -X if args: -X print cmd, ': file command expects no arguments' -X return -X do_page([cmd]) -X elif isdir(cmd): -X if args: -X print cmd, ': directory command expects no arguments' -X return -X do_cd([cmd]) -X else: -X print cmd, ': no such command, file or directory' +X expandaliases(words) +X cmd = words[0] +X args = words[1:] +X if G.commands.has_key(cmd): +X if args: +X try: +X args = expandgloblist(args) +X except glob_error, msg: +X print cmd, ': glob error :', msg +X return +X G.commands[cmd](args) +X return +X if hasglobchar(cmd): +X if args: +X print cmd, ': cannot glob pattern with arguments' +X return +X try: +X words = expandglobword(cmd) +X except glob_error, msg: +X print cmd, ': glob error :', msg +X return +X if len(words) > 1: +X columnize(words) +X return +X cmd = words[0] +X print cmd +X if isfile(cmd): +X if args: +X print cmd, ': file command expects no arguments' +X return +X do_page([cmd]) +X elif isdir(cmd): +X if args: +X print cmd, ': directory command expects no arguments' +X return +X do_cd([cmd]) +X else: +X print cmd, ': no such command, file or directory' X Xglob_error = 'glob error' X Xdef expandgloblist(words): -X res = [] -X for word in words: -X if hasglobchar(word): -X res = res + expandglobword(word) -X else: -X res.append(word) -X return res +X res = [] +X for word in words: +X if hasglobchar(word): +X res = res + expandglobword(word) +X else: +X res.append(word) +X return res X Xdef expandglobword(word): -X names = glob.globlist(mac.listdir(':'), word) -X if not names: raise glob_error, 'no match for pattern ' + word -X return names +X names = glob.globlist(mac.listdir(':'), word) +X if not names: raise glob_error, 'no match for pattern ' + word +X return names X Xdef hasglobchar(word): -X return '*' in word or '?' in word +X return '*' in word or '?' in word X Xdef expandaliases(words): -X seen = [] -X cmd = words[0] -X while cmd not in seen and G.aliases.has_key(cmd): -X seen.append(cmd) -X words[:1] = G.aliases[cmd] -X cmd = words[0] +X seen = [] +X cmd = words[0] +X while cmd not in seen and G.aliases.has_key(cmd): +X seen.append(cmd) +X words[:1] = G.aliases[cmd] +X cmd = words[0] X Xdef do_alias(args): -X if not args: -X listaliases() -X elif len(args) = 1: -X listalias(args[0]) -X else: -X defalias(args[0], args[1:]) +X if not args: +X listaliases() +X elif len(args) = 1: +X listalias(args[0]) +X else: +X defalias(args[0], args[1:]) X Xdef listaliases(): -X names = G.aliases.keys() -X names.sort() -X for name in names: listalias(name) +X names = G.aliases.keys() +X names.sort() +X for name in names: listalias(name) X Xdef listalias(name): -X if not G.aliases.has_key(name): -X print name, ': no such alias' -X return -X print 'alias', name, -X printlist(G.aliases[name]) -X print +X if not G.aliases.has_key(name): +X print name, ': no such alias' +X return +X print 'alias', name, +X printlist(G.aliases[name]) +X print X Xdef defalias(name, expansion): -X G.aliases[name] = expansion +X G.aliases[name] = expansion X Xdef do_cd(args): -X if len(args) > 1: -X print 'usage: cd [dirname]' -X elif args: -X chdirto(args[0]) -X else: -X chdirto(G.homedir) +X if len(args) > 1: +X print 'usage: cd [dirname]' +X elif args: +X chdirto(args[0]) +X else: +X chdirto(G.homedir) X Xdef chdirto(dirname): -X try: -X mac.chdir(dirname) -X except mac.error, msg: -X print dirname, ':', msg -X return +X try: +X mac.chdir(dirname) +X except mac.error, msg: +X print dirname, ':', msg +X return X Xdef do_debug(args): -X G.debug = (not G.debug) +X G.debug = (not G.debug) X Xdef do_grep(args): -X if len(args) < 2: -X print 'usage: grep regexp file ...' -X return -X import regexp -X try: -X prog = regexp.compile(args[0]) -X except regexp.error, msg: -X print 'regexp.compile error for', args[0], ':', msg -X return -X for file in args[1:]: -X grepfile(prog, file) +X if len(args) < 2: +X print 'usage: grep regexp file ...' +X return +X import regexp +X try: +X prog = regexp.compile(args[0]) +X except regexp.error, msg: +X print 'regexp.compile error for', args[0], ':', msg +X return +X for file in args[1:]: +X grepfile(prog, file) X Xdef grepfile(prog, file): -X try: -X fp = open(file, 'r') -X except RuntimeError, msg: -X print file, ': cannot open :', msg -X return -X lineno = 0 -X while 1: -X line = fp.readline() -X if not line: break -X lineno = lineno+1 -X if prog.exec(line): -X print file+'('+`lineno`+'):', line, +X try: +X fp = open(file, 'r') +X except RuntimeError, msg: +X print file, ': cannot open :', msg +X return +X lineno = 0 +X while 1: +X line = fp.readline() +X if not line: break +X lineno = lineno+1 +X if prog.exec(line): +X print file+'('+`lineno`+'):', line, X Xdef do_help(args): -X if args: -X print 'usage: help' -X return -X names = G.commands.keys() -X names.sort() -X columnize(names) +X if args: +X print 'usage: help' +X return +X names = G.commands.keys() +X names.sort() +X columnize(names) X Xdef do_ls(args): -X if not args: -X lsdir(':') -X else: -X for dirname in args: -X lsdir(dirname) +X if not args: +X lsdir(':') +X else: +X for dirname in args: +X lsdir(dirname) X Xdef lsdir(dirname): -X if not isdir(dirname): -X print dirname, ': no such directory' -X return -X names = mac.listdir(dirname) -X lsfiles(names, dirname) +X if not isdir(dirname): +X print dirname, ': no such directory' +X return +X names = mac.listdir(dirname) +X lsfiles(names, dirname) X Xdef lsfiles(names, dirname): -X names = names[:] # Make a copy so we can modify it -X for i in range(len(names)): -X name = names[i] -X if G.debug: print i, name -X if isdir(macpath.cat(dirname, name)): -X names[i] = ':' + name + ':' -X columnize(names) +X names = names[:] # Make a copy so we can modify it +X for i in range(len(names)): +X name = names[i] +X if G.debug: print i, name +X if isdir(macpath.cat(dirname, name)): +X names[i] = ':' + name + ':' +X columnize(names) X Xdef columnize(list): -X COLUMNS = 80-1 -X n = len(list) -X colwidth = maxwidth(list) -X ncols = (COLUMNS + 1) / (colwidth + 1) -X if ncols < 1: ncols = 1 -X nrows = (n + ncols - 1) / ncols -X for irow in range(nrows): -X line = '' -X for icol in range(ncols): -X i = irow + nrows*icol -X if 0 <= i < n: -X word = list[i] -X if i+nrows < n: -X word = string.ljust(word, colwidth) -X if icol > 0: -X word = ' ' + word -X line = line + word -X print line +X COLUMNS = 80-1 +X n = len(list) +X colwidth = maxwidth(list) +X ncols = (COLUMNS + 1) / (colwidth + 1) +X if ncols < 1: ncols = 1 +X nrows = (n + ncols - 1) / ncols +X for irow in range(nrows): +X line = '' +X for icol in range(ncols): +X i = irow + nrows*icol +X if 0 <= i < n: +X word = list[i] +X if i+nrows < n: +X word = string.ljust(word, colwidth) +X if icol > 0: +X word = ' ' + word +X line = line + word +X print line X Xdef maxwidth(list): -X width = 0 -X for word in list: -X if len(word) > width: -X width = len(word) -X return width +X width = 0 +X for word in list: +X if len(word) > width: +X width = len(word) +X return width X Xdef do_mv(args): -X if len(args) <> 2: -X print 'usage: mv src dst' -X return -X src, dst = args[0], args[1] -X if not exists(src): -X print src, ': source does not exist' -X return -X if exists(dst): -X print src, ': destination already exists' -X return -X try: -X mac.rename(src, dst) -X except mac.error, msg: -X print src, dst, ': rename failed:', msg +X if len(args) <> 2: +X print 'usage: mv src dst' +X return +X src, dst = args[0], args[1] +X if not exists(src): +X print src, ': source does not exist' +X return +X if exists(dst): +X print src, ': destination already exists' +X return +X try: +X mac.rename(src, dst) +X except mac.error, msg: +X print src, dst, ': rename failed:', msg X Xdef do_mkdir(args): -X if not args: -X print 'usage: mkdir name ...' -X return -X for name in args: -X makedir(name) +X if not args: +X print 'usage: mkdir name ...' +X return +X for name in args: +X makedir(name) X Xdef makedir(name): -X if exists(name): -X print name, ': already exists' -X return -X try: -X mac.mkdir(name, 0777) -X except mac.error, msg: -X print name, ': mkdir failed:', msg +X if exists(name): +X print name, ': already exists' +X return +X try: +X mac.mkdir(name, 0777) +X except mac.error, msg: +X print name, ': mkdir failed:', msg X Xdef do_page(args): -X if not args: -X print 'usage: page file ...' -X return -X for name in args: -X pagefile(name) +X if not args: +X print 'usage: page file ...' +X return +X for name in args: +X pagefile(name) X Xdef pagefile(name): -X if not isfile(name): -X print name, ': no such file' -X return -X LINES = 24 - 1 -X # For THINK C 3.0, make the path absolute: -X # if not macpath.isabs(name): -X # name = macpath.cat(mac.getcwd(), name) -X try: -X fp = open(name, 'r') -X except: -X print name, ': cannot open' -X return -X line = fp.readline() -X while line: -X for i in range(LINES): -X print line, -X line = fp.readline() -X if not line: break -X if line: -X try: -X more = raw_input('[more]') -X except (EOFError, KeyboardInterrupt): -X print -X break -X if string.strip(more)[:1] in ('q', 'Q'): -X break +X if not isfile(name): +X print name, ': no such file' +X return +X LINES = 24 - 1 +X # For THINK C 3.0, make the path absolute: +X # if not macpath.isabs(name): +X # name = macpath.cat(mac.getcwd(), name) +X try: +X fp = open(name, 'r') +X except: +X print name, ': cannot open' +X return +X line = fp.readline() +X while line: +X for i in range(LINES): +X print line, +X line = fp.readline() +X if not line: break +X if line: +X try: +X more = raw_input('[more]') +X except (EOFError, KeyboardInterrupt): +X print +X break +X if string.strip(more)[:1] in ('q', 'Q'): +X break X Xdef do_pwd(args): -X if args: -X print 'usage: pwd' -X else: -X print mac.getcwd() +X if args: +X print 'usage: pwd' +X else: +X print mac.getcwd() X Xdef do_reset(args): -X if args: -X print 'usage: reset' -X else: -X reset() +X if args: +X print 'usage: reset' +X else: +X reset() X Xdef do_rm(args): -X if not args: -X print 'usage: rm file ...' -X return -X for name in args: -X remove(name) +X if not args: +X print 'usage: rm file ...' +X return +X for name in args: +X remove(name) X Xdef remove(name): -X if not isfile(name): -X print name, ': no such file' -X return -X try: -X mac.unlink(name) -X except mac.error, msg: -X print name, ': unlink failed:', msg +X if not isfile(name): +X print name, ': no such file' +X return +X try: +X mac.unlink(name) +X except mac.error, msg: +X print name, ': unlink failed:', msg X Xdef do_rmdir(args): -X if not args: -X print 'usage: rmdir dir ...' -X return -X for name in args: -X rmdir(name) +X if not args: +X print 'usage: rmdir dir ...' +X return +X for name in args: +X rmdir(name) X Xdef rmdir(name): -X if not isdir(name): -X print name, ': no such directory' -X return -X try: -X mac.rmdir(name) -X except mac.error, msg: -X print name, ': rmdir failed:', msg +X if not isdir(name): +X print name, ': no such directory' +X return +X try: +X mac.rmdir(name) +X except mac.error, msg: +X print name, ': rmdir failed:', msg X Xdef do_sync(args): -X if args: -X print 'usage: sync' -X return -X try: -X mac.sync() -X except mac.error, msg: -X print 'sync failed:', msg +X if args: +X print 'usage: sync' +X return +X try: +X mac.sync() +X except mac.error, msg: +X print 'sync failed:', msg X Xdef do_unalias(args): -X if not args: -X print 'usage: unalias name ...' -X return -X for name in args: -X unalias(name) +X if not args: +X print 'usage: unalias name ...' +X return +X for name in args: +X unalias(name) X Xdef unalias(name): -X if not G.aliases.has_key(name): -X print name, ': no such alias' -X return -X del G.aliases[name] +X if not G.aliases.has_key(name): +X print name, ': no such alias' +X return +X del G.aliases[name] X Xdef printlist(list): -X for word in list: -X print word, +X for word in list: +X print word, X Xreset() Xmain() @@ -1249,12 +1249,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1292,351 +1292,351 @@ X/* Functions to construct return values */ X Xobject * Xmknewcharobject(c) -X int c; +X int c; X{ -X char ch[1]; -X ch[0] = c; -X return newsizedstringobject(ch, 1); +X char ch[1]; +X ch[0] = c; +X return newsizedstringobject(ch, 1); X} X X/* Functions to extract arguments. -X These needs to know the total number of arguments supplied, -X since the argument list is a tuple only of there is more than -X one argument. */ +X These needs to know the total number of arguments supplied, +X since the argument list is a tuple only of there is more than +X one argument. */ X Xint Xgetiobjectarg(args, nargs, i, p_arg) -X register object *args; -X int nargs, i; -X object **p_arg; -X{ -X if (nargs != 1) { -X if (args == NULL || !is_tupleobject(args) || -X nargs != gettuplesize(args) || -X i < 0 || i >= nargs) { -X return err_badarg(); -X } -X else { -X args = gettupleitem(args, i); -X } -X } -X if (args == NULL) { -X return err_badarg(); -X } -X *p_arg = args; -X return 1; +X register object *args; +X int nargs, i; +X object **p_arg; +X{ +X if (nargs != 1) { +X if (args == NULL || !is_tupleobject(args) || +X nargs != gettuplesize(args) || +X i < 0 || i >= nargs) { +X return err_badarg(); +X } +X else { +X args = gettupleitem(args, i); +X } +X } +X if (args == NULL) { +X return err_badarg(); +X } +X *p_arg = args; +X return 1; X} X Xint Xgetilongarg(args, nargs, i, p_arg) -X register object *args; -X int nargs, i; -X long *p_arg; -X{ -X if (nargs != 1) { -X if (args == NULL || !is_tupleobject(args) || -X nargs != gettuplesize(args) || -X i < 0 || i >= nargs) { -X return err_badarg(); -X } -X args = gettupleitem(args, i); -X } -X if (args == NULL || !is_intobject(args)) { -X return err_badarg(); -X } -X *p_arg = getintvalue(args); -X return 1; +X register object *args; +X int nargs, i; +X long *p_arg; +X{ +X if (nargs != 1) { +X if (args == NULL || !is_tupleobject(args) || +X nargs != gettuplesize(args) || +X i < 0 || i >= nargs) { +X return err_badarg(); +X } +X args = gettupleitem(args, i); +X } +X if (args == NULL || !is_intobject(args)) { +X return err_badarg(); +X } +X *p_arg = getintvalue(args); +X return 1; X} X Xint Xgetishortarg(args, nargs, i, p_arg) -X register object *args; -X int nargs, i; -X short *p_arg; +X register object *args; +X int nargs, i; +X short *p_arg; X{ -X long x; -X if (!getilongarg(args, nargs, i, &x)) -X return 0; -X *p_arg = x; -X return 1; +X long x; +X if (!getilongarg(args, nargs, i, &x)) +X return 0; +X *p_arg = x; +X return 1; X} X Xstatic int Xextractdouble(v, p_arg) -X register object *v; -X double *p_arg; -X{ -X if (v == NULL) { -X /* Fall through to error return at end of function */ -X } -X else if (is_floatobject(v)) { -X *p_arg = GETFLOATVALUE((floatobject *)v); -X return 1; -X } -X else if (is_intobject(v)) { -X *p_arg = GETINTVALUE((intobject *)v); -X return 1; -X } -X return err_badarg(); +X register object *v; +X double *p_arg; +X{ +X if (v == NULL) { +X /* Fall through to error return at end of function */ +X } +X else if (is_floatobject(v)) { +X *p_arg = GETFLOATVALUE((floatobject *)v); +X return 1; +X } +X else if (is_intobject(v)) { +X *p_arg = GETINTVALUE((intobject *)v); +X return 1; +X } +X return err_badarg(); X} X Xstatic int Xextractfloat(v, p_arg) -X register object *v; -X float *p_arg; -X{ -X if (v == NULL) { -X /* Fall through to error return at end of function */ -X } -X else if (is_floatobject(v)) { -X *p_arg = GETFLOATVALUE((floatobject *)v); -X return 1; -X } -X else if (is_intobject(v)) { -X *p_arg = GETINTVALUE((intobject *)v); -X return 1; -X } -X return err_badarg(); +X register object *v; +X float *p_arg; +X{ +X if (v == NULL) { +X /* Fall through to error return at end of function */ +X } +X else if (is_floatobject(v)) { +X *p_arg = GETFLOATVALUE((floatobject *)v); +X return 1; +X } +X else if (is_intobject(v)) { +X *p_arg = GETINTVALUE((intobject *)v); +X return 1; +X } +X return err_badarg(); X} X Xint Xgetifloatarg(args, nargs, i, p_arg) -X register object *args; -X int nargs, i; -X float *p_arg; +X register object *args; +X int nargs, i; +X float *p_arg; X{ -X object *v; -X float x; -X if (!getiobjectarg(args, nargs, i, &v)) -X return 0; -X if (!extractfloat(v, &x)) -X return 0; -X *p_arg = x; -X return 1; +X object *v; +X float x; +X if (!getiobjectarg(args, nargs, i, &v)) +X return 0; +X if (!extractfloat(v, &x)) +X return 0; +X *p_arg = x; +X return 1; X} X Xint Xgetistringarg(args, nargs, i, p_arg) -X object *args; -X int nargs, i; -X string *p_arg; +X object *args; +X int nargs, i; +X string *p_arg; X{ -X object *v; -X if (!getiobjectarg(args, nargs, i, &v)) -X return NULL; -X if (!is_stringobject(v)) { -X return err_badarg(); -X } -X *p_arg = getstringvalue(v); -X return 1; +X object *v; +X if (!getiobjectarg(args, nargs, i, &v)) +X return NULL; +X if (!is_stringobject(v)) { +X return err_badarg(); +X } +X *p_arg = getstringvalue(v); +X return 1; X} X Xint Xgetichararg(args, nargs, i, p_arg) -X object *args; -X int nargs, i; -X char *p_arg; +X object *args; +X int nargs, i; +X char *p_arg; X{ -X string x; -X if (!getistringarg(args, nargs, i, &x)) -X return 0; -X if (x[0] == '\0' || x[1] != '\0') { -X /* Not exactly one char */ -X return err_badarg(); -X } -X *p_arg = x[0]; -X return 1; +X string x; +X if (!getistringarg(args, nargs, i, &x)) +X return 0; +X if (x[0] == '\0' || x[1] != '\0') { +X /* Not exactly one char */ +X return err_badarg(); +X } +X *p_arg = x[0]; +X return 1; X} X Xint Xgetilongarraysize(args, nargs, i, p_arg) -X object *args; -X int nargs, i; -X long *p_arg; -X{ -X object *v; -X if (!getiobjectarg(args, nargs, i, &v)) -X return 0; -X if (is_tupleobject(v)) { -X *p_arg = gettuplesize(v); -X return 1; -X } -X if (is_listobject(v)) { -X *p_arg = getlistsize(v); -X return 1; -X } -X return err_badarg(); +X object *args; +X int nargs, i; +X long *p_arg; +X{ +X object *v; +X if (!getiobjectarg(args, nargs, i, &v)) +X return 0; +X if (is_tupleobject(v)) { +X *p_arg = gettuplesize(v); +X return 1; +X } +X if (is_listobject(v)) { +X *p_arg = getlistsize(v); +X return 1; +X } +X return err_badarg(); X} X Xint Xgetishortarraysize(args, nargs, i, p_arg) -X object *args; -X int nargs, i; -X short *p_arg; +X object *args; +X int nargs, i; +X short *p_arg; X{ -X long x; -X if (!getilongarraysize(args, nargs, i, &x)) -X return 0; -X *p_arg = x; -X return 1; +X long x; +X if (!getilongarraysize(args, nargs, i, &x)) +X return 0; +X *p_arg = x; +X return 1; X} X -X/* XXX The following four are too similar. Should share more code. */ +X/* XXX The following four are too similar. Should share more code. */ X Xint Xgetilongarray(args, nargs, i, n, p_arg) -X object *args; -X int nargs, i; -X int n; -X long *p_arg; /* [n] */ -X{ -X object *v, *w; -X if (!getiobjectarg(args, nargs, i, &v)) -X return 0; -X if (is_tupleobject(v)) { -X if (gettuplesize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = gettupleitem(v, i); -X if (!is_intobject(w)) { -X return err_badarg(); -X } -X p_arg[i] = getintvalue(w); -X } -X return 1; -X } -X else if (is_listobject(v)) { -X if (getlistsize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = getlistitem(v, i); -X if (!is_intobject(w)) { -X return err_badarg(); -X } -X p_arg[i] = getintvalue(w); -X } -X return 1; -X } -X else { -X return err_badarg(); -X } +X object *args; +X int nargs, i; +X int n; +X long *p_arg; /* [n] */ +X{ +X object *v, *w; +X if (!getiobjectarg(args, nargs, i, &v)) +X return 0; +X if (is_tupleobject(v)) { +X if (gettuplesize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = gettupleitem(v, i); +X if (!is_intobject(w)) { +X return err_badarg(); +X } +X p_arg[i] = getintvalue(w); +X } +X return 1; +X } +X else if (is_listobject(v)) { +X if (getlistsize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = getlistitem(v, i); +X if (!is_intobject(w)) { +X return err_badarg(); +X } +X p_arg[i] = getintvalue(w); +X } +X return 1; +X } +X else { +X return err_badarg(); +X } X} X Xint Xgetishortarray(args, nargs, i, n, p_arg) -X object *args; -X int nargs, i; -X int n; -X short *p_arg; /* [n] */ -X{ -X object *v, *w; -X if (!getiobjectarg(args, nargs, i, &v)) -X return 0; -X if (is_tupleobject(v)) { -X if (gettuplesize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = gettupleitem(v, i); -X if (!is_intobject(w)) { -X return err_badarg(); -X } -X p_arg[i] = getintvalue(w); -X } -X return 1; -X } -X else if (is_listobject(v)) { -X if (getlistsize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = getlistitem(v, i); -X if (!is_intobject(w)) { -X return err_badarg(); -X } -X p_arg[i] = getintvalue(w); -X } -X return 1; -X } -X else { -X return err_badarg(); -X } +X object *args; +X int nargs, i; +X int n; +X short *p_arg; /* [n] */ +X{ +X object *v, *w; +X if (!getiobjectarg(args, nargs, i, &v)) +X return 0; +X if (is_tupleobject(v)) { +X if (gettuplesize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = gettupleitem(v, i); +X if (!is_intobject(w)) { +X return err_badarg(); +X } +X p_arg[i] = getintvalue(w); +X } +X return 1; +X } +X else if (is_listobject(v)) { +X if (getlistsize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = getlistitem(v, i); +X if (!is_intobject(w)) { +X return err_badarg(); +X } +X p_arg[i] = getintvalue(w); +X } +X return 1; +X } +X else { +X return err_badarg(); +X } X} X Xint Xgetidoublearray(args, nargs, i, n, p_arg) -X object *args; -X int nargs, i; -X int n; -X double *p_arg; /* [n] */ -X{ -X object *v, *w; -X if (!getiobjectarg(args, nargs, i, &v)) -X return 0; -X if (is_tupleobject(v)) { -X if (gettuplesize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = gettupleitem(v, i); -X if (!extractdouble(w, &p_arg[i])) -X return 0; -X } -X return 1; -X } -X else if (is_listobject(v)) { -X if (getlistsize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = getlistitem(v, i); -X if (!extractdouble(w, &p_arg[i])) -X return 0; -X } -X return 1; -X } -X else { -X return err_badarg(); -X } +X object *args; +X int nargs, i; +X int n; +X double *p_arg; /* [n] */ +X{ +X object *v, *w; +X if (!getiobjectarg(args, nargs, i, &v)) +X return 0; +X if (is_tupleobject(v)) { +X if (gettuplesize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = gettupleitem(v, i); +X if (!extractdouble(w, &p_arg[i])) +X return 0; +X } +X return 1; +X } +X else if (is_listobject(v)) { +X if (getlistsize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = getlistitem(v, i); +X if (!extractdouble(w, &p_arg[i])) +X return 0; +X } +X return 1; +X } +X else { +X return err_badarg(); +X } X} X Xint Xgetifloatarray(args, nargs, i, n, p_arg) -X object *args; -X int nargs, i; -X int n; -X float *p_arg; /* [n] */ -X{ -X object *v, *w; -X if (!getiobjectarg(args, nargs, i, &v)) -X return 0; -X if (is_tupleobject(v)) { -X if (gettuplesize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = gettupleitem(v, i); -X if (!extractfloat(w, &p_arg[i])) -X return 0; -X } -X return 1; -X } -X else if (is_listobject(v)) { -X if (getlistsize(v) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X w = getlistitem(v, i); -X if (!extractfloat(w, &p_arg[i])) -X return 0; -X } -X return 1; -X } -X else { -X return err_badarg(); -X } +X object *args; +X int nargs, i; +X int n; +X float *p_arg; /* [n] */ +X{ +X object *v, *w; +X if (!getiobjectarg(args, nargs, i, &v)) +X return 0; +X if (is_tupleobject(v)) { +X if (gettuplesize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = gettupleitem(v, i); +X if (!extractfloat(w, &p_arg[i])) +X return 0; +X } +X return 1; +X } +X else if (is_listobject(v)) { +X if (getlistsize(v) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X w = getlistitem(v, i); +X if (!extractfloat(w, &p_arg[i])) +X return 0; +X } +X return 1; +X } +X else { +X return err_badarg(); +X } X} EOF fi @@ -1649,12 +1649,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1678,353 +1678,353 @@ X X Xobject * Xinitmodule(name, methods) -X char *name; -X struct methodlist *methods; -X{ -X object *m, *d, *v; -X struct methodlist *ml; -X char namebuf[256]; -X if ((m = add_module(name)) == NULL) { -X fprintf(stderr, "initializing module: %s\n", name); -X fatal("can't create a module"); -X } -X d = getmoduledict(m); -X for (ml = methods; ml->ml_name != NULL; ml++) { -X sprintf(namebuf, "%s.%s", name, ml->ml_name); -X v = newmethodobject(strdup(namebuf), ml->ml_meth, -X (object *)NULL); -X /* XXX The strdup'ed memory is never freed */ -X if (v == NULL || dictinsert(d, ml->ml_name, v) != 0) { -X fprintf(stderr, "initializing module: %s\n", name); -X fatal("can't initialize module"); -X } -X DECREF(v); -X } -X return m; +X char *name; +X struct methodlist *methods; +X{ +X object *m, *d, *v; +X struct methodlist *ml; +X char namebuf[256]; +X if ((m = add_module(name)) == NULL) { +X fprintf(stderr, "initializing module: %s\n", name); +X fatal("can't create a module"); +X } +X d = getmoduledict(m); +X for (ml = methods; ml->ml_name != NULL; ml++) { +X sprintf(namebuf, "%s.%s", name, ml->ml_name); +X v = newmethodobject(strdup(namebuf), ml->ml_meth, +X (object *)NULL); +X /* XXX The strdup'ed memory is never freed */ +X if (v == NULL || dictinsert(d, ml->ml_name, v) != 0) { +X fprintf(stderr, "initializing module: %s\n", name); +X fatal("can't initialize module"); +X } +X DECREF(v); +X } +X return m; X} X X X/* Argument list handling tools. -X All return 1 for success, or call err_set*() and return 0 for failure */ +X All return 1 for success, or call err_set*() and return 0 for failure */ X Xint Xgetnoarg(v) -X object *v; +X object *v; X{ -X if (v != NULL) { -X return err_badarg(); -X } -X return 1; +X if (v != NULL) { +X return err_badarg(); +X } +X return 1; X} X Xint Xgetintarg(v, a) -X object *v; -X int *a; +X object *v; +X int *a; X{ -X if (v == NULL || !is_intobject(v)) { -X return err_badarg(); -X } -X *a = getintvalue(v); -X return 1; +X if (v == NULL || !is_intobject(v)) { +X return err_badarg(); +X } +X *a = getintvalue(v); +X return 1; X} X Xint Xgetintintarg(v, a, b) -X object *v; -X int *a; -X int *b; +X object *v; +X int *a; +X int *b; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getintarg(gettupleitem(v, 0), a) && -X getintarg(gettupleitem(v, 1), b); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getintarg(gettupleitem(v, 0), a) && +X getintarg(gettupleitem(v, 1), b); X} X Xint Xgetlongarg(v, a) -X object *v; -X long *a; +X object *v; +X long *a; X{ -X if (v == NULL || !is_intobject(v)) { -X return err_badarg(); -X } -X *a = getintvalue(v); -X return 1; +X if (v == NULL || !is_intobject(v)) { +X return err_badarg(); +X } +X *a = getintvalue(v); +X return 1; X} X Xint Xgetlonglongargs(v, a, b) -X object *v; -X long *a, *b; +X object *v; +X long *a, *b; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getlongarg(gettupleitem(v, 0), a) && -X getlongarg(gettupleitem(v, 1), b); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getlongarg(gettupleitem(v, 0), a) && +X getlongarg(gettupleitem(v, 1), b); X} X Xint Xgetlonglongobjectargs(v, a, b, c) -X object *v; -X long *a, *b; -X object **c; -X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { -X return err_badarg(); -X } -X if (getlongarg(gettupleitem(v, 0), a) && -X getlongarg(gettupleitem(v, 1), b)) { -X *c = gettupleitem(v, 2); -X return 1; -X } -X else { -X return err_badarg(); -X } +X object *v; +X long *a, *b; +X object **c; +X{ +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { +X return err_badarg(); +X } +X if (getlongarg(gettupleitem(v, 0), a) && +X getlongarg(gettupleitem(v, 1), b)) { +X *c = gettupleitem(v, 2); +X return 1; +X } +X else { +X return err_badarg(); +X } X} X Xint Xgetstrarg(v, a) -X object *v; -X object **a; +X object *v; +X object **a; X{ -X if (v == NULL || !is_stringobject(v)) { -X return err_badarg(); -X } -X *a = v; -X return 1; +X if (v == NULL || !is_stringobject(v)) { +X return err_badarg(); +X } +X *a = v; +X return 1; X} X Xint Xgetstrstrarg(v, a, b) -X object *v; -X object **a; -X object **b; +X object *v; +X object **a; +X object **b; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getstrarg(gettupleitem(v, 0), a) && -X getstrarg(gettupleitem(v, 1), b); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getstrarg(gettupleitem(v, 0), a) && +X getstrarg(gettupleitem(v, 1), b); X} X Xint Xgetstrstrintarg(v, a, b, c) -X object *v; -X object **a; -X object **b; -X int *c; +X object *v; +X object **a; +X object **b; +X int *c; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { -X return err_badarg(); -X } -X return getstrarg(gettupleitem(v, 0), a) && -X getstrarg(gettupleitem(v, 1), b) && -X getintarg(gettupleitem(v, 2), c); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { +X return err_badarg(); +X } +X return getstrarg(gettupleitem(v, 0), a) && +X getstrarg(gettupleitem(v, 1), b) && +X getintarg(gettupleitem(v, 2), c); X} X Xint Xgetstrintarg(v, a, b) -X object *v; -X object **a; -X int *b; +X object *v; +X object **a; +X int *b; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getstrarg(gettupleitem(v, 0), a) && -X getintarg(gettupleitem(v, 1), b); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getstrarg(gettupleitem(v, 0), a) && +X getintarg(gettupleitem(v, 1), b); X} X Xint Xgetintstrarg(v, a, b) -X object *v; -X int *a; -X object **b; +X object *v; +X int *a; +X object **b; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getintarg(gettupleitem(v, 0), a) && -X getstrarg(gettupleitem(v, 1), b); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getintarg(gettupleitem(v, 0), a) && +X getstrarg(gettupleitem(v, 1), b); X} X Xint Xgetpointarg(v, a) -X object *v; -X int *a; /* [2] */ +X object *v; +X int *a; /* [2] */ X{ -X return getintintarg(v, a, a+1); +X return getintintarg(v, a, a+1); X} X Xint Xget3pointarg(v, a) -X object *v; -X int *a; /* [6] */ +X object *v; +X int *a; /* [6] */ X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { -X return err_badarg(); -X } -X return getpointarg(gettupleitem(v, 0), a) && -X getpointarg(gettupleitem(v, 1), a+2) && -X getpointarg(gettupleitem(v, 2), a+4); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { +X return err_badarg(); +X } +X return getpointarg(gettupleitem(v, 0), a) && +X getpointarg(gettupleitem(v, 1), a+2) && +X getpointarg(gettupleitem(v, 2), a+4); X} X Xint Xgetrectarg(v, a) -X object *v; -X int *a; /* [2+2] */ +X object *v; +X int *a; /* [2+2] */ X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getpointarg(gettupleitem(v, 0), a) && -X getpointarg(gettupleitem(v, 1), a+2); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getpointarg(gettupleitem(v, 0), a) && +X getpointarg(gettupleitem(v, 1), a+2); X} X Xint Xgetrectintarg(v, a) -X object *v; -X int *a; /* [4+1] */ +X object *v; +X int *a; /* [4+1] */ X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getrectarg(gettupleitem(v, 0), a) && -X getintarg(gettupleitem(v, 1), a+4); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getrectarg(gettupleitem(v, 0), a) && +X getintarg(gettupleitem(v, 1), a+4); X} X Xint Xgetpointintarg(v, a) -X object *v; -X int *a; /* [2+1] */ +X object *v; +X int *a; /* [2+1] */ X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getpointarg(gettupleitem(v, 0), a) && -X getintarg(gettupleitem(v, 1), a+2); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getpointarg(gettupleitem(v, 0), a) && +X getintarg(gettupleitem(v, 1), a+2); X} X Xint Xgetpointstrarg(v, a, b) -X object *v; -X int *a; /* [2] */ -X object **b; +X object *v; +X int *a; /* [2] */ +X object **b; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getpointarg(gettupleitem(v, 0), a) && -X getstrarg(gettupleitem(v, 1), b); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getpointarg(gettupleitem(v, 0), a) && +X getstrarg(gettupleitem(v, 1), b); X} X Xint Xgetstrintintarg(v, a, b, c) -X object *v; -X object *a; -X int *b, *c; +X object *v; +X object *a; +X int *b, *c; X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { -X return err_badarg(); -X } -X return getstrarg(gettupleitem(v, 0), a) && -X getintarg(gettupleitem(v, 1), b) && -X getintarg(gettupleitem(v, 2), c); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 3) { +X return err_badarg(); +X } +X return getstrarg(gettupleitem(v, 0), a) && +X getintarg(gettupleitem(v, 1), b) && +X getintarg(gettupleitem(v, 2), c); X} X Xint Xgetrectpointarg(v, a) -X object *v; -X int *a; /* [4+2] */ +X object *v; +X int *a; /* [4+2] */ X{ -X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { -X return err_badarg(); -X } -X return getrectarg(gettupleitem(v, 0), a) && -X getpointarg(gettupleitem(v, 1), a+4); +X if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2) { +X return err_badarg(); +X } +X return getrectarg(gettupleitem(v, 0), a) && +X getpointarg(gettupleitem(v, 1), a+4); X} X Xint Xgetlongtuplearg(args, a, n) -X object *args; -X long *a; /* [n] */ -X int n; -X{ -X int i; -X if (!is_tupleobject(args) || gettuplesize(args) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X object *v = gettupleitem(args, i); -X if (!is_intobject(v)) { -X return err_badarg(); -X } -X a[i] = getintvalue(v); -X } -X return 1; +X object *args; +X long *a; /* [n] */ +X int n; +X{ +X int i; +X if (!is_tupleobject(args) || gettuplesize(args) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X object *v = gettupleitem(args, i); +X if (!is_intobject(v)) { +X return err_badarg(); +X } +X a[i] = getintvalue(v); +X } +X return 1; X} X Xint Xgetshorttuplearg(args, a, n) -X object *args; -X short *a; /* [n] */ -X int n; -X{ -X int i; -X if (!is_tupleobject(args) || gettuplesize(args) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X object *v = gettupleitem(args, i); -X if (!is_intobject(v)) { -X return err_badarg(); -X } -X a[i] = getintvalue(v); -X } -X return 1; +X object *args; +X short *a; /* [n] */ +X int n; +X{ +X int i; +X if (!is_tupleobject(args) || gettuplesize(args) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X object *v = gettupleitem(args, i); +X if (!is_intobject(v)) { +X return err_badarg(); +X } +X a[i] = getintvalue(v); +X } +X return 1; X} X Xint Xgetlonglistarg(args, a, n) -X object *args; -X long *a; /* [n] */ -X int n; -X{ -X int i; -X if (!is_listobject(args) || getlistsize(args) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X object *v = getlistitem(args, i); -X if (!is_intobject(v)) { -X return err_badarg(); -X } -X a[i] = getintvalue(v); -X } -X return 1; +X object *args; +X long *a; /* [n] */ +X int n; +X{ +X int i; +X if (!is_listobject(args) || getlistsize(args) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X object *v = getlistitem(args, i); +X if (!is_intobject(v)) { +X return err_badarg(); +X } +X a[i] = getintvalue(v); +X } +X return 1; X} X Xint Xgetshortlistarg(args, a, n) -X object *args; -X short *a; /* [n] */ -X int n; -X{ -X int i; -X if (!is_listobject(args) || getlistsize(args) != n) { -X return err_badarg(); -X } -X for (i = 0; i < n; i++) { -X object *v = getlistitem(args, i); -X if (!is_intobject(v)) { -X return err_badarg(); -X } -X a[i] = getintvalue(v); -X } -X return 1; +X object *args; +X short *a; /* [n] */ +X int n; +X{ +X int i; +X if (!is_listobject(args) || getlistsize(args) != n) { +X return err_badarg(); +X } +X for (i = 0; i < n; i++) { +X object *v = getlistitem(args, i); +X if (!is_intobject(v)) { +X return err_badarg(); +X } +X a[i] = getintvalue(v); +X } +X return 1; X} EOF fi @@ -2037,12 +2037,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2083,32 +2083,32 @@ Xint debugging; /* Needed by parser.c */ X#endif X Xmain(argc, argv) -X int argc; -X char **argv; -X{ -X char *filename = NULL; -X FILE *fp = stdin; -X -X initargs(&argc, &argv); -X -X if (argc > 1 && strcmp(argv[1], "-") != 0) -X filename = argv[1]; -X -X if (filename != NULL) { -X if ((fp = fopen(filename, "r")) == NULL) { -X fprintf(stderr, "python: can't open file '%s'\n", -X filename); -X exit(2); -X } -X } -X -X initall(); -X -X setpythonpath(getpythonpath()); -X setpythonargv(argc-1, argv+1); -X -X goaway(run(fp, filename == NULL ? "<stdin>" : filename)); -X /*NOTREACHED*/ +X int argc; +X char **argv; +X{ +X char *filename = NULL; +X FILE *fp = stdin; +X +X initargs(&argc, &argv); +X +X if (argc > 1 && strcmp(argv[1], "-") != 0) +X filename = argv[1]; +X +X if (filename != NULL) { +X if ((fp = fopen(filename, "r")) == NULL) { +X fprintf(stderr, "python: can't open file '%s'\n", +X filename); +X exit(2); +X } +X } +X +X initall(); +X +X setpythonpath(getpythonpath()); +X setpythonargv(argc-1, argv+1); +X +X goaway(run(fp, filename == NULL ? "<stdin>" : filename)); +X /*NOTREACHED*/ X} X X/* Initialize all */ @@ -2116,321 +2116,321 @@ X Xvoid Xinitall() X{ -X static int inited; -X -X if (inited) -X return; -X inited = 1; -X -X initimport(); -X -X /* Modules 'builtin' and 'sys' are initialized here, -X they are needed by random bits of the interpreter. -X All other modules are optional and should be initialized -X by the initcalls() of a specific configuration. */ -X -X initbuiltin(); /* Also initializes builtin exceptions */ -X initsys(); -X -X initcalls(); /* Configuration-dependent initializations */ -X -X initintr(); /* For intrcheck() */ +X static int inited; +X +X if (inited) +X return; +X inited = 1; +X +X initimport(); +X +X /* Modules 'builtin' and 'sys' are initialized here, +X they are needed by random bits of the interpreter. +X All other modules are optional and should be initialized +X by the initcalls() of a specific configuration. */ +X +X initbuiltin(); /* Also initializes builtin exceptions */ +X initsys(); +X +X initcalls(); /* Configuration-dependent initializations */ +X +X initintr(); /* For intrcheck() */ X} X X/* Parse input from a file and execute it */ X Xint Xrun(fp, filename) -X FILE *fp; -X char *filename; +X FILE *fp; +X char *filename; X{ -X if (filename == NULL) -X filename = "???"; -X if (isatty(fileno(fp))) -X return run_tty_loop(fp, filename); -X else -X return run_script(fp, filename); +X if (filename == NULL) +X filename = "???"; +X if (isatty(fileno(fp))) +X return run_tty_loop(fp, filename); +X else +X return run_script(fp, filename); X} X Xint Xrun_tty_loop(fp, filename) -X FILE *fp; -X char *filename; -X{ -X object *v; -X int ret; -X v = sysget("ps1"); -X if (v == NULL) { -X sysset("ps1", v = newstringobject(">>> ")); -X XDECREF(v); -X } -X v = sysget("ps2"); -X if (v == NULL) { -X sysset("ps2", v = newstringobject("... ")); -X XDECREF(v); -X } -X for (;;) { -X ret = run_tty_1(fp, filename); +X FILE *fp; +X char *filename; +X{ +X object *v; +X int ret; +X v = sysget("ps1"); +X if (v == NULL) { +X sysset("ps1", v = newstringobject(">>> ")); +X XDECREF(v); +X } +X v = sysget("ps2"); +X if (v == NULL) { +X sysset("ps2", v = newstringobject("... ")); +X XDECREF(v); +X } +X for (;;) { +X ret = run_tty_1(fp, filename); X#ifdef REF_DEBUG -X fprintf(stderr, "[%ld refs]\n", ref_total); +X fprintf(stderr, "[%ld refs]\n", ref_total); X#endif -X if (ret == E_EOF) -X return 0; -X /* -X if (ret == E_NOMEM) -X return -1; -X */ -X } +X if (ret == E_EOF) +X return 0; +X /* +X if (ret == E_NOMEM) +X return -1; +X */ +X } X} X Xint Xrun_tty_1(fp, filename) -X FILE *fp; -X char *filename; -X{ -X object *m, *d, *v, *w; -X node *n; -X char *ps1, *ps2; -X int err; -X v = sysget("ps1"); -X w = sysget("ps2"); -X if (v != NULL && is_stringobject(v)) { -X INCREF(v); -X ps1 = getstringvalue(v); -X } -X else { -X v = NULL; -X ps1 = ""; -X } -X if (w != NULL && is_stringobject(w)) { -X INCREF(w); -X ps2 = getstringvalue(w); -X } -X else { -X w = NULL; -X ps2 = ""; -X } -X err = parsefile(fp, filename, &gram, single_input, ps1, ps2, &n); -X XDECREF(v); -X XDECREF(w); -X if (err == E_EOF) -X return E_EOF; -X if (err != E_DONE) { -X err_input(err); -X print_error(); -X return err; -X } -X m = add_module("__main__"); -X if (m == NULL) -X return -1; -X d = getmoduledict(m); -X v = run_node(n, filename, d, d); -X flushline(); -X if (v == NULL) { -X print_error(); -X return -1; -X } -X DECREF(v); -X return 0; +X FILE *fp; +X char *filename; +X{ +X object *m, *d, *v, *w; +X node *n; +X char *ps1, *ps2; +X int err; +X v = sysget("ps1"); +X w = sysget("ps2"); +X if (v != NULL && is_stringobject(v)) { +X INCREF(v); +X ps1 = getstringvalue(v); +X } +X else { +X v = NULL; +X ps1 = ""; +X } +X if (w != NULL && is_stringobject(w)) { +X INCREF(w); +X ps2 = getstringvalue(w); +X } +X else { +X w = NULL; +X ps2 = ""; +X } +X err = parsefile(fp, filename, &gram, single_input, ps1, ps2, &n); +X XDECREF(v); +X XDECREF(w); +X if (err == E_EOF) +X return E_EOF; +X if (err != E_DONE) { +X err_input(err); +X print_error(); +X return err; +X } +X m = add_module("__main__"); +X if (m == NULL) +X return -1; +X d = getmoduledict(m); +X v = run_node(n, filename, d, d); +X flushline(); +X if (v == NULL) { +X print_error(); +X return -1; +X } +X DECREF(v); +X return 0; X} X Xint Xrun_script(fp, filename) -X FILE *fp; -X char *filename; -X{ -X object *m, *d, *v; -X m = add_module("__main__"); -X if (m == NULL) -X return -1; -X d = getmoduledict(m); -X v = run_file(fp, filename, file_input, d, d); -X flushline(); -X if (v == NULL) { -X print_error(); -X return -1; -X } -X DECREF(v); -X return 0; +X FILE *fp; +X char *filename; +X{ +X object *m, *d, *v; +X m = add_module("__main__"); +X if (m == NULL) +X return -1; +X d = getmoduledict(m); +X v = run_file(fp, filename, file_input, d, d); +X flushline(); +X if (v == NULL) { +X print_error(); +X return -1; +X } +X DECREF(v); +X return 0; X} X Xvoid Xprint_error() X{ -X object *exception, *v; -X err_get(&exception, &v); -X fprintf(stderr, "Unhandled exception: "); -X printobject(exception, stderr, PRINT_RAW); -X if (v != NULL && v != None) { -X fprintf(stderr, ": "); -X printobject(v, stderr, PRINT_RAW); -X } -X fprintf(stderr, "\n"); -X XDECREF(exception); -X XDECREF(v); -X printtraceback(stderr); +X object *exception, *v; +X err_get(&exception, &v); +X fprintf(stderr, "Unhandled exception: "); +X printobject(exception, stderr, PRINT_RAW); +X if (v != NULL && v != None) { +X fprintf(stderr, ": "); +X printobject(v, stderr, PRINT_RAW); +X } +X fprintf(stderr, "\n"); +X XDECREF(exception); +X XDECREF(v); +X printtraceback(stderr); X} X Xobject * Xrun_string(str, start, globals, locals) -X char *str; -X int start; -X /*dict*/object *globals, *locals; +X char *str; +X int start; +X /*dict*/object *globals, *locals; X{ -X node *n; -X int err; -X err = parse_string(str, start, &n); -X return run_err_node(err, n, "<string>", globals, locals); +X node *n; +X int err; +X err = parse_string(str, start, &n); +X return run_err_node(err, n, "<string>", globals, locals); X} X Xobject * Xrun_file(fp, filename, start, globals, locals) -X FILE *fp; -X char *filename; -X int start; -X /*dict*/object *globals, *locals; +X FILE *fp; +X char *filename; +X int start; +X /*dict*/object *globals, *locals; X{ -X node *n; -X int err; -X err = parse_file(fp, filename, start, &n); -X return run_err_node(err, n, filename, globals, locals); +X node *n; +X int err; +X err = parse_file(fp, filename, start, &n); +X return run_err_node(err, n, filename, globals, locals); X} X Xobject * Xrun_err_node(err, n, filename, globals, locals) -X int err; -X node *n; -X char *filename; -X /*dict*/object *globals, *locals; +X int err; +X node *n; +X char *filename; +X /*dict*/object *globals, *locals; X{ -X if (err != E_DONE) { -X err_input(err); -X return NULL; -X } -X return run_node(n, filename, globals, locals); +X if (err != E_DONE) { +X err_input(err); +X return NULL; +X } +X return run_node(n, filename, globals, locals); X} X Xobject * Xrun_node(n, filename, globals, locals) -X node *n; -X char *filename; -X /*dict*/object *globals, *locals; -X{ -X if (globals == NULL) { -X globals = getglobals(); -X if (locals == NULL) -X locals = getlocals(); -X } -X else { -X if (locals == NULL) -X locals = globals; -X } -X return eval_node(n, filename, globals, locals); +X node *n; +X char *filename; +X /*dict*/object *globals, *locals; +X{ +X if (globals == NULL) { +X globals = getglobals(); +X if (locals == NULL) +X locals = getlocals(); +X } +X else { +X if (locals == NULL) +X locals = globals; +X } +X return eval_node(n, filename, globals, locals); X} X Xobject * Xeval_node(n, filename, globals, locals) -X node *n; -X char *filename; -X object *globals; -X object *locals; -X{ -X codeobject *co; -X object *v; -X co = compile(n, filename); -X freetree(n); -X if (co == NULL) -X return NULL; -X v = eval_code(co, globals, locals, (object *)NULL); -X DECREF(co); -X return v; +X node *n; +X char *filename; +X object *globals; +X object *locals; +X{ +X codeobject *co; +X object *v; +X co = compile(n, filename); +X freetree(n); +X if (co == NULL) +X return NULL; +X v = eval_code(co, globals, locals, (object *)NULL); +X DECREF(co); +X return v; X} X X/* Simplified interface to parsefile */ X Xint Xparse_file(fp, filename, start, n_ret) -X FILE *fp; -X char *filename; -X int start; -X node **n_ret; +X FILE *fp; +X char *filename; +X int start; +X node **n_ret; X{ -X return parsefile(fp, filename, &gram, start, -X (char *)0, (char *)0, n_ret); +X return parsefile(fp, filename, &gram, start, +X (char *)0, (char *)0, n_ret); X} X X/* Simplified interface to parsestring */ X Xint Xparse_string(str, start, n_ret) -X char *str; -X int start; -X node **n_ret; +X char *str; +X int start; +X node **n_ret; X{ -X int err = parsestring(str, &gram, start, n_ret); -X /* Don't confuse early end of string with early end of input */ -X if (err == E_EOF) -X err = E_SYNTAX; -X return err; +X int err = parsestring(str, &gram, start, n_ret); +X /* Don't confuse early end of string with early end of input */ +X if (err == E_EOF) +X err = E_SYNTAX; +X return err; X} X X/* Print fatal error message and abort */ X Xvoid Xfatal(msg) -X char *msg; +X char *msg; X{ -X fprintf(stderr, "Fatal error: %s\n", msg); -X abort(); +X fprintf(stderr, "Fatal error: %s\n", msg); +X abort(); X} X X/* Clean up and exit */ X Xvoid Xgoaway(sts) -X int sts; +X int sts; X{ -X flushline(); -X -X /* XXX Call doneimport() before donecalls(), since donecalls() -X calls wdone(), and doneimport() may close windows */ -X doneimport(); -X donecalls(); -X -X err_clear(); +X flushline(); +X +X /* XXX Call doneimport() before donecalls(), since donecalls() +X calls wdone(), and doneimport() may close windows */ +X doneimport(); +X donecalls(); +X +X err_clear(); X X#ifdef REF_DEBUG -X fprintf(stderr, "[%ld refs]\n", ref_total); +X fprintf(stderr, "[%ld refs]\n", ref_total); X#endif X X#ifdef THINK_C_3_0 -X if (sts == 0) -X Click_On(0); +X if (sts == 0) +X Click_On(0); X#endif X X#ifdef TRACE_REFS -X if (askyesno("Print left references?")) { +X if (askyesno("Print left references?")) { X#ifdef THINK_C_3_0 -X Click_On(1); +X Click_On(1); X#endif -X printrefs(stderr); -X } +X printrefs(stderr); +X } X#endif /* TRACE_REFS */ X -X exit(sts); -X /*NOTREACHED*/ +X exit(sts); +X /*NOTREACHED*/ X} X Xstatic Xfinaloutput() X{ X#ifdef TRACE_REFS -X if (!askyesno("Print left references?")) -X return; +X if (!askyesno("Print left references?")) +X return; X#ifdef THINK_C_3_0 -X Click_On(1); +X Click_On(1); X#endif -X printrefs(stderr); +X printrefs(stderr); X#endif /* TRACE_REFS */ X} X @@ -2438,38 +2438,38 @@ X/* Ask a yes/no question */ X Xstatic int Xaskyesno(prompt) -X char *prompt; +X char *prompt; X{ -X char buf[256]; -X -X printf("%s [ny] ", prompt); -X if (fgets(buf, sizeof buf, stdin) == NULL) -X return 0; -X return buf[0] == 'y' || buf[0] == 'Y'; +X char buf[256]; +X +X printf("%s [ny] ", prompt); +X if (fgets(buf, sizeof buf, stdin) == NULL) +X return 0; +X return buf[0] == 'y' || buf[0] == 'Y'; X} X X#ifdef THINK_C_3_0 X X/* Check for file descriptor connected to interactive device. -X Pretend that stdin is always interactive, other files never. */ +X Pretend that stdin is always interactive, other files never. */ X Xint Xisatty(fd) -X int fd; +X int fd; X{ -X return fd == fileno(stdin); +X return fd == fileno(stdin); X} X X#endif X -X/* XXX WISH LIST +X/* XXX WISH LIST X -X - possible new types: -X - iterator (for range, keys, ...) -X - improve interpreter error handling, e.g., true tracebacks -X - save precompiled modules on file? -X - fork threads, locking -X - allow syntax extensions +X - possible new types: +X - iterator (for range, keys, ...) +X - improve interpreter error handling, e.g., true tracebacks +X - save precompiled modules on file? +X - fork threads, locking +X - allow syntax extensions X*/ X X/* "Floccinaucinihilipilification" */ @@ -2484,12 +2484,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2510,324 +2510,324 @@ X#include "allobjects.h" X Xobject * Xnewsizedstringobject(str, size) -X char *str; -X int size; -X{ -X register stringobject *op = (stringobject *) -X malloc(sizeof(stringobject) + size * sizeof(char)); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = &Stringtype; -X op->ob_size = size; -X if (str != NULL) -X memcpy(op->ob_sval, str, size); -X op->ob_sval[size] = '\0'; -X return (object *) op; +X char *str; +X int size; +X{ +X register stringobject *op = (stringobject *) +X malloc(sizeof(stringobject) + size * sizeof(char)); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = &Stringtype; +X op->ob_size = size; +X if (str != NULL) +X memcpy(op->ob_sval, str, size); +X op->ob_sval[size] = '\0'; +X return (object *) op; X} X Xobject * Xnewstringobject(str) -X char *str; +X char *str; X{ -X register unsigned int size = strlen(str); -X register stringobject *op = (stringobject *) -X malloc(sizeof(stringobject) + size * sizeof(char)); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = &Stringtype; -X op->ob_size = size; -X strcpy(op->ob_sval, str); -X return (object *) op; +X register unsigned int size = strlen(str); +X register stringobject *op = (stringobject *) +X malloc(sizeof(stringobject) + size * sizeof(char)); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = &Stringtype; +X op->ob_size = size; +X strcpy(op->ob_sval, str); +X return (object *) op; X} X Xunsigned int Xgetstringsize(op) -X register object *op; +X register object *op; X{ -X if (!is_stringobject(op)) { -X err_badcall(); -X return -1; -X } -X return ((stringobject *)op) -> ob_size; +X if (!is_stringobject(op)) { +X err_badcall(); +X return -1; +X } +X return ((stringobject *)op) -> ob_size; X} X X/*const*/ char * Xgetstringvalue(op) -X register object *op; +X register object *op; X{ -X if (!is_stringobject(op)) { -X err_badcall(); -X return NULL; -X } -X return ((stringobject *)op) -> ob_sval; +X if (!is_stringobject(op)) { +X err_badcall(); +X return NULL; +X } +X return ((stringobject *)op) -> ob_sval; X} X X/* Methods */ X Xstatic void Xstringprint(op, fp, flags) -X stringobject *op; -X FILE *fp; -X int flags; -X{ -X int i; -X char c; -X if (flags & PRINT_RAW) { -X fwrite(op->ob_sval, 1, (int) op->ob_size, fp); -X return; -X } -X fprintf(fp, "'"); -X for (i = 0; i < op->ob_size; i++) { -X c = op->ob_sval[i]; -X if (c == '\'' || c == '\\') -X fprintf(fp, "\\%c", c); -X else if (c < ' ' || c >= 0177) -X fprintf(fp, "\\%03o", c&0377); -X else -X putc(c, fp); -X } -X fprintf(fp, "'"); +X stringobject *op; +X FILE *fp; +X int flags; +X{ +X int i; +X char c; +X if (flags & PRINT_RAW) { +X fwrite(op->ob_sval, 1, (int) op->ob_size, fp); +X return; +X } +X fprintf(fp, "'"); +X for (i = 0; i < op->ob_size; i++) { +X c = op->ob_sval[i]; +X if (c == '\'' || c == '\\') +X fprintf(fp, "\\%c", c); +X else if (c < ' ' || c >= 0177) +X fprintf(fp, "\\%03o", c&0377); +X else +X putc(c, fp); +X } +X fprintf(fp, "'"); X} X Xstatic object * Xstringrepr(op) -X register stringobject *op; -X{ -X /* XXX overflow? */ -X int newsize = 2 + 4 * op->ob_size * sizeof(char); -X object *v = newsizedstringobject((char *)NULL, newsize); -X if (v == NULL) { -X return err_nomem(); -X } -X else { -X register int i; -X register char c; -X register char *p; -X NEWREF(v); -X v->ob_type = &Stringtype; -X ((stringobject *)v)->ob_size = newsize; -X p = ((stringobject *)v)->ob_sval; -X *p++ = '\''; -X for (i = 0; i < op->ob_size; i++) { -X c = op->ob_sval[i]; -X if (c == '\'' || c == '\\') -X *p++ = '\\', *p++ = c; -X else if (c < ' ' || c >= 0177) { -X sprintf(p, "\\%03o", c&0377); -X while (*p != '\0') -X p++; -X -X } -X else -X *p++ = c; -X } -X *p++ = '\''; -X *p = '\0'; -X resizestring(&v, (int) (p - ((stringobject *)v)->ob_sval)); -X return v; -X } +X register stringobject *op; +X{ +X /* XXX overflow? */ +X int newsize = 2 + 4 * op->ob_size * sizeof(char); +X object *v = newsizedstringobject((char *)NULL, newsize); +X if (v == NULL) { +X return err_nomem(); +X } +X else { +X register int i; +X register char c; +X register char *p; +X NEWREF(v); +X v->ob_type = &Stringtype; +X ((stringobject *)v)->ob_size = newsize; +X p = ((stringobject *)v)->ob_sval; +X *p++ = '\''; +X for (i = 0; i < op->ob_size; i++) { +X c = op->ob_sval[i]; +X if (c == '\'' || c == '\\') +X *p++ = '\\', *p++ = c; +X else if (c < ' ' || c >= 0177) { +X sprintf(p, "\\%03o", c&0377); +X while (*p != '\0') +X p++; +X +X } +X else +X *p++ = c; +X } +X *p++ = '\''; +X *p = '\0'; +X resizestring(&v, (int) (p - ((stringobject *)v)->ob_sval)); +X return v; +X } X} X Xstatic int Xstringlength(a) -X stringobject *a; +X stringobject *a; X{ -X return a->ob_size; +X return a->ob_size; X} X Xstatic object * Xstringconcat(a, bb) -X register stringobject *a; -X register object *bb; -X{ -X register unsigned int size; -X register stringobject *op; -X if (!is_stringobject(bb)) { -X err_badarg(); -X return NULL; -X } +X register stringobject *a; +X register object *bb; +X{ +X register unsigned int size; +X register stringobject *op; +X if (!is_stringobject(bb)) { +X err_badarg(); +X return NULL; +X } X#define b ((stringobject *)bb) -X /* Optimize cases with empty left or right operand */ -X if (a->ob_size == 0) { -X INCREF(bb); -X return bb; -X } -X if (b->ob_size == 0) { -X INCREF(a); -X return (object *)a; -X } -X size = a->ob_size + b->ob_size; -X op = (stringobject *) -X malloc(sizeof(stringobject) + size * sizeof(char)); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = &Stringtype; -X op->ob_size = size; -X memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size); -X memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size); -X op->ob_sval[size] = '\0'; -X return (object *) op; +X /* Optimize cases with empty left or right operand */ +X if (a->ob_size == 0) { +X INCREF(bb); +X return bb; +X } +X if (b->ob_size == 0) { +X INCREF(a); +X return (object *)a; +X } +X size = a->ob_size + b->ob_size; +X op = (stringobject *) +X malloc(sizeof(stringobject) + size * sizeof(char)); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = &Stringtype; +X op->ob_size = size; +X memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size); +X memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size); +X op->ob_sval[size] = '\0'; +X return (object *) op; X#undef b X} X Xstatic object * Xstringrepeat(a, n) -X register stringobject *a; -X register int n; -X{ -X register int i; -X register unsigned int size; -X register stringobject *op; -X if (n < 0) -X n = 0; -X size = a->ob_size * n; -X if (size == a->ob_size) { -X INCREF(a); -X return (object *)a; -X } -X op = (stringobject *) -X malloc(sizeof(stringobject) + size * sizeof(char)); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = &Stringtype; -X op->ob_size = size; -X for (i = 0; i < size; i += a->ob_size) -X memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size); -X op->ob_sval[size] = '\0'; -X return (object *) op; +X register stringobject *a; +X register int n; +X{ +X register int i; +X register unsigned int size; +X register stringobject *op; +X if (n < 0) +X n = 0; +X size = a->ob_size * n; +X if (size == a->ob_size) { +X INCREF(a); +X return (object *)a; +X } +X op = (stringobject *) +X malloc(sizeof(stringobject) + size * sizeof(char)); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = &Stringtype; +X op->ob_size = size; +X for (i = 0; i < size; i += a->ob_size) +X memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size); +X op->ob_sval[size] = '\0'; +X return (object *) op; X} X X/* String slice a[i:j] consists of characters a[i] ... a[j-1] */ X Xstatic object * Xstringslice(a, i, j) -X register stringobject *a; -X register int i, j; /* May be negative! */ -X{ -X if (i < 0) -X i = 0; -X if (j < 0) -X j = 0; /* Avoid signed/unsigned bug in next line */ -X if (j > a->ob_size) -X j = a->ob_size; -X if (i == 0 && j == a->ob_size) { /* It's the same as a */ -X INCREF(a); -X return (object *)a; -X } -X if (j < i) -X j = i; -X return newsizedstringobject(a->ob_sval + i, (int) (j-i)); +X register stringobject *a; +X register int i, j; /* May be negative! */ +X{ +X if (i < 0) +X i = 0; +X if (j < 0) +X j = 0; /* Avoid signed/unsigned bug in next line */ +X if (j > a->ob_size) +X j = a->ob_size; +X if (i == 0 && j == a->ob_size) { /* It's the same as a */ +X INCREF(a); +X return (object *)a; +X } +X if (j < i) +X j = i; +X return newsizedstringobject(a->ob_sval + i, (int) (j-i)); X} X Xstatic object * Xstringitem(a, i) -X stringobject *a; -X register int i; +X stringobject *a; +X register int i; X{ -X if (i < 0 || i >= a->ob_size) { -X err_setstr(IndexError, "string index out of range"); -X return NULL; -X } -X return stringslice(a, i, i+1); +X if (i < 0 || i >= a->ob_size) { +X err_setstr(IndexError, "string index out of range"); +X return NULL; +X } +X return stringslice(a, i, i+1); X} X Xstatic int Xstringcompare(a, b) -X stringobject *a, *b; +X stringobject *a, *b; X{ -X int len_a = a->ob_size, len_b = b->ob_size; -X int min_len = (len_a < len_b) ? len_a : len_b; -X int cmp = memcmp(a->ob_sval, b->ob_sval, min_len); -X if (cmp != 0) -X return cmp; -X return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; +X int len_a = a->ob_size, len_b = b->ob_size; +X int min_len = (len_a < len_b) ? len_a : len_b; +X int cmp = memcmp(a->ob_sval, b->ob_sval, min_len); +X if (cmp != 0) +X return cmp; +X return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; X} X Xstatic sequence_methods string_as_sequence = { -X stringlength, /*tp_length*/ -X stringconcat, /*tp_concat*/ -X stringrepeat, /*tp_repeat*/ -X stringitem, /*tp_item*/ -X stringslice, /*tp_slice*/ -X 0, /*tp_ass_item*/ -X 0, /*tp_ass_slice*/ +X stringlength, /*tp_length*/ +X stringconcat, /*tp_concat*/ +X stringrepeat, /*tp_repeat*/ +X stringitem, /*tp_item*/ +X stringslice, /*tp_slice*/ +X 0, /*tp_ass_item*/ +X 0, /*tp_ass_slice*/ X}; X Xtypeobject Stringtype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "string", -X sizeof(stringobject), -X sizeof(char), -X free, /*tp_dealloc*/ -X stringprint, /*tp_print*/ -X 0, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X stringcompare, /*tp_compare*/ -X stringrepr, /*tp_repr*/ -X 0, /*tp_as_number*/ -X &string_as_sequence, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "string", +X sizeof(stringobject), +X sizeof(char), +X free, /*tp_dealloc*/ +X stringprint, /*tp_print*/ +X 0, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X stringcompare, /*tp_compare*/ +X stringrepr, /*tp_repr*/ +X 0, /*tp_as_number*/ +X &string_as_sequence, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X Xvoid Xjoinstring(pv, w) -X register object **pv; -X register object *w; +X register object **pv; +X register object *w; X{ -X register object *v; -X if (*pv == NULL || w == NULL || !is_stringobject(*pv)) -X return; -X v = stringconcat((stringobject *) *pv, w); -X DECREF(*pv); -X *pv = v; +X register object *v; +X if (*pv == NULL || w == NULL || !is_stringobject(*pv)) +X return; +X v = stringconcat((stringobject *) *pv, w); +X DECREF(*pv); +X *pv = v; X} X X/* The following function breaks the notion that strings are immutable: -X it changes the size of a string. We get away with this only if there -X is only one module referencing the object. You can also think of it -X as creating a new string object and destroying the old one, only -X more efficiently. In any case, don't use this if the string may -X already be known to some other part of the code... */ +X it changes the size of a string. We get away with this only if there +X is only one module referencing the object. You can also think of it +X as creating a new string object and destroying the old one, only +X more efficiently. In any case, don't use this if the string may +X already be known to some other part of the code... */ X Xint Xresizestring(pv, newsize) -X object **pv; -X int newsize; -X{ -X register object *v; -X register stringobject *sv; -X v = *pv; -X if (!is_stringobject(v) || v->ob_refcnt != 1) { -X *pv = 0; -X DECREF(v); -X err_badcall(); -X return -1; -X } -X /* XXX UNREF/NEWREF interface should be more symmetrical */ +X object **pv; +X int newsize; +X{ +X register object *v; +X register stringobject *sv; +X v = *pv; +X if (!is_stringobject(v) || v->ob_refcnt != 1) { +X *pv = 0; +X DECREF(v); +X err_badcall(); +X return -1; +X } +X /* XXX UNREF/NEWREF interface should be more symmetrical */ X#ifdef REF_DEBUG -X --ref_total; +X --ref_total; X#endif -X UNREF(v); -X *pv = (object *) -X realloc((char *)v, -X sizeof(stringobject) + newsize * sizeof(char)); -X if (*pv == NULL) { -X DEL(v); -X err_nomem(); -X return -1; -X } -X NEWREF(*pv); -X sv = (stringobject *) *pv; -X sv->ob_size = newsize; -X sv->ob_sval[newsize] = '\0'; -X return 0; +X UNREF(v); +X *pv = (object *) +X realloc((char *)v, +X sizeof(stringobject) + newsize * sizeof(char)); +X if (*pv == NULL) { +X DEL(v); +X err_nomem(); +X return -1; +X } +X NEWREF(*pv); +X sv = (stringobject *) *pv; +X sv->ob_size = newsize; +X sv->ob_sval[newsize] = '\0'; +X return 0; X} EOF fi echo 'Part 12 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-13-21.shar b/shar/python-0.9.1-13-21.shar index 1d0e2ec..9f43ada 100644 --- a/shar/python-0.9.1-13-21.shar +++ b/shar/python-0.9.1-13-21.shar @@ -13,8 +13,8 @@ X X# JUKEBOX: browse directories full of sampled sound files. X# X# One or more "list windows" display the files and subdirectories of -X# the arguments. Double-clicking on a subdirectory opens a new window -X# displaying its contents (and so on recursively). Double clicking +X# the arguments. Double-clicking on a subdirectory opens a new window +X# displaying its contents (and so on recursively). Double clicking X# on a file plays it as a sound file (assuming it is one). X# X# Playing is asynchronous: the application keeps listening to events @@ -26,7 +26,7 @@ X# "stop button" to cancel the current play request. X# X# Sound files must currently be in Dik Winter's compressed Mac format. X# Since decompression is costly, decompressed samples are saved in -X# /usr/tmp/@j* until the application is left. The files are read +X# /usr/tmp/@j* until the application is left. The files are read X# afresh each time, though. X Ximport audio @@ -48,205 +48,205 @@ Xfrom Sliders import ComplexSlider X X# Pathnames X -XHOME_BIN_SGI = '/ufs/guido/bin/sgi/' # Directory where macsound2sgi lives -XDEF_DB = '/ufs/dik/sounds/Mac/HCOM' # Default directory of sounds +XHOME_BIN_SGI = '/ufs/guido/bin/sgi/' # Directory where macsound2sgi lives +XDEF_DB = '/ufs/dik/sounds/Mac/HCOM' # Default directory of sounds X X X# Global variables X -Xclass struct(): pass # Class to define featureless structures +Xclass struct(): pass # Class to define featureless structures X -XG = struct() # Holds writable global variables +XG = struct() # Holds writable global variables X X X# Main program X Xdef main(): -X G.synchronous = 0 # If set, use synchronous audio.write() -X G.debug = 0 # If set, print debug messages -X G.gain = 75 # Output gain -X G.rate = 3 # Sampling rate -X G.busy = 0 # Set while asynchronous playing is active -X G.windows = [] # List of open windows (except control) -X G.mode = 'mac' # Macintosh mode -X G.tempprefix = '/usr/tmp/@j' + `rand.rand()` + '-' -X # -X optlist, args = getopt.getopt(sys.argv[1:], 'dg:r:sSa') -X for optname, optarg in optlist: -X if optname = '-d': -X G.debug = 1 -X elif optname = '-g': -X G.gain = string.atoi(optarg) -X if not (0 < G.gain < 256): -X raise optarg.error, '-g gain out of range' -X elif optname = '-r': -X G.rate = string.atoi(optarg) -X if not (1 <= G.rate <= 3): -X raise optarg.error, '-r rate out of range' -X elif optname = '-s': -X G.synchronous = 1 -X elif optname = '-S': -X G.mode = 'sgi' -X elif optname = '-a': -X G.mode = 'sun' -X # -X if not args: -X args = [DEF_DB] -X # -X G.cw = opencontrolwindow() -X for dirname in args: -X G.windows.append(openlistwindow(dirname)) -X # -X # -X savegain = audio.getoutgain() -X try: -X # Initialize stdaudio -X audio.setoutgain(0) -X audio.start_playing('') -X dummy = audio.wait_playing() -X audio.setoutgain(0) -X maineventloop() -X finally: -X audio.setoutgain(savegain) -X audio.done() -X clearcache() +X G.synchronous = 0 # If set, use synchronous audio.write() +X G.debug = 0 # If set, print debug messages +X G.gain = 75 # Output gain +X G.rate = 3 # Sampling rate +X G.busy = 0 # Set while asynchronous playing is active +X G.windows = [] # List of open windows (except control) +X G.mode = 'mac' # Macintosh mode +X G.tempprefix = '/usr/tmp/@j' + `rand.rand()` + '-' +X # +X optlist, args = getopt.getopt(sys.argv[1:], 'dg:r:sSa') +X for optname, optarg in optlist: +X if optname = '-d': +X G.debug = 1 +X elif optname = '-g': +X G.gain = string.atoi(optarg) +X if not (0 < G.gain < 256): +X raise optarg.error, '-g gain out of range' +X elif optname = '-r': +X G.rate = string.atoi(optarg) +X if not (1 <= G.rate <= 3): +X raise optarg.error, '-r rate out of range' +X elif optname = '-s': +X G.synchronous = 1 +X elif optname = '-S': +X G.mode = 'sgi' +X elif optname = '-a': +X G.mode = 'sun' +X # +X if not args: +X args = [DEF_DB] +X # +X G.cw = opencontrolwindow() +X for dirname in args: +X G.windows.append(openlistwindow(dirname)) +X # +X # +X savegain = audio.getoutgain() +X try: +X # Initialize stdaudio +X audio.setoutgain(0) +X audio.start_playing('') +X dummy = audio.wait_playing() +X audio.setoutgain(0) +X maineventloop() +X finally: +X audio.setoutgain(savegain) +X audio.done() +X clearcache() X Xdef maineventloop(): -X mouse_events = WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP -X while G.windows: -X type, w, detail = event = stdwin.getevent() -X if w = G.cw.win: -X if type = WE_CLOSE: -X return -X G.cw.dispatch(event) -X else: -X if type = WE_DRAW: -X w.drawproc(w, detail) -X elif type in mouse_events: -X w.mouse(w, type, detail) -X elif type = WE_CLOSE: -X w.close(w) -X del w, event -X else: -X if G.debug: print type, w, detail +X mouse_events = WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP +X while G.windows: +X type, w, detail = event = stdwin.getevent() +X if w = G.cw.win: +X if type = WE_CLOSE: +X return +X G.cw.dispatch(event) +X else: +X if type = WE_DRAW: +X w.drawproc(w, detail) +X elif type in mouse_events: +X w.mouse(w, type, detail) +X elif type = WE_CLOSE: +X w.close(w) +X del w, event +X else: +X if G.debug: print type, w, detail X X# Control window -- to set gain and cancel play operations in progress X Xdef opencontrolwindow(): -X cw = WindowParent().create('Jukebox', (0, 0)) -X v = VSplit().create(cw) -X # -X gain = ComplexSlider().define(v) -X gain.setminvalmax(0, G.gain, 255) -X gain.settexts(' ', ' ') -X gain.sethook(gain_setval_hook) -X # -X stop = PushButton().definetext(v, 'Stop') -X stop.hook = stop_hook -X # -X cw.realize() -X return cw +X cw = WindowParent().create('Jukebox', (0, 0)) +X v = VSplit().create(cw) +X # +X gain = ComplexSlider().define(v) +X gain.setminvalmax(0, G.gain, 255) +X gain.settexts(' ', ' ') +X gain.sethook(gain_setval_hook) +X # +X stop = PushButton().definetext(v, 'Stop') +X stop.hook = stop_hook +X # +X cw.realize() +X return cw X Xdef gain_setval_hook(self): -X G.gain = self.val -X if G.busy: audio.setoutgain(G.gain) +X G.gain = self.val +X if G.busy: audio.setoutgain(G.gain) X Xdef stop_hook(self): -X if G.busy: -X audio.setoutgain(0) -X dummy = audio.stop_playing() -X G.busy = 0 +X if G.busy: +X audio.setoutgain(0) +X dummy = audio.stop_playing() +X G.busy = 0 X X X# List windows -- to display list of files and subdirectories X Xdef openlistwindow(dirname): -X list = posix.listdir(dirname) -X list.sort() -X i = 0 -X while i < len(list): -X if list[i] = '.' or list[i] = '..': -X del list[i] -X else: -X i = i+1 -X for i in range(len(list)): -X name = list[i] -X if path.isdir(path.cat(dirname, name)): -X list[i] = list[i] + '/' -X width = maxwidth(list) -X width = width + stdwin.textwidth(' ') # XXX X11 stdwin bug workaround -X height = len(list) * stdwin.lineheight() -X stdwin.setdefwinsize(width, min(height, 500)) -X w = stdwin.open(dirname) -X stdwin.setdefwinsize(0, 0) -X w.setdocsize(width, height) -X w.drawproc = drawlistwindow -X w.mouse = mouselistwindow -X w.close = closelistwindow -X w.dirname = dirname -X w.list = list -X w.selected = -1 -X return w +X list = posix.listdir(dirname) +X list.sort() +X i = 0 +X while i < len(list): +X if list[i] = '.' or list[i] = '..': +X del list[i] +X else: +X i = i+1 +X for i in range(len(list)): +X name = list[i] +X if path.isdir(path.cat(dirname, name)): +X list[i] = list[i] + '/' +X width = maxwidth(list) +X width = width + stdwin.textwidth(' ') # XXX X11 stdwin bug workaround +X height = len(list) * stdwin.lineheight() +X stdwin.setdefwinsize(width, min(height, 500)) +X w = stdwin.open(dirname) +X stdwin.setdefwinsize(0, 0) +X w.setdocsize(width, height) +X w.drawproc = drawlistwindow +X w.mouse = mouselistwindow +X w.close = closelistwindow +X w.dirname = dirname +X w.list = list +X w.selected = -1 +X return w X Xdef maxwidth(list): -X width = 1 -X for name in list: -X w = stdwin.textwidth(name) -X if w > width: width = w -X return width +X width = 1 +X for name in list: +X w = stdwin.textwidth(name) +X if w > width: width = w +X return width X Xdef drawlistwindow(w, area): -X d = w.begindrawing() -X d.erase((0, 0), (1000, 10000)) -X lh = d.lineheight() -X h, v = 0, 0 -X for name in w.list: -X d.text((h, v), name) -X v = v + lh -X showselection(w, d) +X d = w.begindrawing() +X d.erase((0, 0), (1000, 10000)) +X lh = d.lineheight() +X h, v = 0, 0 +X for name in w.list: +X d.text((h, v), name) +X v = v + lh +X showselection(w, d) X Xdef hideselection(w, d): -X if w.selected >= 0: -X invertselection(w, d) +X if w.selected >= 0: +X invertselection(w, d) X Xdef showselection(w, d): -X if w.selected >= 0: -X invertselection(w, d) +X if w.selected >= 0: +X invertselection(w, d) X Xdef invertselection(w, d): -X lh = d.lineheight() -X h1, v1 = p1 = 0, w.selected*lh -X h2, v2 = p2 = 1000, v1 + lh -X d.invert(p1, p2) +X lh = d.lineheight() +X h1, v1 = p1 = 0, w.selected*lh +X h2, v2 = p2 = 1000, v1 + lh +X d.invert(p1, p2) X Xdef mouselistwindow(w, type, detail): -X (h, v), clicks, button = detail[:3] -X d = w.begindrawing() -X lh = d.lineheight() -X if 0 <= v < lh*len(w.list): -X i = v / lh -X else: -X i = -1 -X if w.selected <> i: -X hideselection(w, d) -X w.selected = i -X showselection(w, d) -X if type = WE_MOUSE_DOWN and clicks >= 2 and i >= 0: -X name = path.cat(w.dirname, w.list[i]) -X if name[-1:] = '/': -X if clicks = 2: -X G.windows.append(openlistwindow(name[:-1])) -X else: -X playfile(name) +X (h, v), clicks, button = detail[:3] +X d = w.begindrawing() +X lh = d.lineheight() +X if 0 <= v < lh*len(w.list): +X i = v / lh +X else: +X i = -1 +X if w.selected <> i: +X hideselection(w, d) +X w.selected = i +X showselection(w, d) +X if type = WE_MOUSE_DOWN and clicks >= 2 and i >= 0: +X name = path.cat(w.dirname, w.list[i]) +X if name[-1:] = '/': +X if clicks = 2: +X G.windows.append(openlistwindow(name[:-1])) +X else: +X playfile(name) X Xdef closelistwindow(w): -X remove(G.windows, w) +X remove(G.windows, w) X Xdef remove(list, item): -X for i in range(len(list)): -X if list[i] = item: -X del list[i] -X break +X for i in range(len(list)): +X if list[i] = item: +X del list[i] +X break X X X# Playing tools @@ -254,79 +254,79 @@ X Xcache = {} X Xdef clearcache(): -X for x in cache.keys(): -X try: -X sts = posix.system('rm -f ' + cache[x]) -X if sts: -X print cmd -X print 'Exit status', sts -X except: -X print cmd -X print 'Exception?!' -X del cache[x] +X for x in cache.keys(): +X try: +X sts = posix.system('rm -f ' + cache[x]) +X if sts: +X print cmd +X print 'Exit status', sts +X except: +X print cmd +X print 'Exception?!' +X del cache[x] X Xdef playfile(name): -X if G.mode <> 'mac': -X tempname = name -X elif cache.has_key(name): -X tempname = cache[name] -X else: -X tempname = G.tempprefix + `rand.rand()` -X cmd = HOME_BIN_SGI + 'macsound2sgi' -X cmd = cmd + ' ' + commands.mkarg(name) -X cmd = cmd + ' >' + tempname -X if G.debug: print cmd -X sts = posix.system(cmd) -X if sts: -X print cmd -X print 'Exit status', sts -X stdwin.fleep() -X return -X cache[name] = tempname -X fp = open(tempname, 'r') -X try: -X hdr = sunaudio.gethdr(fp) -X except sunaudio.error, msg: -X hdr = () -X if hdr: -X data_size = hdr[0] -X data = fp.read(data_size) -X # XXX this doesn't work yet, need to convert from uLAW!!! -X del fp -X else: -X del fp -X data = readfile(tempname) -X if G.debug: print len(data), 'bytes read from', tempname -X if G.busy: -X G.busy = 0 -X dummy = audio.stop_playing() -X # -X # Completely reset the audio device -X audio.setrate(G.rate) -X audio.setduration(0) -X audio.setoutgain(G.gain) -X # -X if G.synchronous: -X audio.write(data) -X audio.setoutgain(0) -X else: -X try: -X audio.start_playing(data) -X G.busy = 1 -X except: -X stdwin.fleep() -X del data +X if G.mode <> 'mac': +X tempname = name +X elif cache.has_key(name): +X tempname = cache[name] +X else: +X tempname = G.tempprefix + `rand.rand()` +X cmd = HOME_BIN_SGI + 'macsound2sgi' +X cmd = cmd + ' ' + commands.mkarg(name) +X cmd = cmd + ' >' + tempname +X if G.debug: print cmd +X sts = posix.system(cmd) +X if sts: +X print cmd +X print 'Exit status', sts +X stdwin.fleep() +X return +X cache[name] = tempname +X fp = open(tempname, 'r') +X try: +X hdr = sunaudio.gethdr(fp) +X except sunaudio.error, msg: +X hdr = () +X if hdr: +X data_size = hdr[0] +X data = fp.read(data_size) +X # XXX this doesn't work yet, need to convert from uLAW!!! +X del fp +X else: +X del fp +X data = readfile(tempname) +X if G.debug: print len(data), 'bytes read from', tempname +X if G.busy: +X G.busy = 0 +X dummy = audio.stop_playing() +X # +X # Completely reset the audio device +X audio.setrate(G.rate) +X audio.setduration(0) +X audio.setoutgain(G.gain) +X # +X if G.synchronous: +X audio.write(data) +X audio.setoutgain(0) +X else: +X try: +X audio.start_playing(data) +X G.busy = 1 +X except: +X stdwin.fleep() +X del data X Xdef readfile(filename): -X return readfp(open(filename, 'r')) +X return readfp(open(filename, 'r')) X Xdef readfp(fp): -X data = '' -X while 1: -X buf = fp.read(102400) # Reads most samples in one fell swoop -X if not buf: -X return data -X data = data + buf +X data = '' +X while 1: +X buf = fp.read(102400) # Reads most samples in one fell swoop +X if not buf: +X return data +X data = data + buf X Xmain() EOF @@ -340,7 +340,7 @@ sed 's/^X//' > 'demo/sgi/gl_panel/twoview/twoview.py' << 'EOF' X#! /ufs/guido/bin/sgi/python X X# A demo of GL's viewing transformations, showing two views on one scene. -X# Requires the NASA AMES Panel Library. Requires Z buffer. +X# Requires the NASA AMES Panel Library. Requires Z buffer. X Xfrom gl import * Xfrom GL import * @@ -352,384 +352,384 @@ Xfar = 1000.0 Xnear = 100.0 X Xdef main(): -X foreground() -X # -X keepaspect(1, 1) -X prefposition(10, 610, 10, 610) -X obswid = winopen('Observer View') -X doublebuffer() -X RGBmode() -X gconfig() -X # -X keepaspect(1, 1) -X prefposition(10, 310, 650, 950) -X topwid = winopen('Top View') -X doublebuffer() -X RGBmode() -X gconfig() -X # -X panels = panel.defpanellist('observer.s') -X panels = panels + panel.defpanellist('camera.s') -X panels = panels + panel.defpanellist('topview.s') -X # -X p = panels[0] -X q = panels[1] -X r = panels[2] -X # -X p.farclip = q.farclip -X p.nearclip = q.nearclip -X p.zoom = q.zoom -X p.quitbutton = q.quitbutton -X # -X p.xpos = r.xpos -X p.zpos = r.zpos -X p.direction = r.direction -X # -X p.direction.winds = 1.0 # allow full rotation -X # -X def quit(act): -X import sys -X sys.exit(0) -X p.quitbutton.downfunc = quit -X # -X p.left.back = p -X p.fast_left.back = p -X p.right.back = p -X p.fast_right.back = p -X p.forward.back = p -X p.fast_forward.back = p -X p.reverse.back = p -X p.fast_reverse.back = p -X p.up.back = p -X p.down.back = p -X # -X p.left.activefunc = left -X p.fast_left.activefunc = fast_left -X p.right.activefunc = right -X p.fast_right.activefunc = fast_right -X p.forward.activefunc = forward -X p.fast_forward.activefunc = fast_forward -X p.reverse.activefunc = reverse -X p.fast_reverse.activefunc = fast_reverse -X p.up.activefunc = up -X p.down.activefunc = down -X # -X makeobjects() -X # -X drawall(p, obswid, topwid) -X panel.needredraw() -X while 1: -X act = panel.dopanel() -X if panel.userredraw() or act: -X drawall(p, obswid, topwid) +X foreground() +X # +X keepaspect(1, 1) +X prefposition(10, 610, 10, 610) +X obswid = winopen('Observer View') +X doublebuffer() +X RGBmode() +X gconfig() +X # +X keepaspect(1, 1) +X prefposition(10, 310, 650, 950) +X topwid = winopen('Top View') +X doublebuffer() +X RGBmode() +X gconfig() +X # +X panels = panel.defpanellist('observer.s') +X panels = panels + panel.defpanellist('camera.s') +X panels = panels + panel.defpanellist('topview.s') +X # +X p = panels[0] +X q = panels[1] +X r = panels[2] +X # +X p.farclip = q.farclip +X p.nearclip = q.nearclip +X p.zoom = q.zoom +X p.quitbutton = q.quitbutton +X # +X p.xpos = r.xpos +X p.zpos = r.zpos +X p.direction = r.direction +X # +X p.direction.winds = 1.0 # allow full rotation +X # +X def quit(act): +X import sys +X sys.exit(0) +X p.quitbutton.downfunc = quit +X # +X p.left.back = p +X p.fast_left.back = p +X p.right.back = p +X p.fast_right.back = p +X p.forward.back = p +X p.fast_forward.back = p +X p.reverse.back = p +X p.fast_reverse.back = p +X p.up.back = p +X p.down.back = p +X # +X p.left.activefunc = left +X p.fast_left.activefunc = fast_left +X p.right.activefunc = right +X p.fast_right.activefunc = fast_right +X p.forward.activefunc = forward +X p.fast_forward.activefunc = fast_forward +X p.reverse.activefunc = reverse +X p.fast_reverse.activefunc = fast_reverse +X p.up.activefunc = up +X p.down.activefunc = down +X # +X makeobjects() +X # +X drawall(p, obswid, topwid) +X panel.needredraw() +X while 1: +X act = panel.dopanel() +X if panel.userredraw() or act: +X drawall(p, obswid, topwid) X Xdef left(a): -X doturn(a.back, 0.01) +X doturn(a.back, 0.01) X Xdef fast_left(a): -X doturn(a.back, 0.1) +X doturn(a.back, 0.1) X Xdef right(a): -X doturn(a.back, -0.01) +X doturn(a.back, -0.01) X Xdef fast_right(a): -X doturn(a.back, -0.1) +X doturn(a.back, -0.1) X Xdef doturn(p, angle): -X alpha = lookangle(p) + angle -X # Reverse the following assignment: -X # alpha = pi*1.5 - p.direction.val*2.0*pi -X val = (pi*1.5 - alpha) / 2.0 / pi -X while val < 0.0: val = val + 1.0 -X while val > 1.0: val = val - 1.0 -X p.direction.val = val -X p.direction.fixact() +X alpha = lookangle(p) + angle +X # Reverse the following assignment: +X # alpha = pi*1.5 - p.direction.val*2.0*pi +X val = (pi*1.5 - alpha) / 2.0 / pi +X while val < 0.0: val = val + 1.0 +X while val > 1.0: val = val - 1.0 +X p.direction.val = val +X p.direction.fixact() X Xdef forward(a): -X dostep(a.back, 1.0) +X dostep(a.back, 1.0) X Xdef fast_forward(a): -X dostep(a.back, 10.0) +X dostep(a.back, 10.0) X Xdef reverse(a): -X dostep(a.back, -1.0) +X dostep(a.back, -1.0) X Xdef fast_reverse(a): -X dostep(a.back, -10.0) +X dostep(a.back, -10.0) X Xdef dostep(p, step): -X x, y, z = observerpos(p) -X alpha = lookangle(p) -X x = x + step*cos(alpha) -X z = z - step*sin(alpha) -X # Reverse the following assignments: -X # x = 2.0 * p.xpos.val * near - near -X # z = near - 2.0 * p.zpos.val * near -X p.xpos.val = (x + near) / 2.0 / near -X p.zpos.val = - (z - near) / 2.0 / near -X p.xpos.fixact() -X p.zpos.fixact() +X x, y, z = observerpos(p) +X alpha = lookangle(p) +X x = x + step*cos(alpha) +X z = z - step*sin(alpha) +X # Reverse the following assignments: +X # x = 2.0 * p.xpos.val * near - near +X # z = near - 2.0 * p.zpos.val * near +X p.xpos.val = (x + near) / 2.0 / near +X p.zpos.val = - (z - near) / 2.0 / near +X p.xpos.fixact() +X p.zpos.fixact() X Xdef up(a): -X doup(a.back, 0.2) +X doup(a.back, 0.2) X Xdef down(a): -X doup(a.back, -0.2) +X doup(a.back, -0.2) X Xdef doup(p, step): -X x, y, z = observerpos(p) -X y = y + step -X # Reverse: -X # y = p.ypos.val * near -X p.ypos.val = y/near -X p.ypos.fixact() +X x, y, z = observerpos(p) +X y = y + step +X # Reverse: +X # y = p.ypos.val * near +X p.ypos.val = y/near +X p.ypos.fixact() X Xdef drawall(p, obswid, topwid): -X # -X winset(obswid) -X obsview(p) -X drawscene() -X swapbuffers() -X # -X winset(topwid) -X topview(p) -X drawscene() -X drawobserver(p) -X swapbuffers() +X # +X winset(obswid) +X obsview(p) +X drawscene() +X swapbuffers() +X # +X winset(topwid) +X topview(p) +X drawscene() +X drawobserver(p) +X swapbuffers() X Xdef drawobserver(p): -X x, y, z = observerpos(p) -X alpha = lookangle(p) -X fov = 2.0 + 1798.0 * p.zoom.val -X beta = fov*pi/3600.0 # Half fov, expressed in radians -X # -X c3i(0, 255, 0) -X # -X move(x, y, z) -X x1 = x + inf*cos(alpha+beta) -X y1 = y -X z1 = z - inf*sin(alpha+beta) -X draw(x1, y1, z1) -X # -X move(x, y, z) -X x1 = x + inf*cos(alpha-beta) -X y1 = y -X z1 = z - inf*sin(alpha-beta) -X draw(x1, y1, z1) +X x, y, z = observerpos(p) +X alpha = lookangle(p) +X fov = 2.0 + 1798.0 * p.zoom.val +X beta = fov*pi/3600.0 # Half fov, expressed in radians +X # +X c3i(0, 255, 0) +X # +X move(x, y, z) +X x1 = x + inf*cos(alpha+beta) +X y1 = y +X z1 = z - inf*sin(alpha+beta) +X draw(x1, y1, z1) +X # +X move(x, y, z) +X x1 = x + inf*cos(alpha-beta) +X y1 = y +X z1 = z - inf*sin(alpha-beta) +X draw(x1, y1, z1) X Xdef observerlookat(p): -X x, y, z = observerpos(p) -X alpha = lookangle(p) -X return x, y, z, x+near*cos(alpha), y, z-near*sin(alpha), 0 +X x, y, z = observerpos(p) +X alpha = lookangle(p) +X return x, y, z, x+near*cos(alpha), y, z-near*sin(alpha), 0 X Xdef observerpos(p): -X x = 2.0 * p.xpos.val * near - near -X y = p.ypos.val * near -X z = near - 2.0 * p.zpos.val * near -X return x, y, z +X x = 2.0 * p.xpos.val * near - near +X y = p.ypos.val * near +X z = near - 2.0 * p.zpos.val * near +X return x, y, z X Xdef lookangle(p): -X return pi*1.5 - p.direction.val*2.0*pi +X return pi*1.5 - p.direction.val*2.0*pi X Xidmat = 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 X Xdef topview(p): -X mmode(MVIEWING) -X ortho(-far, far, -far, far, far, -far) -X loadmatrix(idmat) -X rotate(900, 'x') +X mmode(MVIEWING) +X ortho(-far, far, -far, far, far, -far) +X loadmatrix(idmat) +X rotate(900, 'x') X Xdef obsview(p): -X fov = 2.0 + 1798.0 * p.zoom.val -X nearclip = p.nearclip.val * 10.0 -X farclip = p.farclip.val * 10.0*far -X aspectratio = 1.0 -X mmode(MVIEWING) -X perspective(int(fov), aspectratio, nearclip, farclip) -X loadmatrix(idmat) -X lookat(observerlookat(p)) +X fov = 2.0 + 1798.0 * p.zoom.val +X nearclip = p.nearclip.val * 10.0 +X farclip = p.farclip.val * 10.0*far +X aspectratio = 1.0 +X mmode(MVIEWING) +X perspective(int(fov), aspectratio, nearclip, farclip) +X loadmatrix(idmat) +X lookat(observerlookat(p)) X Xdef drawscene(): -X # -X # clear window -X # -X c3i(0, 0, 0) -X clear() -X # -X # turn on z buffering and clear it -X # -X zbuffer(TRUE) -X zclear() -X # -X # dark blue sky (depending on your gamma value!) -X # -X c3i(0, 0, 150) -X callobj(41) -X # -X # bright red near and far units circle -X # (use rotate since circ() always draws in x-y plane) -X # -X c3i(255, 0, 0) -X pushmatrix() -X rotate(900, 'x') -X circ(0.0, 0.0, near) -X circ(0.0, 0.0, far) -X popmatrix() -X # -X # bright white striping -X # -X c3i(255, 255, 200) -X callobj(42) -X # -X # building (does its own colors) -X # -X building() -X # -X # some other objects -X # -X dice() +X # +X # clear window +X # +X c3i(0, 0, 0) +X clear() +X # +X # turn on z buffering and clear it +X # +X zbuffer(TRUE) +X zclear() +X # +X # dark blue sky (depending on your gamma value!) +X # +X c3i(0, 0, 150) +X callobj(41) +X # +X # bright red near and far units circle +X # (use rotate since circ() always draws in x-y plane) +X # +X c3i(255, 0, 0) +X pushmatrix() +X rotate(900, 'x') +X circ(0.0, 0.0, near) +X circ(0.0, 0.0, far) +X popmatrix() +X # +X # bright white striping +X # +X c3i(255, 255, 200) +X callobj(42) +X # +X # building (does its own colors) +X # +X building() +X # +X # some other objects +X # +X dice() X Xdef makeobjects(): -X # -X # sky object -X # -X makeobj(41) -X pmv(-inf, 0.0, -far) -X pdr(inf, 0.0, -far) -X pdr(inf, inf, -far) -X pdr(-inf, inf, -far) -X pclos() -X closeobj() -X # -X # road stripes object -X # -X makeobj(42) -X stripes() -X closeobj() -X # -X # lighting model definitions -X # -X deflight() +X # +X # sky object +X # +X makeobj(41) +X pmv(-inf, 0.0, -far) +X pdr(inf, 0.0, -far) +X pdr(inf, inf, -far) +X pdr(-inf, inf, -far) +X pclos() +X closeobj() +X # +X # road stripes object +X # +X makeobj(42) +X stripes() +X closeobj() +X # +X # lighting model definitions +X # +X deflight() X Xdef stripes(): -X # -X # left line -X # -X botrect(-11, -10, far, -far) -X # -X # right line -X # -X botrect(10, 11, far, -far) -X # -X # center lines -X # -X z = far -X while z > -far: -X botrect(-0.5, 0.5, z, z - 4.0) -X z = z - 10.0 +X # +X # left line +X # +X botrect(-11, -10, far, -far) +X # +X # right line +X # +X botrect(10, 11, far, -far) +X # +X # center lines +X # +X z = far +X while z > -far: +X botrect(-0.5, 0.5, z, z - 4.0) +X z = z - 10.0 X Xdef dice(): -X from block import block -X uselight() -X pushmatrix() -X translate(0.0, 1.0, -20.0) -X rotate(200, 'y') -X block(1, 0, 0, 0, 0, 0) -X translate(1.0, 0.0, 3.0) -X rotate(500, 'y') -X block(2, 0, 0, 0, 0, 0) -X popmatrix() +X from block import block +X uselight() +X pushmatrix() +X translate(0.0, 1.0, -20.0) +X rotate(200, 'y') +X block(1, 0, 0, 0, 0, 0) +X translate(1.0, 0.0, 3.0) +X rotate(500, 'y') +X block(2, 0, 0, 0, 0, 0) +X popmatrix() X Xdef deflight(): -X # Material for first die (red) -X lmdef(DEFMATERIAL, 1, (DIFFUSE, 1.0, 0.0, 0.0)) -X # Material for second die (green) -X lmdef(DEFMATERIAL, 2, (DIFFUSE, 0.0, 1.0, 0.0)) -X # First light source (default: white, from front) -X lmdef(DEFLIGHT, 1, ()) -X # Second light source (red, from back) -X lmdef(DEFLIGHT, 2, (POSITION, 0.0, 1.0, -1.0, 0.0)) -X lmdef(DEFLIGHT, 2, (LCOLOR, 1.0, 0.0, 0.0)) -X # Lighting model -X lmdef(DEFLMODEL, 1, (AMBIENT, 0.0, 0.0, 1.0)) +X # Material for first die (red) +X lmdef(DEFMATERIAL, 1, (DIFFUSE, 1.0, 0.0, 0.0)) +X # Material for second die (green) +X lmdef(DEFMATERIAL, 2, (DIFFUSE, 0.0, 1.0, 0.0)) +X # First light source (default: white, from front) +X lmdef(DEFLIGHT, 1, ()) +X # Second light source (red, from back) +X lmdef(DEFLIGHT, 2, (POSITION, 0.0, 1.0, -1.0, 0.0)) +X lmdef(DEFLIGHT, 2, (LCOLOR, 1.0, 0.0, 0.0)) +X # Lighting model +X lmdef(DEFLMODEL, 1, (AMBIENT, 0.0, 0.0, 1.0)) X Xdef uselight(): -X lmbind(LIGHT0, 1) -X lmbind(LIGHT1, 2) -X lmbind(LMODEL, 1) -X # (materials are bound later) +X lmbind(LIGHT0, 1) +X lmbind(LIGHT1, 2) +X lmbind(LMODEL, 1) +X # (materials are bound later) X Xdef building(): -X # -X c3i(0, 255, 255) -X # -X # house bounding coordinates -X # -X x1 = 20.0 -X x1a = 25.0 -X x2 = 30.0 -X y1 = 0.0 -X y2 = 15.0 -X y2a = 20.0 -X z1 = -40.0 -X z2 = -55.0 -X # -X # door y and z coordinates -X # -X dy1 = 0.0 -X dy2 = 4.0 -X dz1 = -45.0 -X dz2 = -47.0 -X # -X # front side (seen from origin) -X # -X A1 = (x1, y1, z1) -X B1 = (x2, y1, z1) -X C1 = (x2, y2, z1) -X D1 = (x1a, y2a, z1) -X E1 = (x1, y2, z1) -X # -X # back size -X # -X A2 = (x1, y1, z2) -X B2 = (x2, y1, z2) -X C2 = (x2, y2, z2) -X D2 = (x1a, y2a, z2) -X E2 = (x1, y2, z2) -X # -X # door in the left side -X # -X P = x1, dy1, dz2 -X Q = x1, dy2, dz2 -X R = x1, dy2, dz1 -X S = x1, dy1, dz1 -X # -X # draw it -X # -X concave(TRUE) -X c3i(255, 0, 0) -X face(A1, B1, C1, D1, E1) -X c3i(127, 127, 0) -X face(A1, E1, E2, A2, P, Q, R, S) -X c3i(0, 255, 0) -X face(E1, D1, D2, E2) -X c3i(0, 127, 127) -X face(D1, C1, C2, D2) -X c3i(0, 0, 255) -X face(C1, B1, B2, C2) -X c3i(127, 0, 127) -X face(E2, D2, C2, B2, A2) -X concave(FALSE) +X # +X c3i(0, 255, 255) +X # +X # house bounding coordinates +X # +X x1 = 20.0 +X x1a = 25.0 +X x2 = 30.0 +X y1 = 0.0 +X y2 = 15.0 +X y2a = 20.0 +X z1 = -40.0 +X z2 = -55.0 +X # +X # door y and z coordinates +X # +X dy1 = 0.0 +X dy2 = 4.0 +X dz1 = -45.0 +X dz2 = -47.0 +X # +X # front side (seen from origin) +X # +X A1 = (x1, y1, z1) +X B1 = (x2, y1, z1) +X C1 = (x2, y2, z1) +X D1 = (x1a, y2a, z1) +X E1 = (x1, y2, z1) +X # +X # back size +X # +X A2 = (x1, y1, z2) +X B2 = (x2, y1, z2) +X C2 = (x2, y2, z2) +X D2 = (x1a, y2a, z2) +X E2 = (x1, y2, z2) +X # +X # door in the left side +X # +X P = x1, dy1, dz2 +X Q = x1, dy2, dz2 +X R = x1, dy2, dz1 +X S = x1, dy1, dz1 +X # +X # draw it +X # +X concave(TRUE) +X c3i(255, 0, 0) +X face(A1, B1, C1, D1, E1) +X c3i(127, 127, 0) +X face(A1, E1, E2, A2, P, Q, R, S) +X c3i(0, 255, 0) +X face(E1, D1, D2, E2) +X c3i(0, 127, 127) +X face(D1, C1, C2, D2) +X c3i(0, 0, 255) +X face(C1, B1, B2, C2) +X c3i(127, 0, 127) +X face(E2, D2, C2, B2, A2) +X concave(FALSE) X Xdef face(points): -X bgnpolygon() -X varray(points) -X endpolygon() +X bgnpolygon() +X varray(points) +X endpolygon() X X# draw a rectangle at y=0.0 X# Xdef botrect(x1, x2, z1, z2): -X polf(x1, 0.0, z1, x2, 0.0, z1, x2, 0.0, z2, x1, 0.0, z2) +X polf(x1, 0.0, z1, x2, 0.0, z1, x2, 0.0, z2, x1, 0.0, z2) X Xmain() EOF @@ -741,19 +741,19 @@ else echo 'x - lib/DEVICE.py' sed 's/^X//' > 'lib/DEVICE.py' << 'EOF' X#/************************************************************************** -X# * * -X# * Copyright (C) 1984, Silicon Graphics, Inc. * -X# * * -X# * These coded instructions, statements, and computer programs contain * -X# * unpublished proprietary information of Silicon Graphics, Inc., and * -X# * are protected by Federal copyright law. They may not be disclosed * -X# * to third parties or copied or duplicated in any form, in whole or * -X# * in part, without the prior written consent of Silicon Graphics, Inc. * -X# * * +X# * * +X# * Copyright (C) 1984, Silicon Graphics, Inc. * +X# * * +X# * These coded instructions, statements, and computer programs contain * +X# * unpublished proprietary information of Silicon Graphics, Inc., and * +X# * are protected by Federal copyright law. They may not be disclosed * +X# * to third parties or copied or duplicated in any form, in whole or * +X# * in part, without the prior written consent of Silicon Graphics, Inc. * +X# * * X# **************************************************************************/ X#/* file with device definitions (see /usr/include/device.h) */ X -XNULLDEV = 0 +XNULLDEV = 0 XBUTOFFSET = 1 XVALOFFSET = 256 XTIMOFFSET = 515 @@ -764,405 +764,405 @@ XBUTCOUNT = 190 XVALCOUNT = 27 XTIMCOUNT = 4 XXKBDCOUNT = 28 -XINCOUNT = 8 +XINCOUNT = 8 XOUTCOUNT = 8 X# X# X# X# -XBUT0 = 1 -XBUT1 = 2 -XBUT2 = 3 -XBUT3 = 4 -XBUT4 = 5 -XBUT5 = 6 -XBUT6 = 7 -XBUT7 = 8 -XBUT8 = 9 -XBUT9 = 10 -XBUT10 = 11 -XBUT11 = 12 -XBUT12 = 13 -XBUT13 = 14 -XBUT14 = 15 -XBUT15 = 16 -XBUT16 = 17 -XBUT17 = 18 -XBUT18 = 19 -XBUT19 = 20 -XBUT20 = 21 -XBUT21 = 22 -XBUT22 = 23 -XBUT23 = 24 -XBUT24 = 25 -XBUT25 = 26 -XBUT26 = 27 -XBUT27 = 28 -XBUT28 = 29 -XBUT29 = 30 -XBUT30 = 31 -XBUT31 = 32 -XBUT32 = 33 -XBUT33 = 34 -XBUT34 = 35 -XBUT35 = 36 -XBUT36 = 37 -XBUT37 = 38 -XBUT38 = 39 -XBUT39 = 40 -XBUT40 = 41 -XBUT41 = 42 -XBUT42 = 43 -XBUT43 = 44 -XBUT44 = 45 -XBUT45 = 46 -XBUT46 = 47 -XBUT47 = 48 -XBUT48 = 49 -XBUT49 = 50 -XBUT50 = 51 -XBUT51 = 52 -XBUT52 = 53 -XBUT53 = 54 -XBUT54 = 55 -XBUT55 = 56 -XBUT56 = 57 -XBUT57 = 58 -XBUT58 = 59 -XBUT59 = 60 -XBUT60 = 61 -XBUT61 = 62 -XBUT62 = 63 -XBUT63 = 64 -XBUT64 = 65 -XBUT65 = 66 -XBUT66 = 67 -XBUT67 = 68 -XBUT68 = 69 -XBUT69 = 70 -XBUT70 = 71 -XBUT71 = 72 -XBUT72 = 73 -XBUT73 = 74 -XBUT74 = 75 -XBUT75 = 76 -XBUT76 = 77 -XBUT77 = 78 -XBUT78 = 79 -XBUT79 = 80 -XBUT80 = 81 -XBUT81 = 82 -XBUT82 = 83 -XMAXKBDBUT = 83 -XBUT100 = 101 -XBUT101 = 102 -XBUT102 = 103 -XBUT110 = 111 -XBUT111 = 112 -XBUT112 = 113 -XBUT113 = 114 -XBUT114 = 115 -XBUT115 = 116 -XBUT116 = 117 -XBUT117 = 118 -XBUT118 = 119 -XBUT119 = 120 -XBUT120 = 121 -XBUT121 = 122 -XBUT122 = 123 -XBUT123 = 124 -XBUT124 = 125 -XBUT125 = 126 -XBUT126 = 127 -XBUT127 = 128 -XBUT128 = 129 -XBUT129 = 130 -XBUT130 = 131 -XBUT131 = 132 -XBUT132 = 133 -XBUT133 = 134 -XBUT134 = 135 -XBUT135 = 136 -XBUT136 = 137 -XBUT137 = 138 -XBUT138 = 139 -XBUT139 = 140 -XBUT140 = 141 -XBUT141 = 142 -XBUT142 = 143 -XBUT143 = 144 -XBUT144 = 145 -XBUT145 = 146 -XBUT146 = 147 -XBUT147 = 148 -XBUT148 = 149 -XBUT149 = 150 -XBUT150 = 151 -XBUT151 = 152 -XBUT152 = 153 -XBUT153 = 154 -XBUT154 = 155 -XBUT155 = 156 -XBUT156 = 157 -XBUT157 = 158 -XBUT158 = 159 -XBUT159 = 160 -XBUT160 = 161 -XBUT161 = 162 -XBUT162 = 163 -XBUT163 = 164 -XBUT164 = 165 -XBUT165 = 166 -XBUT166 = 167 -XBUT167 = 168 -XBUT168 = 169 -XBUT181 = 182 -XBUT182 = 183 -XBUT183 = 184 -XBUT184 = 185 -XBUT185 = 186 -XBUT186 = 187 -XBUT187 = 188 -XBUT188 = 189 -XBUT189 = 190 -XMOUSE1 = 101 -XMOUSE2 = 102 -XMOUSE3 = 103 -XLEFTMOUSE = 103 -XMIDDLEMOUSE = 102 -XRIGHTMOUSE = 101 -XLPENBUT = 104 -XBPAD0 = 105 -XBPAD1 = 106 -XBPAD2 = 107 -XBPAD3 = 108 -XLPENVALID = 109 -XSWBASE = 111 -XSW0 = 111 -XSW1 = 112 -XSW2 = 113 -XSW3 = 114 -XSW4 = 115 -XSW5 = 116 -XSW6 = 117 -XSW7 = 118 -XSW8 = 119 -XSW9 = 120 -XSW10 = 121 -XSW11 = 122 -XSW12 = 123 -XSW13 = 124 -XSW14 = 125 -XSW15 = 126 -XSW16 = 127 -XSW17 = 128 -XSW18 = 129 -XSW19 = 130 -XSW20 = 131 -XSW21 = 132 -XSW22 = 133 -XSW23 = 134 -XSW24 = 135 -XSW25 = 136 -XSW26 = 137 -XSW27 = 138 -XSW28 = 139 -XSW29 = 140 -XSW30 = 141 -XSW31 = 142 -XSBBASE = 182 -XSBPICK = 182 -XSBBUT1 = 183 -XSBBUT2 = 184 -XSBBUT3 = 185 -XSBBUT4 = 186 -XSBBUT5 = 187 -XSBBUT6 = 188 -XSBBUT7 = 189 -XSBBUT8 = 190 -XAKEY = 11 -XBKEY = 36 -XCKEY = 28 -XDKEY = 18 -XEKEY = 17 -XFKEY = 19 -XGKEY = 26 -XHKEY = 27 -XIKEY = 40 -XJKEY = 34 -XKKEY = 35 -XLKEY = 42 -XMKEY = 44 -XNKEY = 37 -XOKEY = 41 -XPKEY = 48 -XQKEY = 10 -XRKEY = 24 -XSKEY = 12 -XTKEY = 25 -XUKEY = 33 -XVKEY = 29 -XWKEY = 16 -XXKEY = 21 -XYKEY = 32 -XZKEY = 20 -XZEROKEY = 46 -XONEKEY = 8 -XTWOKEY = 14 -XTHREEKEY = 15 -XFOURKEY = 22 -XFIVEKEY = 23 -XSIXKEY = 30 -XSEVENKEY = 31 -XEIGHTKEY = 38 -XNINEKEY = 39 -XBREAKKEY = 1 -XSETUPKEY = 2 -XCTRLKEY = 3 -XLEFTCTRLKEY = CTRLKEY -XCAPSLOCKKEY = 4 -XRIGHTSHIFTKEY = 5 -XLEFTSHIFTKEY = 6 -XNOSCRLKEY = 13 -XESCKEY = 7 -XTABKEY = 9 -XRETKEY = 51 -XSPACEKEY = 83 -XLINEFEEDKEY = 60 -XBACKSPACEKEY = 61 -XDELKEY = 62 -XSEMICOLONKEY = 43 -XPERIODKEY = 52 -XCOMMAKEY = 45 -XQUOTEKEY = 50 -XACCENTGRAVEKEY = 55 -XMINUSKEY = 47 -XVIRGULEKEY = 53 -XBACKSLASHKEY = 57 -XEQUALKEY = 54 -XLEFTBRACKETKEY = 49 -XRIGHTBRACKETKEY = 56 -XLEFTARROWKEY = 73 -XDOWNARROWKEY = 74 -XRIGHTARROWKEY = 80 -XUPARROWKEY = 81 -XPAD0 = 59 -XPAD1 = 58 -XPAD2 = 64 -XPAD3 = 65 -XPAD4 = 63 -XPAD5 = 69 -XPAD6 = 70 -XPAD7 = 67 -XPAD8 = 68 -XPAD9 = 75 -XPADPF1 = 72 -XPADPF2 = 71 -XPADPF3 = 79 -XPADPF4 = 78 -XPADPERIOD = 66 -XPADMINUS = 76 -XPADCOMMA = 77 -XPADENTER = 82 -XLEFTALTKEY = 143 -XRIGHTALTKEY = 144 -XRIGHTCTRLKEY = 145 -XF1KEY = 146 -XF2KEY = 147 -XF3KEY = 148 -XF4KEY = 149 -XF5KEY = 150 -XF6KEY = 151 -XF7KEY = 152 -XF8KEY = 153 -XF9KEY = 154 -XF10KEY = 155 -XF11KEY = 156 -XF12KEY = 157 +XBUT0 = 1 +XBUT1 = 2 +XBUT2 = 3 +XBUT3 = 4 +XBUT4 = 5 +XBUT5 = 6 +XBUT6 = 7 +XBUT7 = 8 +XBUT8 = 9 +XBUT9 = 10 +XBUT10 = 11 +XBUT11 = 12 +XBUT12 = 13 +XBUT13 = 14 +XBUT14 = 15 +XBUT15 = 16 +XBUT16 = 17 +XBUT17 = 18 +XBUT18 = 19 +XBUT19 = 20 +XBUT20 = 21 +XBUT21 = 22 +XBUT22 = 23 +XBUT23 = 24 +XBUT24 = 25 +XBUT25 = 26 +XBUT26 = 27 +XBUT27 = 28 +XBUT28 = 29 +XBUT29 = 30 +XBUT30 = 31 +XBUT31 = 32 +XBUT32 = 33 +XBUT33 = 34 +XBUT34 = 35 +XBUT35 = 36 +XBUT36 = 37 +XBUT37 = 38 +XBUT38 = 39 +XBUT39 = 40 +XBUT40 = 41 +XBUT41 = 42 +XBUT42 = 43 +XBUT43 = 44 +XBUT44 = 45 +XBUT45 = 46 +XBUT46 = 47 +XBUT47 = 48 +XBUT48 = 49 +XBUT49 = 50 +XBUT50 = 51 +XBUT51 = 52 +XBUT52 = 53 +XBUT53 = 54 +XBUT54 = 55 +XBUT55 = 56 +XBUT56 = 57 +XBUT57 = 58 +XBUT58 = 59 +XBUT59 = 60 +XBUT60 = 61 +XBUT61 = 62 +XBUT62 = 63 +XBUT63 = 64 +XBUT64 = 65 +XBUT65 = 66 +XBUT66 = 67 +XBUT67 = 68 +XBUT68 = 69 +XBUT69 = 70 +XBUT70 = 71 +XBUT71 = 72 +XBUT72 = 73 +XBUT73 = 74 +XBUT74 = 75 +XBUT75 = 76 +XBUT76 = 77 +XBUT77 = 78 +XBUT78 = 79 +XBUT79 = 80 +XBUT80 = 81 +XBUT81 = 82 +XBUT82 = 83 +XMAXKBDBUT = 83 +XBUT100 = 101 +XBUT101 = 102 +XBUT102 = 103 +XBUT110 = 111 +XBUT111 = 112 +XBUT112 = 113 +XBUT113 = 114 +XBUT114 = 115 +XBUT115 = 116 +XBUT116 = 117 +XBUT117 = 118 +XBUT118 = 119 +XBUT119 = 120 +XBUT120 = 121 +XBUT121 = 122 +XBUT122 = 123 +XBUT123 = 124 +XBUT124 = 125 +XBUT125 = 126 +XBUT126 = 127 +XBUT127 = 128 +XBUT128 = 129 +XBUT129 = 130 +XBUT130 = 131 +XBUT131 = 132 +XBUT132 = 133 +XBUT133 = 134 +XBUT134 = 135 +XBUT135 = 136 +XBUT136 = 137 +XBUT137 = 138 +XBUT138 = 139 +XBUT139 = 140 +XBUT140 = 141 +XBUT141 = 142 +XBUT142 = 143 +XBUT143 = 144 +XBUT144 = 145 +XBUT145 = 146 +XBUT146 = 147 +XBUT147 = 148 +XBUT148 = 149 +XBUT149 = 150 +XBUT150 = 151 +XBUT151 = 152 +XBUT152 = 153 +XBUT153 = 154 +XBUT154 = 155 +XBUT155 = 156 +XBUT156 = 157 +XBUT157 = 158 +XBUT158 = 159 +XBUT159 = 160 +XBUT160 = 161 +XBUT161 = 162 +XBUT162 = 163 +XBUT163 = 164 +XBUT164 = 165 +XBUT165 = 166 +XBUT166 = 167 +XBUT167 = 168 +XBUT168 = 169 +XBUT181 = 182 +XBUT182 = 183 +XBUT183 = 184 +XBUT184 = 185 +XBUT185 = 186 +XBUT186 = 187 +XBUT187 = 188 +XBUT188 = 189 +XBUT189 = 190 +XMOUSE1 = 101 +XMOUSE2 = 102 +XMOUSE3 = 103 +XLEFTMOUSE = 103 +XMIDDLEMOUSE = 102 +XRIGHTMOUSE = 101 +XLPENBUT = 104 +XBPAD0 = 105 +XBPAD1 = 106 +XBPAD2 = 107 +XBPAD3 = 108 +XLPENVALID = 109 +XSWBASE = 111 +XSW0 = 111 +XSW1 = 112 +XSW2 = 113 +XSW3 = 114 +XSW4 = 115 +XSW5 = 116 +XSW6 = 117 +XSW7 = 118 +XSW8 = 119 +XSW9 = 120 +XSW10 = 121 +XSW11 = 122 +XSW12 = 123 +XSW13 = 124 +XSW14 = 125 +XSW15 = 126 +XSW16 = 127 +XSW17 = 128 +XSW18 = 129 +XSW19 = 130 +XSW20 = 131 +XSW21 = 132 +XSW22 = 133 +XSW23 = 134 +XSW24 = 135 +XSW25 = 136 +XSW26 = 137 +XSW27 = 138 +XSW28 = 139 +XSW29 = 140 +XSW30 = 141 +XSW31 = 142 +XSBBASE = 182 +XSBPICK = 182 +XSBBUT1 = 183 +XSBBUT2 = 184 +XSBBUT3 = 185 +XSBBUT4 = 186 +XSBBUT5 = 187 +XSBBUT6 = 188 +XSBBUT7 = 189 +XSBBUT8 = 190 +XAKEY = 11 +XBKEY = 36 +XCKEY = 28 +XDKEY = 18 +XEKEY = 17 +XFKEY = 19 +XGKEY = 26 +XHKEY = 27 +XIKEY = 40 +XJKEY = 34 +XKKEY = 35 +XLKEY = 42 +XMKEY = 44 +XNKEY = 37 +XOKEY = 41 +XPKEY = 48 +XQKEY = 10 +XRKEY = 24 +XSKEY = 12 +XTKEY = 25 +XUKEY = 33 +XVKEY = 29 +XWKEY = 16 +XXKEY = 21 +XYKEY = 32 +XZKEY = 20 +XZEROKEY = 46 +XONEKEY = 8 +XTWOKEY = 14 +XTHREEKEY = 15 +XFOURKEY = 22 +XFIVEKEY = 23 +XSIXKEY = 30 +XSEVENKEY = 31 +XEIGHTKEY = 38 +XNINEKEY = 39 +XBREAKKEY = 1 +XSETUPKEY = 2 +XCTRLKEY = 3 +XLEFTCTRLKEY = CTRLKEY +XCAPSLOCKKEY = 4 +XRIGHTSHIFTKEY = 5 +XLEFTSHIFTKEY = 6 +XNOSCRLKEY = 13 +XESCKEY = 7 +XTABKEY = 9 +XRETKEY = 51 +XSPACEKEY = 83 +XLINEFEEDKEY = 60 +XBACKSPACEKEY = 61 +XDELKEY = 62 +XSEMICOLONKEY = 43 +XPERIODKEY = 52 +XCOMMAKEY = 45 +XQUOTEKEY = 50 +XACCENTGRAVEKEY = 55 +XMINUSKEY = 47 +XVIRGULEKEY = 53 +XBACKSLASHKEY = 57 +XEQUALKEY = 54 +XLEFTBRACKETKEY = 49 +XRIGHTBRACKETKEY = 56 +XLEFTARROWKEY = 73 +XDOWNARROWKEY = 74 +XRIGHTARROWKEY = 80 +XUPARROWKEY = 81 +XPAD0 = 59 +XPAD1 = 58 +XPAD2 = 64 +XPAD3 = 65 +XPAD4 = 63 +XPAD5 = 69 +XPAD6 = 70 +XPAD7 = 67 +XPAD8 = 68 +XPAD9 = 75 +XPADPF1 = 72 +XPADPF2 = 71 +XPADPF3 = 79 +XPADPF4 = 78 +XPADPERIOD = 66 +XPADMINUS = 76 +XPADCOMMA = 77 +XPADENTER = 82 +XLEFTALTKEY = 143 +XRIGHTALTKEY = 144 +XRIGHTCTRLKEY = 145 +XF1KEY = 146 +XF2KEY = 147 +XF3KEY = 148 +XF4KEY = 149 +XF5KEY = 150 +XF6KEY = 151 +XF7KEY = 152 +XF8KEY = 153 +XF9KEY = 154 +XF10KEY = 155 +XF11KEY = 156 +XF12KEY = 157 XPRINTSCREENKEY = 158 XSCROLLLOCKKEY = 159 XPAUSEKEY = 160 XINSERTKEY = 161 -XHOMEKEY = 162 -XPAGEUPKEY = 163 -XENDKEY = 164 +XHOMEKEY = 162 +XPAGEUPKEY = 163 +XENDKEY = 164 XPAGEDOWNKEY = 165 XNUMLOCKKEY = 166 -XPADVIRGULEKEY = 167 -XPADASTERKEY = 168 -XPADPLUSKEY = 169 -XSGIRESERVED = 256 -XDIAL0 = 257 -XDIAL1 = 258 -XDIAL2 = 259 -XDIAL3 = 260 -XDIAL4 = 261 -XDIAL5 = 262 -XDIAL6 = 263 -XDIAL7 = 264 -XDIAL8 = 265 -XMOUSEX = 266 -XMOUSEY = 267 -XLPENX = 268 -XLPENY = 269 -XBPADX = 270 -XBPADY = 271 -XCURSORX = 272 -XCURSORY = 273 -XGHOSTX = 274 -XGHOSTY = 275 -XSBTX = 276 -XSBTY = 277 -XSBTZ = 278 -XSBRX = 279 -XSBRY = 280 -XSBRZ = 281 -XSBPERIOD = 282 -XTIMER0 = 515 -XTIMER1 = 516 -XTIMER2 = 517 -XTIMER3 = 518 -XKEYBD = 513 -XRAWKEYBD = 514 -XVALMARK = 523 -XGERROR = 524 -XREDRAW = 528 -XWMSEND = 529 -XWMREPLY = 530 -XWMGFCLOSE = 531 -XWMTXCLOSE = 532 -XMODECHANGE = 533 -XINPUTCHANGE = 534 -XQFULL = 535 -XPIECECHANGE = 536 -XWINCLOSE = 537 -XQREADERROR = 538 -XWINFREEZE = 539 -XWINTHAW = 540 -XREDRAWICONIC = 541 -XWINQUIT = 542 -XDEPTHCHANGE = 543 -XKEYBDFNAMES = 544 -XKEYBDFSTRINGS = 545 -XWINSHUT = 546 -XINPUT0 = 1024 -XINPUT1 = 1025 -XINPUT2 = 1026 -XINPUT3 = 1027 -XINPUT4 = 1028 -XINPUT5 = 1029 -XINPUT6 = 1030 -XINPUT7 = 1032 -XOUTPUT0 = 1033 -XOUTPUT1 = 1034 -XOUTPUT2 = 1035 -XOUTPUT3 = 1036 -XOUTPUT4 = 1037 -XOUTPUT5 = 1038 -XOUTPUT6 = 1039 -XOUTPUT7 = 1040 +XPADVIRGULEKEY = 167 +XPADASTERKEY = 168 +XPADPLUSKEY = 169 +XSGIRESERVED = 256 +XDIAL0 = 257 +XDIAL1 = 258 +XDIAL2 = 259 +XDIAL3 = 260 +XDIAL4 = 261 +XDIAL5 = 262 +XDIAL6 = 263 +XDIAL7 = 264 +XDIAL8 = 265 +XMOUSEX = 266 +XMOUSEY = 267 +XLPENX = 268 +XLPENY = 269 +XBPADX = 270 +XBPADY = 271 +XCURSORX = 272 +XCURSORY = 273 +XGHOSTX = 274 +XGHOSTY = 275 +XSBTX = 276 +XSBTY = 277 +XSBTZ = 278 +XSBRX = 279 +XSBRY = 280 +XSBRZ = 281 +XSBPERIOD = 282 +XTIMER0 = 515 +XTIMER1 = 516 +XTIMER2 = 517 +XTIMER3 = 518 +XKEYBD = 513 +XRAWKEYBD = 514 +XVALMARK = 523 +XGERROR = 524 +XREDRAW = 528 +XWMSEND = 529 +XWMREPLY = 530 +XWMGFCLOSE = 531 +XWMTXCLOSE = 532 +XMODECHANGE = 533 +XINPUTCHANGE = 534 +XQFULL = 535 +XPIECECHANGE = 536 +XWINCLOSE = 537 +XQREADERROR = 538 +XWINFREEZE = 539 +XWINTHAW = 540 +XREDRAWICONIC = 541 +XWINQUIT = 542 +XDEPTHCHANGE = 543 +XKEYBDFNAMES = 544 +XKEYBDFSTRINGS = 545 +XWINSHUT = 546 +XINPUT0 = 1024 +XINPUT1 = 1025 +XINPUT2 = 1026 +XINPUT3 = 1027 +XINPUT4 = 1028 +XINPUT5 = 1029 +XINPUT6 = 1030 +XINPUT7 = 1032 +XOUTPUT0 = 1033 +XOUTPUT1 = 1034 +XOUTPUT2 = 1035 +XOUTPUT3 = 1036 +XOUTPUT4 = 1037 +XOUTPUT5 = 1038 +XOUTPUT6 = 1039 +XOUTPUT7 = 1040 XMAXSGIDEVICE = 20000 -XMENUBUTTON = RIGHTMOUSE +XMENUBUTTON = RIGHTMOUSE EOF fi if test -s 'lib/GL.py' @@ -1173,15 +1173,15 @@ sed 's/^X//' > 'lib/GL.py' << 'EOF' X# Constants defined in <gl.h> X X#************************************************************************** -X#* * -X#* Copyright (C) 1984, Silicon Graphics, Inc. * -X#* * -X#* These coded instructions, statements, and computer programs contain * -X#* unpublished proprietary information of Silicon Graphics, Inc., and * -X#* are protected by Federal copyright law. They may not be disclosed * -X#* to third parties or copied or duplicated in any form, in whole or * -X#* in part, without the prior written consent of Silicon Graphics, Inc. * -X#* * +X#* * +X#* Copyright (C) 1984, Silicon Graphics, Inc. * +X#* * +X#* These coded instructions, statements, and computer programs contain * +X#* unpublished proprietary information of Silicon Graphics, Inc., and * +X#* are protected by Federal copyright law. They may not be disclosed * +X#* to third parties or copied or duplicated in any form, in whole or * +X#* in part, without the prior written consent of Silicon Graphics, Inc. * +X#* * X#************************************************************************** X X# Graphics Libary constants @@ -1190,17 +1190,17 @@ X# Booleans XTRUE = 1 XFALSE = 0 X -X# maximum X and Y screen coordinates +X# maximum X and Y screen coordinates XXMAXSCREEN = 1279 XYMAXSCREEN = 1023 -XXMAXMEDIUM = 1023 # max for medium res monitor +XXMAXMEDIUM = 1023 # max for medium res monitor XYMAXMEDIUM = 767 -XXMAX170 = 645 # max for RS-170 +XXMAX170 = 645 # max for RS-170 XYMAX170 = 484 -XXMAXPAL = 779 # max for PAL +XXMAXPAL = 779 # max for PAL XYMAXPAL = 574 X -X# various hardware/software limits +X# various hardware/software limits XATTRIBSTACKDEPTH = 10 XVPSTACKDEPTH = 8 XMATRIXSTACKDEPTH = 32 @@ -1209,7 +1209,7 @@ XSTARTTAG = -2 XENDTAG = -3 XCPOSX_INVALID = -(2*XMAXSCREEN) X -X# names for colors in color map loaded by greset +X# names for colors in color map loaded by greset XBLACK = 0 XRED = 1 XGREEN = 2 @@ -1219,20 +1219,20 @@ XMAGENTA = 5 XCYAN = 6 XWHITE = 7 X -X# popup colors +X# popup colors XPUP_CLEAR = 0 XPUP_COLOR = 1 XPUP_BLACK = 2 XPUP_WHITE = 3 X -X# defines for drawmode +X# defines for drawmode XNORMALDRAW = 0 XPUPDRAW = 1 XOVERDRAW = 2 XUNDERDRAW = 3 XCURSORDRAW = 4 X -X# defines for defpattern +X# defines for defpattern XPATTERN_16 = 16 XPATTERN_32 = 32 XPATTERN_64 = 64 @@ -1241,7 +1241,7 @@ XPATTERN_16_SIZE = 16 XPATTERN_32_SIZE = 64 XPATTERN_64_SIZE = 256 X -X# defines for readsource +X# defines for readsource XSRC_AUTO = 0 XSRC_FRONT = 1 XSRC_BACK = 2 @@ -1251,7 +1251,7 @@ XSRC_OVER = 5 XSRC_UNDER = 6 XSRC_FRAMEGRABBER = 7 X -X# defines for blendfunction +X# defines for blendfunction XBF_ZERO = 0 XBF_ONE = 1 XBF_DC = 2 @@ -1263,7 +1263,7 @@ XBF_MSA = 5 XBF_DA = 6 XBF_MDA = 7 X -X# defines for zfunction +X# defines for zfunction XZF_NEVER = 0 XZF_LESS = 1 XZF_EQUAL = 2 @@ -1273,38 +1273,38 @@ XZF_NOTEQUAL = 5 XZF_GEQUAL = 6 XZF_ALWAYS = 7 X -X# defines for zsource +X# defines for zsource XZSRC_DEPTH = 0 XZSRC_COLOR = 1 X -X# defines for pntsmooth +X# defines for pntsmooth XSMP_OFF = 0 XSMP_ON = 1 X -X# defines for linesmooth +X# defines for linesmooth XSML_OFF = 0 XSML_ON = 1 X -X# defines for setpup +X# defines for setpup XPUP_NONE = 0 XPUP_GREY = 1 X -X# defines for glcompat +X# defines for glcompat XGLC_OLDPOLYGON = 0 XGLC_ZRANGEMAP = 1 X -X# defines for curstype +X# defines for curstype XC16X1 = 0 XC16X2 = 1 XC32X1 = 2 XC32X2 = 3 XCCROSS = 4 X -X# defines for shademodel +X# defines for shademodel XFLAT = 0 XGOURAUD = 1 X -X# defines for logicop +X# defines for logicop X### LO_ZERO = 0x0 X### LO_AND = 0x1 X### LO_ANDR = 0x2 @@ -1324,7 +1324,7 @@ X### LO_ONE = 0xf X X X# -X# START defines for getgdesc +X# START defines for getgdesc X# X XGD_XPMAX = 0 @@ -1347,7 +1347,7 @@ XGD_BITS_NORM_ZBUFFER = 16 XGD_BITS_OVER_SNG_CMODE = 17 XGD_BITS_UNDR_SNG_CMODE = 18 XGD_BITS_PUP_SNG_CMODE = 19 -XGD_BITS_NORM_SNG_ALPHA = 21 +XGD_BITS_NORM_SNG_ALPHA = 21 XGD_BITS_NORM_DBL_ALPHA = 22 XGD_BITS_CURSOR = 23 XGD_OVERUNDER_SHARED = 24 @@ -1406,16 +1406,16 @@ X# return values for GD_SCRNTYPE XGD_SCRNTYPE_WM = 0 XGD_SCRNTYPE_NOWM = 1 X -X# -X# END defines for getgdesc +X# +X# END defines for getgdesc X# X X -X# -X# START NURBS interface definitions +X# +X# START NURBS interface definitions X# X -X# NURBS Rendering Properties +X# NURBS Rendering Properties XN_PIXEL_TOLERANCE = 1 XN_CULLING = 2 XN_DISPLAY = 3 @@ -1425,59 +1425,59 @@ XN_S_STEPS = 6 XN_T_STEPS = 7 XN_TILES = 8 X -XN_SHADED = 1.0 +XN_SHADED = 1.0 X X# --------------------------------------------------------------------------- -X# FLAGS FOR NURBS SURFACES AND CURVES -X# -X# Bit: 9876 5432 1 0 -X# |tttt|nnnn|f|r| : r - 1 bit = 1 if rational coordinate exists -X# : f - 1 bit = 1 if rational coordinate is before rest -X# : = 0 if rational coordinate is after rest -X# : nnnn - 4 bits for number of coordinates -X# : tttt - 4 bits for type of data (color, position, etc.) -X# +X# FLAGS FOR NURBS SURFACES AND CURVES +X# +X# Bit: 9876 5432 1 0 +X# |tttt|nnnn|f|r| : r - 1 bit = 1 if rational coordinate exists +X# : f - 1 bit = 1 if rational coordinate is before rest +X# : = 0 if rational coordinate is after rest +X# : nnnn - 4 bits for number of coordinates +X# : tttt - 4 bits for type of data (color, position, etc.) +X# X# NURBS data type -X# N_T_ST 0 parametric space data -X# N_T_XYZ 1 model space data -X# -X# rational or non-rational data and position in memory -X# N_NONRATIONAL 0 non-rational data -X# N_RATAFTER 1 rational data with rat coord after rest -X# N_RATBEFORE 3 rational data with rat coord before rest -X# +X# N_T_ST 0 parametric space data +X# N_T_XYZ 1 model space data +X# +X# rational or non-rational data and position in memory +X# N_NONRATIONAL 0 non-rational data +X# N_RATAFTER 1 rational data with rat coord after rest +X# N_RATBEFORE 3 rational data with rat coord before rest +X# X# N_MKFLAG(a,b,c) ((a<<6) | (b<<2) | c) -X# +X# X# --------------------------------------------------------------------------- -X# -XN_ST = 0x8 # N_MKFLAG( N_T_ST, 2, N_NONRATIONAL ) -XN_STW = 0xd # N_MKFLAG( N_T_ST, 3, N_RATAFTER ) -XN_WST = 0xf # N_MKFLAG( N_T_ST, 3, N_RATBEFORE ) -XN_XYZ = 0x4c # N_MKFLAG( N_T_XYZ, 3, N_NONRATIONAL ) -XN_XYZW = 0x51 # N_MKFLAG( N_T_XYZ, 4, N_RATAFTER ) -XN_WXYZ = 0x53 # N_MKFLAG( N_T_XYZ, 4, N_RATBEFORE ) +X# +XN_ST = 0x8 # N_MKFLAG( N_T_ST, 2, N_NONRATIONAL ) +XN_STW = 0xd # N_MKFLAG( N_T_ST, 3, N_RATAFTER ) +XN_WST = 0xf # N_MKFLAG( N_T_ST, 3, N_RATBEFORE ) +XN_XYZ = 0x4c # N_MKFLAG( N_T_XYZ, 3, N_NONRATIONAL ) +XN_XYZW = 0x51 # N_MKFLAG( N_T_XYZ, 4, N_RATAFTER ) +XN_WXYZ = 0x53 # N_MKFLAG( N_T_XYZ, 4, N_RATBEFORE ) X -X# -X# END NURBS interface definitions -X# +X# +X# END NURBS interface definitions +X# X X -X# -X# START lighting model defines -X# +X# +X# START lighting model defines +X# X XLMNULL = 0.0 X -X# MATRIX modes +X# MATRIX modes XMSINGLE = 0 XMPROJECTION = 1 XMVIEWING = 2 X -X# LIGHT constants +X# LIGHT constants XMAXLIGHTS = 8 XMAXRESTRICTIONS = 4 X -X# MATERIAL properties +X# MATERIAL properties XDEFMATERIAL = 0 XEMISSION = 1 XAMBIENT = 2 @@ -1487,17 +1487,17 @@ XSHININESS = 5 XCOLORINDEXES = 6 XALPHA = 7 X -X# LIGHT properties +X# LIGHT properties XDEFLIGHT = 100 XLCOLOR = 101 XPOSITION = 102 X -X# LIGHTINGMODEL properties +X# LIGHTINGMODEL properties XDEFLMODEL = 200 XLOCALVIEWER = 201 XATTENUATION = 202 X -X# TARGET constants +X# TARGET constants XMATERIAL = 1000 XLIGHT0 = 1100 XLIGHT1 = 1101 @@ -1509,7 +1509,7 @@ XLIGHT6 = 1106 XLIGHT7 = 1107 XLMODEL = 1200 X -X# lmcolor modes +X# lmcolor modes XLMC_COLOR = 0 XLMC_EMISSION = 1 XLMC_AMBIENT = 2 @@ -1518,23 +1518,23 @@ XLMC_SPECULAR = 4 XLMC_AD = 5 XLMC_NULL = 6 X -X# -X# END lighting model defines -X# +X# +X# END lighting model defines +X# X X -X# -X# START distributed graphics library defines -X# +X# +X# START distributed graphics library defines +X# X -XDGLSINK = 0 # sink connection -XDGLLOCAL = 1 # local connection -XDGLTSOCKET = 2 # tcp socket connection -XDGL4DDN = 3 # 4DDN (DECnet) +XDGLSINK = 0 # sink connection +XDGLLOCAL = 1 # local connection +XDGLTSOCKET = 2 # tcp socket connection +XDGL4DDN = 3 # 4DDN (DECnet) X -X# -X# END distributed graphics library defines -X# +X# +X# END distributed graphics library defines +X# EOF fi if test -s 'lib/calendar.py' @@ -1555,12 +1555,12 @@ X# - months numbers are 1-12, not 0-11; month arrays have a dummy element 0 X# - Monday is the first day of the week (numbered 0) X X# These are really parameters of the 'time' module: -Xepoch = 1970 # Time began on January 1 of this year (00:00:00 UCT) -Xday_0 = 3 # The epoch begins on a Thursday (Monday = 0) +Xepoch = 1970 # Time began on January 1 of this year (00:00:00 UCT) +Xday_0 = 3 # The epoch begins on a Thursday (Monday = 0) X X# Return 1 for leap years, 0 for non-leap years Xdef isleap(year): -X return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) +X return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) X X# Constants for months referenced later XJanuary = 1 @@ -1574,41 +1574,41 @@ Xerror = 'calendar error' X X# Turn seconds since epoch into calendar time Xdef gmtime(secs): -X if secs < 0: raise error, 'negative input to gmtime()' -X mins, secs = divmod(secs, 60) -X hours, mins = divmod(mins, 60) -X days, hours = divmod(hours, 24) -X wday = (days + day_0) % 7 -X year = epoch -X # XXX Most of the following loop can be replaced by one division -X while 1: -X yd = 365 + isleap(year) -X if days < yd: break -X days = days - yd -X year = year + 1 -X yday = days -X month = January -X while 1: -X md = mdays[month] + (month = February and isleap(year)) -X if days < md: break -X days = days - md -X month = month + 1 -X return year, month, days + 1, hours, mins, secs, yday, wday -X # XXX Week number also? +X if secs < 0: raise error, 'negative input to gmtime()' +X mins, secs = divmod(secs, 60) +X hours, mins = divmod(mins, 60) +X days, hours = divmod(hours, 24) +X wday = (days + day_0) % 7 +X year = epoch +X # XXX Most of the following loop can be replaced by one division +X while 1: +X yd = 365 + isleap(year) +X if days < yd: break +X days = days - yd +X year = year + 1 +X yday = days +X month = January +X while 1: +X md = mdays[month] + (month = February and isleap(year)) +X if days < md: break +X days = days - md +X month = month + 1 +X return year, month, days + 1, hours, mins, secs, yday, wday +X # XXX Week number also? X X# Return number of leap years in range [y1, y2) X# Assume y1 <= y2 and no funny (non-leap century) years Xdef leapdays(y1, y2): -X return (y2+3)/4 - (y1+3)/4 +X return (y2+3)/4 - (y1+3)/4 X X# Inverse of gmtime(): X# Turn UCT calendar time (less yday, wday) into seconds since epoch Xdef mktime(year, month, day, hours, mins, secs): -X days = day - 1 -X for m in range(January, month): days = days + mdays[m] -X if isleap(year) and month > February: days = days+1 -X days = days + (year-epoch)*365 + leapdays(epoch, year) -X return ((days*24 + hours)*60 + mins)*60 + secs +X days = day - 1 +X for m in range(January, month): days = days + mdays[m] +X if isleap(year) and month > February: days = days+1 +X days = days + (year-epoch)*365 + leapdays(epoch, year) +X return ((days*24 + hours)*60 + mins)*60 + secs X X# Full and abbreviated names of weekdays Xday_name = ('Monday', 'Tuesday', 'Wednesday', 'Thursday') @@ -1616,40 +1616,40 @@ Xday_name = day_name + ('Friday', 'Saturday', 'Sunday') Xday_abbr = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') X X# Full and abbreviated of months (1-based arrays!!!) -Xmonth_name = ('', 'January', 'February', 'March', 'April') -Xmonth_name = month_name + ('May', 'June', 'July', 'August') -Xmonth_name = month_name + ('September', 'October', 'November', 'December') -Xmonth_abbr = (' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') +Xmonth_name = ('', 'January', 'February', 'March', 'April') +Xmonth_name = month_name + ('May', 'June', 'July', 'August') +Xmonth_name = month_name + ('September', 'October', 'November', 'December') +Xmonth_abbr = (' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') Xmonth_abbr = month_abbr + ('Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') X X# Zero-fill string to two positions (helper for asctime()) Xdef dd(s): -X while len(s) < 2: s = '0' + s -X return s +X while len(s) < 2: s = '0' + s +X return s X X# Blank-fill string to two positions (helper for asctime()) Xdef zd(s): -X while len(s) < 2: s = ' ' + s -X return s +X while len(s) < 2: s = ' ' + s +X return s X X# Turn calendar time as returned by gmtime() into a string X# (the yday parameter is for compatibility with gmtime()) Xdef asctime(year, month, day, hours, mins, secs, yday, wday): -X s = day_abbr[wday] + ' ' + month_abbr[month] + ' ' + zd(`day`) -X s = s + ' ' + dd(`hours`) + ':' + dd(`mins`) + ':' + dd(`secs`) -X return s + ' ' + `year` +X s = day_abbr[wday] + ' ' + month_abbr[month] + ' ' + zd(`day`) +X s = s + ' ' + dd(`hours`) + ':' + dd(`mins`) + ':' + dd(`secs`) +X return s + ' ' + `year` X X# Localization: Minutes West from Greenwich -X# timezone = -2*60 # Middle-European time with DST on -Xtimezone = 5*60 # EST (sigh -- THINK time() doesn't return UCT) +X# timezone = -2*60 # Middle-European time with DST on +Xtimezone = 5*60 # EST (sigh -- THINK time() doesn't return UCT) X X# Local time ignores DST issues for now -- adjust 'timezone' to fake it Xdef localtime(secs): -X return gmtime(secs - timezone*60) +X return gmtime(secs - timezone*60) X X# UNIX-style ctime (except it doesn't append '\n'!) Xdef ctime(secs): -X return asctime(localtime(secs)) +X return asctime(localtime(secs)) X X###################### X# Non-UNIX additions # @@ -1659,102 +1659,102 @@ X# Calendar printing etc. X X# Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31) Xdef weekday(year, month, day): -X secs = mktime(year, month, day, 0, 0, 0) -X days = secs / (24*60*60) -X return (days + day_0) % 7 +X secs = mktime(year, month, day, 0, 0, 0) +X days = secs / (24*60*60) +X return (days + day_0) % 7 X X# Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month Xdef monthrange(year, month): -X day1 = weekday(year, month, 1) -X ndays = mdays[month] + (month = February and isleap(year)) -X return day1, ndays +X day1 = weekday(year, month, 1) +X ndays = mdays[month] + (month = February and isleap(year)) +X return day1, ndays X X# Return a matrix representing a month's calendar X# Each row represents a week; days outside this month are zero Xdef _monthcalendar(year, month): -X day1, ndays = monthrange(year, month) -X rows = [] -X r7 = range(7) -X day = 1 - day1 -X while day <= ndays: -X row = [0, 0, 0, 0, 0, 0, 0] -X for i in r7: -X if 1 <= day <= ndays: row[i] = day -X day = day + 1 -X rows.append(row) -X return rows +X day1, ndays = monthrange(year, month) +X rows = [] +X r7 = range(7) +X day = 1 - day1 +X while day <= ndays: +X row = [0, 0, 0, 0, 0, 0, 0] +X for i in r7: +X if 1 <= day <= ndays: row[i] = day +X day = day + 1 +X rows.append(row) +X return rows X X# Caching interface to _monthcalendar Xmc_cache = {} Xdef monthcalendar(year, month): -X key = `year` + month_abbr[month] -X try: -X return mc_cache[key] -X except RuntimeError: -X mc_cache[key] = ret = _monthcalendar(year, month) -X return ret +X key = `year` + month_abbr[month] +X try: +X return mc_cache[key] +X except RuntimeError: +X mc_cache[key] = ret = _monthcalendar(year, month) +X return ret X X# Center a string in a field Xdef center(str, width): -X n = width - len(str) -X if n < 0: return str -X return ' '*(n/2) + str + ' '*(n-n/2) +X n = width - len(str) +X if n < 0: return str +X return ' '*(n/2) + str + ' '*(n-n/2) X X# XXX The following code knows that print separates items with space! X X# Print a single week (no newline) Xdef prweek(week, width): -X for day in week: -X if day = 0: print ' '*width, -X else: -X if width > 2: print ' '*(width-3), -X if day < 10: print '', -X print day, +X for day in week: +X if day = 0: print ' '*width, +X else: +X if width > 2: print ' '*(width-3), +X if day < 10: print '', +X print day, X X# Return a header for a week Xdef weekheader(width): -X str = '' -X for i in range(7): -X if str: str = str + ' ' -X str = str + day_abbr[i%7][:width] -X return str +X str = '' +X for i in range(7): +X if str: str = str + ' ' +X str = str + day_abbr[i%7][:width] +X return str X X# Print a month's calendar Xdef prmonth(year, month): -X print weekheader(3) -X for week in monthcalendar(year, month): -X prweek(week, 3) -X print +X print weekheader(3) +X for week in monthcalendar(year, month): +X prweek(week, 3) +X print X X# Spacing between month columns -Xspacing = ' ' +Xspacing = ' ' X X# 3-column formatting for year calendars Xdef format3c(a, b, c): -X print center(a, 20), spacing, center(b, 20), spacing, center(c, 20) +X print center(a, 20), spacing, center(b, 20), spacing, center(c, 20) X X# Print a year's calendar Xdef prcal(year): -X header = weekheader(2) -X format3c('', `year`, '') -X for q in range(January, January+12, 3): -X print -X format3c(month_name[q], month_name[q+1], month_name[q+2]) -X format3c(header, header, header) -X data = [] -X height = 0 -X for month in range(q, q+3): -X cal = monthcalendar(year, month) -X if len(cal) > height: height = len(cal) -X data.append(cal) -X for i in range(height): -X for cal in data: -X if i >= len(cal): -X print ' '*20, -X else: -X prweek(cal[i], 2) -X print spacing, -X print +X header = weekheader(2) +X format3c('', `year`, '') +X for q in range(January, January+12, 3): +X print +X format3c(month_name[q], month_name[q+1], month_name[q+2]) +X format3c(header, header, header) +X data = [] +X height = 0 +X for month in range(q, q+3): +X cal = monthcalendar(year, month) +X if len(cal) > height: height = len(cal) +X data.append(cal) +X for i in range(height): +X for cal in data: +X if i >= len(cal): +X print ' '*20, +X else: +X prweek(cal[i], 2) +X print spacing, +X print EOF fi if test -s 'lib/panel.py' @@ -1781,82 +1781,82 @@ X X# Test if an object is a list. X# Xdef is_list(x): -X return type(x) = type([]) +X return type(x) = type([]) X X X# Reverse a list. X# Xdef reverse(list): -X res = [] -X for item in list: -X res.insert(0, item) -X return res +X res = [] +X for item in list: +X res.insert(0, item) +X return res X X X# Get an attribute of a list, which may itself be another list. X# Don't use 'prop' for name. X# Xdef getattrlist(list, name): -X for item in list: -X if item and is_list(item) and item[0] = name: -X return item[1:] -X return [] +X for item in list: +X if item and is_list(item) and item[0] = name: +X return item[1:] +X return [] X X X# Get a property of a list, which may itself be another list. X# Xdef getproplist(list, name): -X for item in list: -X if item and is_list(item) and item[0] = 'prop': -X if len(item) > 1 and item[1] = name: -X return item[2:] -X return [] +X for item in list: +X if item and is_list(item) and item[0] = 'prop': +X if len(item) > 1 and item[1] = name: +X return item[2:] +X return [] X X X# Test if an actuator description contains the property 'end-of-group' X# Xdef is_endgroup(list): -X x = getproplist(list, 'end-of-group') -X return (x and x[0] = '#t') +X x = getproplist(list, 'end-of-group') +X return (x and x[0] = '#t') X X X# Neatly display an actuator definition given as S-expression X# the prefix string is printed before each line. X# Xdef show_actuator(prefix, a): -X for item in a: -X if not is_list(item): -X print prefix, item -X elif item and item[0] = 'al': -X print prefix, 'Subactuator list:' -X for a in item[1:]: -X show_actuator(prefix + ' ', a) -X elif len(item) = 2: -X print prefix, item[0], '=>', item[1] -X elif len(item) = 3 and item[0] = 'prop': -X print prefix, 'Prop', item[1], '=>', -X print item[2] -X else: -X print prefix, '?', item +X for item in a: +X if not is_list(item): +X print prefix, item +X elif item and item[0] = 'al': +X print prefix, 'Subactuator list:' +X for a in item[1:]: +X show_actuator(prefix + ' ', a) +X elif len(item) = 2: +X print prefix, item[0], '=>', item[1] +X elif len(item) = 3 and item[0] = 'prop': +X print prefix, 'Prop', item[1], '=>', +X print item[2] +X else: +X print prefix, '?', item X X X# Neatly display a panel. X# Xdef show_panel(prefix, p): -X for item in p: -X if not is_list(item): -X print prefix, item -X elif item and item[0] = 'al': -X print prefix, 'Actuator list:' -X for a in item[1:]: -X show_actuator(prefix + ' ', a) -X elif len(item) = 2: -X print prefix, item[0], '=>', item[1] -X elif len(item) = 3 and item[0] = 'prop': -X print prefix, 'Prop', item[1], '=>', -X print item[2] -X else: -X print prefix, '?', item +X for item in p: +X if not is_list(item): +X print prefix, item +X elif item and item[0] = 'al': +X print prefix, 'Actuator list:' +X for a in item[1:]: +X show_actuator(prefix + ' ', a) +X elif len(item) = 2: +X print prefix, item[0], '=>', item[1] +X elif len(item) = 3 and item[0] = 'prop': +X print prefix, 'Prop', item[1], '=>', +X print item[2] +X else: +X print prefix, '?', item X X X# Exception raised by build_actuator or build_panel. @@ -1867,7 +1867,7 @@ X X# Dummy callback used to initialize the callbacks. X# Xdef dummy_callback(arg): -X pass +X pass X X X# Assign attributes to members of the target. @@ -1875,60 +1875,60 @@ X# Attribute names in exclist are ignored. X# The member name is the attribute name prefixed with the prefix. X# Xdef assign_members(target, attrlist, exclist, prefix): -X for item in attrlist: -X if is_list(item) and len(item) = 2 and item[0] not in exclist: -X name, value = item[0], item[1] -X ok = 1 -X if value[0] in '-0123456789': -X value = eval(value) -X elif value[0] = '"': -X value = value[1:-1] -X elif value = 'move-then-resize': -X # Strange default set by Panel Editor... -X ok = 0 -X else: -X print 'unknown value', value, 'for', name -X ok = 0 -X if ok: -X lhs = 'target.' + prefix + name -X stmt = lhs + '=' + `value` -X if debug: print 'exec', stmt -X try: -X exec(stmt + '\n') -X except KeyboardInterrupt: # Don't catch this! -X raise KeyboardInterrupt -X except: -X print 'assign failed:', stmt +X for item in attrlist: +X if is_list(item) and len(item) = 2 and item[0] not in exclist: +X name, value = item[0], item[1] +X ok = 1 +X if value[0] in '-0123456789': +X value = eval(value) +X elif value[0] = '"': +X value = value[1:-1] +X elif value = 'move-then-resize': +X # Strange default set by Panel Editor... +X ok = 0 +X else: +X print 'unknown value', value, 'for', name +X ok = 0 +X if ok: +X lhs = 'target.' + prefix + name +X stmt = lhs + '=' + `value` +X if debug: print 'exec', stmt +X try: +X exec(stmt + '\n') +X except KeyboardInterrupt: # Don't catch this! +X raise KeyboardInterrupt +X except: +X print 'assign failed:', stmt X X X# Build a real actuator from an actuator descriptior. X# Return a pair (actuator, name). X# Xdef build_actuator(descr): -X namelist = getattrlist(descr, 'name') -X if namelist: -X # Assume it is a string -X actuatorname = namelist[0][1:-1] -X else: -X actuatorname = '' -X type = descr[0] -X if type[:4] = 'pnl_': type = type[4:] -X act = pnl.mkact(type) -X act.downfunc = act.activefunc = act.upfunc = dummy_callback -X # -X assign_members(act, descr[1:], ['al', 'data', 'name'], '') -X # -X # Treat actuator-specific data -X # -X datalist = getattrlist(descr, 'data') -X prefix = '' -X if type[-4:] = 'puck': -X prefix = 'puck_' -X elif type = 'mouse': -X prefix = 'mouse_' -X assign_members(act, datalist, [], prefix) -X # -X return act, actuatorname +X namelist = getattrlist(descr, 'name') +X if namelist: +X # Assume it is a string +X actuatorname = namelist[0][1:-1] +X else: +X actuatorname = '' +X type = descr[0] +X if type[:4] = 'pnl_': type = type[4:] +X act = pnl.mkact(type) +X act.downfunc = act.activefunc = act.upfunc = dummy_callback +X # +X assign_members(act, descr[1:], ['al', 'data', 'name'], '') +X # +X # Treat actuator-specific data +X # +X datalist = getattrlist(descr, 'data') +X prefix = '' +X if type[-4:] = 'puck': +X prefix = 'puck_' +X elif type = 'mouse': +X prefix = 'mouse_' +X assign_members(act, datalist, [], prefix) +X # +X return act, actuatorname X X X# Build all sub-actuators and add them to the super-actuator. @@ -1940,27 +1940,27 @@ X# Note: I have no idea how panel.endgroup() works when applied X# to a sub-actuator. X# Xdef build_subactuators(panel, super_act, al): -X # -X # This is nearly the same loop as below in build_panel(), -X # except a call is made to addsubact() instead of addact(). -X # -X for a in al: -X act, name = build_actuator(a) -X act.addsubact(super_act) -X if name: -X stmt = 'panel.' + name + ' = act' -X if debug: print 'exec', stmt -X exec(stmt + '\n') -X if is_endgroup(a): -X panel.endgroup() -X sub_al = getattrlist(a, 'al') -X if sub_al: -X build_subactuators(panel, act, sub_al) -X # -X # Fix the actuator to which whe just added subactuators. -X # This can't hurt (I hope) and is needed for the scroll actuator. -X # -X super_act.fixact() +X # +X # This is nearly the same loop as below in build_panel(), +X # except a call is made to addsubact() instead of addact(). +X # +X for a in al: +X act, name = build_actuator(a) +X act.addsubact(super_act) +X if name: +X stmt = 'panel.' + name + ' = act' +X if debug: print 'exec', stmt +X exec(stmt + '\n') +X if is_endgroup(a): +X panel.endgroup() +X sub_al = getattrlist(a, 'al') +X if sub_al: +X build_subactuators(panel, act, sub_al) +X # +X # Fix the actuator to which whe just added subactuators. +X # This can't hurt (I hope) and is needed for the scroll actuator. +X # +X super_act.fixact() X X X# Build a real panel from a panel definition. @@ -1968,81 +1968,81 @@ X# Return a panel object p, where for each named actuator a, p.name is a X# reference to a. X# Xdef build_panel(descr): -X # -X # Sanity check -X # -X if (not descr) or descr[0] <> 'panel': -X raise panel_error, 'panel description must start with "panel"' -X # -X if debug: show_panel('', descr) -X # -X # Create an empty panel -X # -X panel = pnl.mkpanel() -X # -X # Assign panel attributes -X # -X assign_members(panel, descr[1:], ['al'], '') -X # -X # Look for actuator list -X # -X al = getattrlist(descr, 'al') -X # -X # The order in which actuators are created is important -X # because of the endgroup() operator. -X # Unfortunately the Panel Editor outputs the actuator list -X # in reverse order, so we reverse it here. -X # -X al = reverse(al) -X # -X for a in al: -X act, name = build_actuator(a) -X act.addact(panel) -X if name: -X stmt = 'panel.' + name + ' = act' -X exec(stmt + '\n') -X if is_endgroup(a): -X panel.endgroup() -X sub_al = getattrlist(a, 'al') -X if sub_al: -X build_subactuators(panel, act, sub_al) -X # -X return panel +X # +X # Sanity check +X # +X if (not descr) or descr[0] <> 'panel': +X raise panel_error, 'panel description must start with "panel"' +X # +X if debug: show_panel('', descr) +X # +X # Create an empty panel +X # +X panel = pnl.mkpanel() +X # +X # Assign panel attributes +X # +X assign_members(panel, descr[1:], ['al'], '') +X # +X # Look for actuator list +X # +X al = getattrlist(descr, 'al') +X # +X # The order in which actuators are created is important +X # because of the endgroup() operator. +X # Unfortunately the Panel Editor outputs the actuator list +X # in reverse order, so we reverse it here. +X # +X al = reverse(al) +X # +X for a in al: +X act, name = build_actuator(a) +X act.addact(panel) +X if name: +X stmt = 'panel.' + name + ' = act' +X exec(stmt + '\n') +X if is_endgroup(a): +X panel.endgroup() +X sub_al = getattrlist(a, 'al') +X if sub_al: +X build_subactuators(panel, act, sub_al) +X # +X return panel X X X# Wrapper around pnl.dopanel() which calls call-back functions. X# Xdef my_dopanel(): -X # Extract only the first 4 elements to allow for future expansion -X a, down, active, up = pnl.dopanel()[:4] -X if down: -X down.downfunc(down) -X if active: -X active.activefunc(active) -X if up: -X up.upfunc(up) -X return a +X # Extract only the first 4 elements to allow for future expansion +X a, down, active, up = pnl.dopanel()[:4] +X if down: +X down.downfunc(down) +X if active: +X active.activefunc(active) +X if up: +X up.upfunc(up) +X return a X X X# Create one or more panels from a description file (S-expressions) X# generated by the Panel Editor. -X# +X# Xdef defpanellist(file): -X import panelparser -X descrlist = panelparser.parse_file(open(file, 'r')) -X panellist = [] -X for descr in descrlist: -X panellist.append(build_panel(descr)) -X return panellist +X import panelparser +X descrlist = panelparser.parse_file(open(file, 'r')) +X panellist = [] +X for descr in descrlist: +X panellist.append(build_panel(descr)) +X return panellist X X X# Import everything from built-in method pnl, so the user can always X# use panel.foo() instead of pnl.foo(). X# This gives *no* performance penalty once this module is imported. X# -Xfrom pnl import * # for export +Xfrom pnl import * # for export X -Xdopanel = my_dopanel # override pnl.dopanel +Xdopanel = my_dopanel # override pnl.dopanel EOF fi if test -s 'src/acceler.c' @@ -2054,12 +2054,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2077,13 +2077,13 @@ X X/* Parser accelerator module */ X X/* The parser as originally conceived had disappointing performance. -X This module does some precomputation that speeds up the selection -X of a DFA based upon a token, turning a search through an array -X into a simple indexing operation. The parser now cannot work -X without the accelerators installed. Note that the accelerators -X are installed dynamically when the parser is initialized, they -X are not part of the static data structure written on graminit.[ch] -X by the parser generator. */ +X This module does some precomputation that speeds up the selection +X of a DFA based upon a token, turning a search through an array +X into a simple indexing operation. The parser now cannot work +X without the accelerators installed. Note that the accelerators +X are installed dynamically when the parser is initialized, they +X are not part of the static data structure written on graminit.[ch] +X by the parser generator. */ X X#include "pgenheaders.h" X#include "grammar.h" @@ -2096,95 +2096,95 @@ Xstatic void fixstate PROTO((grammar *, dfa *, state *)); X Xvoid Xaddaccelerators(g) -X grammar *g; +X grammar *g; X{ -X dfa *d; -X int i; +X dfa *d; +X int i; X#ifdef DEBUG -X printf("Adding parser accellerators ...\n"); +X printf("Adding parser accellerators ...\n"); X#endif -X d = g->g_dfa; -X for (i = g->g_ndfas; --i >= 0; d++) -X fixdfa(g, d); -X g->g_accel = 1; +X d = g->g_dfa; +X for (i = g->g_ndfas; --i >= 0; d++) +X fixdfa(g, d); +X g->g_accel = 1; X#ifdef DEBUG -X printf("Done.\n"); +X printf("Done.\n"); X#endif X} X Xstatic void Xfixdfa(g, d) -X grammar *g; -X dfa *d; +X grammar *g; +X dfa *d; X{ -X state *s; -X int j; -X s = d->d_state; -X for (j = 0; j < d->d_nstates; j++, s++) -X fixstate(g, d, s); +X state *s; +X int j; +X s = d->d_state; +X for (j = 0; j < d->d_nstates; j++, s++) +X fixstate(g, d, s); X} X Xstatic void Xfixstate(g, d, s) -X grammar *g; -X dfa *d; -X state *s; +X grammar *g; +X dfa *d; +X state *s; X{ -X arc *a; -X int k; -X int *accel; -X int nl = g->g_ll.ll_nlabels; -X s->s_accept = 0; -X accel = NEW(int, nl); -X for (k = 0; k < nl; k++) -X accel[k] = -1; -X a = s->s_arc; -X for (k = s->s_narcs; --k >= 0; a++) { -X int lbl = a->a_lbl; -X label *l = &g->g_ll.ll_label[lbl]; -X int type = l->lb_type; -X if (a->a_arrow >= (1 << 7)) { -X printf("XXX too many states!\n"); -X continue; -X } -X if (ISNONTERMINAL(type)) { -X dfa *d1 = finddfa(g, type); -X int ibit; -X if (type - NT_OFFSET >= (1 << 7)) { -X printf("XXX too high nonterminal number!\n"); -X continue; -X } -X for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { -X if (testbit(d1->d_first, ibit)) { -X if (accel[ibit] != -1) -X printf("XXX ambiguity!\n"); -X accel[ibit] = a->a_arrow | (1 << 7) | -X ((type - NT_OFFSET) << 8); -X } -X } -X } -X else if (lbl == EMPTY) -X s->s_accept = 1; -X else if (lbl >= 0 && lbl < nl) -X accel[lbl] = a->a_arrow; -X } -X while (nl > 0 && accel[nl-1] == -1) -X nl--; -X for (k = 0; k < nl && accel[k] == -1;) -X k++; -X if (k < nl) { -X int i; -X s->s_accel = NEW(int, nl-k); -X if (s->s_accel == NULL) { -X fprintf(stderr, "no mem to add parser accelerators\n"); -X exit(1); -X } -X s->s_lower = k; -X s->s_upper = nl; -X for (i = 0; k < nl; i++, k++) -X s->s_accel[i] = accel[k]; -X } -X DEL(accel); +X arc *a; +X int k; +X int *accel; +X int nl = g->g_ll.ll_nlabels; +X s->s_accept = 0; +X accel = NEW(int, nl); +X for (k = 0; k < nl; k++) +X accel[k] = -1; +X a = s->s_arc; +X for (k = s->s_narcs; --k >= 0; a++) { +X int lbl = a->a_lbl; +X label *l = &g->g_ll.ll_label[lbl]; +X int type = l->lb_type; +X if (a->a_arrow >= (1 << 7)) { +X printf("XXX too many states!\n"); +X continue; +X } +X if (ISNONTERMINAL(type)) { +X dfa *d1 = finddfa(g, type); +X int ibit; +X if (type - NT_OFFSET >= (1 << 7)) { +X printf("XXX too high nonterminal number!\n"); +X continue; +X } +X for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { +X if (testbit(d1->d_first, ibit)) { +X if (accel[ibit] != -1) +X printf("XXX ambiguity!\n"); +X accel[ibit] = a->a_arrow | (1 << 7) | +X ((type - NT_OFFSET) << 8); +X } +X } +X } +X else if (lbl == EMPTY) +X s->s_accept = 1; +X else if (lbl >= 0 && lbl < nl) +X accel[lbl] = a->a_arrow; +X } +X while (nl > 0 && accel[nl-1] == -1) +X nl--; +X for (k = 0; k < nl && accel[k] == -1;) +X k++; +X if (k < nl) { +X int i; +X s->s_accel = NEW(int, nl-k); +X if (s->s_accel == NULL) { +X fprintf(stderr, "no mem to add parser accelerators\n"); +X exit(1); +X } +X s->s_lower = k; +X s->s_upper = nl; +X for (i = 0; k < nl; i++, k++) +X s->s_accel[i] = accel[k]; +X } +X DEL(accel); X} EOF fi @@ -2197,12 +2197,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2224,176 +2224,176 @@ X X#include "structmember.h" X Xtypedef struct { -X OB_HEAD -X object *cl_bases; /* A tuple */ -X object *cl_methods; /* A dictionary */ +X OB_HEAD +X object *cl_bases; /* A tuple */ +X object *cl_methods; /* A dictionary */ X} classobject; X Xobject * Xnewclassobject(bases, methods) -X object *bases; /* NULL or tuple of classobjects! */ -X object *methods; +X object *bases; /* NULL or tuple of classobjects! */ +X object *methods; X{ -X classobject *op; -X op = NEWOBJ(classobject, &Classtype); -X if (op == NULL) -X return NULL; -X if (bases != NULL) -X INCREF(bases); -X op->cl_bases = bases; -X INCREF(methods); -X op->cl_methods = methods; -X return (object *) op; +X classobject *op; +X op = NEWOBJ(classobject, &Classtype); +X if (op == NULL) +X return NULL; +X if (bases != NULL) +X INCREF(bases); +X op->cl_bases = bases; +X INCREF(methods); +X op->cl_methods = methods; +X return (object *) op; X} X X/* Class methods */ X Xstatic void Xclass_dealloc(op) -X classobject *op; +X classobject *op; X{ -X int i; -X if (op->cl_bases != NULL) -X DECREF(op->cl_bases); -X DECREF(op->cl_methods); -X free((ANY *)op); +X int i; +X if (op->cl_bases != NULL) +X DECREF(op->cl_bases); +X DECREF(op->cl_methods); +X free((ANY *)op); X} X Xstatic object * Xclass_getattr(op, name) -X register classobject *op; -X register char *name; +X register classobject *op; +X register char *name; X{ -X register object *v; -X v = dictlookup(op->cl_methods, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X if (op->cl_bases != NULL) { -X int n = gettuplesize(op->cl_bases); -X int i; -X for (i = 0; i < n; i++) { -X v = class_getattr(gettupleitem(op->cl_bases, i), name); -X if (v != NULL) -X return v; -X err_clear(); -X } -X } -X err_setstr(NameError, name); -X return NULL; +X register object *v; +X v = dictlookup(op->cl_methods, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X if (op->cl_bases != NULL) { +X int n = gettuplesize(op->cl_bases); +X int i; +X for (i = 0; i < n; i++) { +X v = class_getattr(gettupleitem(op->cl_bases, i), name); +X if (v != NULL) +X return v; +X err_clear(); +X } +X } +X err_setstr(NameError, name); +X return NULL; X} X Xtypeobject Classtype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "class", -X sizeof(classobject), -X 0, -X class_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X class_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "class", +X sizeof(classobject), +X 0, +X class_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X class_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X X X/* We're not done yet: next, we define class member objects... */ X Xtypedef struct { -X OB_HEAD -X classobject *cm_class; /* The class object */ -X object *cm_attr; /* A dictionary */ +X OB_HEAD +X classobject *cm_class; /* The class object */ +X object *cm_attr; /* A dictionary */ X} classmemberobject; X Xobject * Xnewclassmemberobject(class) -X register object *class; +X register object *class; X{ -X register classmemberobject *cm; -X if (!is_classobject(class)) { -X err_badcall(); -X return NULL; -X } -X cm = NEWOBJ(classmemberobject, &Classmembertype); -X if (cm == NULL) -X return NULL; -X INCREF(class); -X cm->cm_class = (classobject *)class; -X cm->cm_attr = newdictobject(); -X if (cm->cm_attr == NULL) { -X DECREF(cm); -X return NULL; -X } -X return (object *)cm; +X register classmemberobject *cm; +X if (!is_classobject(class)) { +X err_badcall(); +X return NULL; +X } +X cm = NEWOBJ(classmemberobject, &Classmembertype); +X if (cm == NULL) +X return NULL; +X INCREF(class); +X cm->cm_class = (classobject *)class; +X cm->cm_attr = newdictobject(); +X if (cm->cm_attr == NULL) { +X DECREF(cm); +X return NULL; +X } +X return (object *)cm; X} X X/* Class member methods */ X Xstatic void Xclassmember_dealloc(cm) -X register classmemberobject *cm; +X register classmemberobject *cm; X{ -X DECREF(cm->cm_class); -X if (cm->cm_attr != NULL) -X DECREF(cm->cm_attr); -X free((ANY *)cm); +X DECREF(cm->cm_class); +X if (cm->cm_attr != NULL) +X DECREF(cm->cm_attr); +X free((ANY *)cm); X} X Xstatic object * Xclassmember_getattr(cm, name) -X register classmemberobject *cm; -X register char *name; +X register classmemberobject *cm; +X register char *name; X{ -X register object *v = dictlookup(cm->cm_attr, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X v = class_getattr(cm->cm_class, name); -X if (v == NULL) -X return v; /* class_getattr() has set the error */ -X if (is_funcobject(v)) { -X object *w = newclassmethodobject(v, (object *)cm); -X DECREF(v); -X return w; -X } -X DECREF(v); -X err_setstr(NameError, name); -X return NULL; +X register object *v = dictlookup(cm->cm_attr, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X v = class_getattr(cm->cm_class, name); +X if (v == NULL) +X return v; /* class_getattr() has set the error */ +X if (is_funcobject(v)) { +X object *w = newclassmethodobject(v, (object *)cm); +X DECREF(v); +X return w; +X } +X DECREF(v); +X err_setstr(NameError, name); +X return NULL; X} X Xstatic int Xclassmember_setattr(cm, name, v) -X classmemberobject *cm; -X char *name; -X object *v; +X classmemberobject *cm; +X char *name; +X object *v; X{ -X if (v == NULL) -X return dictremove(cm->cm_attr, name); -X else -X return dictinsert(cm->cm_attr, name, v); +X if (v == NULL) +X return dictremove(cm->cm_attr, name); +X else +X return dictinsert(cm->cm_attr, name, v); X} X Xtypeobject Classmembertype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "class member", -X sizeof(classmemberobject), -X 0, -X classmember_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X classmember_getattr, /*tp_getattr*/ -X classmember_setattr, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "class member", +X sizeof(classmemberobject), +X 0, +X classmember_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X classmember_getattr, /*tp_getattr*/ +X classmember_setattr, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X X @@ -2401,51 +2401,51 @@ X/* And finally, here are class method objects */ X/* (Really methods of class members) */ X Xtypedef struct { -X OB_HEAD -X object *cm_func; /* The method function */ -X object *cm_self; /* The object to which this applies */ +X OB_HEAD +X object *cm_func; /* The method function */ +X object *cm_self; /* The object to which this applies */ X} classmethodobject; X Xobject * Xnewclassmethodobject(func, self) -X object *func; -X object *self; +X object *func; +X object *self; X{ -X register classmethodobject *cm; -X if (!is_funcobject(func)) { -X err_badcall(); -X return NULL; -X } -X cm = NEWOBJ(classmethodobject, &Classmethodtype); -X if (cm == NULL) -X return NULL; -X INCREF(func); -X cm->cm_func = func; -X INCREF(self); -X cm->cm_self = self; -X return (object *)cm; +X register classmethodobject *cm; +X if (!is_funcobject(func)) { +X err_badcall(); +X return NULL; +X } +X cm = NEWOBJ(classmethodobject, &Classmethodtype); +X if (cm == NULL) +X return NULL; +X INCREF(func); +X cm->cm_func = func; +X INCREF(self); +X cm->cm_self = self; +X return (object *)cm; X} X Xobject * Xclassmethodgetfunc(cm) -X register object *cm; +X register object *cm; X{ -X if (!is_classmethodobject(cm)) { -X err_badcall(); -X return NULL; -X } -X return ((classmethodobject *)cm)->cm_func; +X if (!is_classmethodobject(cm)) { +X err_badcall(); +X return NULL; +X } +X return ((classmethodobject *)cm)->cm_func; X} X Xobject * Xclassmethodgetself(cm) -X register object *cm; +X register object *cm; X{ -X if (!is_classmethodobject(cm)) { -X err_badcall(); -X return NULL; -X } -X return ((classmethodobject *)cm)->cm_self; +X if (!is_classmethodobject(cm)) { +X err_badcall(); +X return NULL; +X } +X return ((classmethodobject *)cm)->cm_self; X} X X/* Class method methods */ @@ -2453,43 +2453,43 @@ X X#define OFF(x) offsetof(classmethodobject, x) X Xstatic struct memberlist classmethod_memberlist[] = { -X {"cm_func", T_OBJECT, OFF(cm_func)}, -X {"cm_self", T_OBJECT, OFF(cm_self)}, -X {NULL} /* Sentinel */ +X {"cm_func", T_OBJECT, OFF(cm_func)}, +X {"cm_self", T_OBJECT, OFF(cm_self)}, +X {NULL} /* Sentinel */ X}; X Xstatic object * Xclassmethod_getattr(cm, name) -X register classmethodobject *cm; -X char *name; +X register classmethodobject *cm; +X char *name; X{ -X return getmember((char *)cm, classmethod_memberlist, name); +X return getmember((char *)cm, classmethod_memberlist, name); X} X Xstatic void Xclassmethod_dealloc(cm) -X register classmethodobject *cm; +X register classmethodobject *cm; X{ -X DECREF(cm->cm_func); -X DECREF(cm->cm_self); -X free((ANY *)cm); +X DECREF(cm->cm_func); +X DECREF(cm->cm_self); +X free((ANY *)cm); X} X Xtypeobject Classmethodtype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "class method", -X sizeof(classmethodobject), -X 0, -X classmethod_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X classmethod_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "class method", +X sizeof(classmethodobject), +X 0, +X classmethod_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X classmethod_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; EOF fi @@ -2502,12 +2502,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2529,283 +2529,283 @@ X X/* Standard Booleans */ X Xintobject FalseObject = { -X OB_HEAD_INIT(&Inttype) -X 0 +X OB_HEAD_INIT(&Inttype) +X 0 X}; X Xintobject TrueObject = { -X OB_HEAD_INIT(&Inttype) -X 1 +X OB_HEAD_INIT(&Inttype) +X 1 X}; X Xstatic object * Xerr_ovf() X{ -X err_setstr(OverflowError, "integer overflow"); -X return NULL; +X err_setstr(OverflowError, "integer overflow"); +X return NULL; X} X Xstatic object * Xerr_zdiv() X{ -X err_setstr(ZeroDivisionError, "integer division by zero"); -X return NULL; +X err_setstr(ZeroDivisionError, "integer division by zero"); +X return NULL; X} X X/* Integers are quite normal objects, to make object handling uniform. -X (Using odd pointers to represent integers would save much space -X but require extra checks for this special case throughout the code.) -X Since, a typical Python program spends much of its time allocating -X and deallocating integers, these operations should be very fast. -X Therefore we use a dedicated allocation scheme with a much lower -X overhead (in space and time) than straight malloc(): a simple -X dedicated free list, filled when necessary with memory from malloc(). +X (Using odd pointers to represent integers would save much space +X but require extra checks for this special case throughout the code.) +X Since, a typical Python program spends much of its time allocating +X and deallocating integers, these operations should be very fast. +X Therefore we use a dedicated allocation scheme with a much lower +X overhead (in space and time) than straight malloc(): a simple +X dedicated free list, filled when necessary with memory from malloc(). X*/ X -X#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ -X#define N_INTOBJECTS (BLOCK_SIZE / sizeof(intobject)) +X#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ +X#define N_INTOBJECTS (BLOCK_SIZE / sizeof(intobject)) X Xstatic intobject * Xfill_free_list() X{ -X intobject *p, *q; -X p = NEW(intobject, N_INTOBJECTS); -X if (p == NULL) -X return (intobject *)err_nomem(); -X q = p + N_INTOBJECTS; -X while (--q > p) -X *(intobject **)q = q-1; -X *(intobject **)q = NULL; -X return p + N_INTOBJECTS - 1; +X intobject *p, *q; +X p = NEW(intobject, N_INTOBJECTS); +X if (p == NULL) +X return (intobject *)err_nomem(); +X q = p + N_INTOBJECTS; +X while (--q > p) +X *(intobject **)q = q-1; +X *(intobject **)q = NULL; +X return p + N_INTOBJECTS - 1; X} X Xstatic intobject *free_list = NULL; X Xobject * Xnewintobject(ival) -X long ival; +X long ival; X{ -X register intobject *v; -X if (free_list == NULL) { -X if ((free_list = fill_free_list()) == NULL) -X return NULL; -X } -X v = free_list; -X free_list = *(intobject **)free_list; -X NEWREF(v); -X v->ob_type = &Inttype; -X v->ob_ival = ival; -X return (object *) v; +X register intobject *v; +X if (free_list == NULL) { +X if ((free_list = fill_free_list()) == NULL) +X return NULL; +X } +X v = free_list; +X free_list = *(intobject **)free_list; +X NEWREF(v); +X v->ob_type = &Inttype; +X v->ob_ival = ival; +X return (object *) v; X} X Xstatic void Xint_dealloc(v) -X intobject *v; +X intobject *v; X{ -X *(intobject **)v = free_list; -X free_list = v; +X *(intobject **)v = free_list; +X free_list = v; X} X Xlong Xgetintvalue(op) -X register object *op; +X register object *op; X{ -X if (!is_intobject(op)) { -X err_badcall(); -X return -1; -X } -X else -X return ((intobject *)op) -> ob_ival; +X if (!is_intobject(op)) { +X err_badcall(); +X return -1; +X } +X else +X return ((intobject *)op) -> ob_ival; X} X X/* Methods */ X Xstatic void Xint_print(v, fp, flags) -X intobject *v; -X FILE *fp; -X int flags; +X intobject *v; +X FILE *fp; +X int flags; X{ -X fprintf(fp, "%ld", v->ob_ival); +X fprintf(fp, "%ld", v->ob_ival); X} X Xstatic object * Xint_repr(v) -X intobject *v; +X intobject *v; X{ -X char buf[20]; -X sprintf(buf, "%ld", v->ob_ival); -X return newstringobject(buf); +X char buf[20]; +X sprintf(buf, "%ld", v->ob_ival); +X return newstringobject(buf); X} X Xstatic int Xint_compare(v, w) -X intobject *v, *w; +X intobject *v, *w; X{ -X register long i = v->ob_ival; -X register long j = w->ob_ival; -X return (i < j) ? -1 : (i > j) ? 1 : 0; +X register long i = v->ob_ival; +X register long j = w->ob_ival; +X return (i < j) ? -1 : (i > j) ? 1 : 0; X} X Xstatic object * Xint_add(v, w) -X intobject *v; -X register object *w; +X intobject *v; +X register object *w; X{ -X register long a, b, x; -X if (!is_intobject(w)) { -X err_badarg(); -X return NULL; -X } -X a = v->ob_ival; -X b = ((intobject *)w) -> ob_ival; -X x = a + b; -X if ((x^a) < 0 && (x^b) < 0) -X return err_ovf(); -X return newintobject(x); +X register long a, b, x; +X if (!is_intobject(w)) { +X err_badarg(); +X return NULL; +X } +X a = v->ob_ival; +X b = ((intobject *)w) -> ob_ival; +X x = a + b; +X if ((x^a) < 0 && (x^b) < 0) +X return err_ovf(); +X return newintobject(x); X} X Xstatic object * Xint_sub(v, w) -X intobject *v; -X register object *w; +X intobject *v; +X register object *w; X{ -X register long a, b, x; -X if (!is_intobject(w)) { -X err_badarg(); -X return NULL; -X } -X a = v->ob_ival; -X b = ((intobject *)w) -> ob_ival; -X x = a - b; -X if ((x^a) < 0 && (x^~b) < 0) -X return err_ovf(); -X return newintobject(x); +X register long a, b, x; +X if (!is_intobject(w)) { +X err_badarg(); +X return NULL; +X } +X a = v->ob_ival; +X b = ((intobject *)w) -> ob_ival; +X x = a - b; +X if ((x^a) < 0 && (x^~b) < 0) +X return err_ovf(); +X return newintobject(x); X} X Xstatic object * Xint_mul(v, w) -X intobject *v; -X register object *w; +X intobject *v; +X register object *w; X{ -X register long a, b; -X double x; -X if (!is_intobject(w)) { -X err_badarg(); -X return NULL; -X } -X a = v->ob_ival; -X b = ((intobject *)w) -> ob_ival; -X x = (double)a * (double)b; -X if (x > 0x7fffffff || x < (double) (long) 0x80000000) -X return err_ovf(); -X return newintobject(a * b); +X register long a, b; +X double x; +X if (!is_intobject(w)) { +X err_badarg(); +X return NULL; +X } +X a = v->ob_ival; +X b = ((intobject *)w) -> ob_ival; +X x = (double)a * (double)b; +X if (x > 0x7fffffff || x < (double) (long) 0x80000000) +X return err_ovf(); +X return newintobject(a * b); X} X Xstatic object * Xint_div(v, w) -X intobject *v; -X register object *w; +X intobject *v; +X register object *w; X{ -X if (!is_intobject(w)) { -X err_badarg(); -X return NULL; -X } -X if (((intobject *)w) -> ob_ival == 0) -X return err_zdiv(); -X return newintobject(v->ob_ival / ((intobject *)w) -> ob_ival); +X if (!is_intobject(w)) { +X err_badarg(); +X return NULL; +X } +X if (((intobject *)w) -> ob_ival == 0) +X return err_zdiv(); +X return newintobject(v->ob_ival / ((intobject *)w) -> ob_ival); X} X Xstatic object * Xint_rem(v, w) -X intobject *v; -X register object *w; +X intobject *v; +X register object *w; X{ -X if (!is_intobject(w)) { -X err_badarg(); -X return NULL; -X } -X if (((intobject *)w) -> ob_ival == 0) -X return err_zdiv(); -X return newintobject(v->ob_ival % ((intobject *)w) -> ob_ival); +X if (!is_intobject(w)) { +X err_badarg(); +X return NULL; +X } +X if (((intobject *)w) -> ob_ival == 0) +X return err_zdiv(); +X return newintobject(v->ob_ival % ((intobject *)w) -> ob_ival); X} X Xstatic object * Xint_pow(v, w) -X intobject *v; -X register object *w; +X intobject *v; +X register object *w; X{ -X register long iv, iw, ix; -X register int neg; -X if (!is_intobject(w)) { -X err_badarg(); -X return NULL; -X } -X iv = v->ob_ival; -X iw = ((intobject *)w)->ob_ival; -X neg = 0; -X if (iw < 0) -X neg = 1, iw = -iw; -X ix = 1; -X for (; iw > 0; iw--) -X ix = ix * iv; -X if (neg) { -X if (ix == 0) -X return err_zdiv(); -X ix = 1/ix; -X } -X /* XXX How to check for overflow? */ -X return newintobject(ix); +X register long iv, iw, ix; +X register int neg; +X if (!is_intobject(w)) { +X err_badarg(); +X return NULL; +X } +X iv = v->ob_ival; +X iw = ((intobject *)w)->ob_ival; +X neg = 0; +X if (iw < 0) +X neg = 1, iw = -iw; +X ix = 1; +X for (; iw > 0; iw--) +X ix = ix * iv; +X if (neg) { +X if (ix == 0) +X return err_zdiv(); +X ix = 1/ix; +X } +X /* XXX How to check for overflow? */ +X return newintobject(ix); X} X Xstatic object * Xint_neg(v) -X intobject *v; +X intobject *v; X{ -X register long a, x; -X a = v->ob_ival; -X x = -a; -X if (a < 0 && x < 0) -X return err_ovf(); -X return newintobject(x); +X register long a, x; +X a = v->ob_ival; +X x = -a; +X if (a < 0 && x < 0) +X return err_ovf(); +X return newintobject(x); X} X Xstatic object * Xint_pos(v) -X intobject *v; +X intobject *v; X{ -X INCREF(v); -X return (object *)v; +X INCREF(v); +X return (object *)v; X} X Xstatic number_methods int_as_number = { -X int_add, /*tp_add*/ -X int_sub, /*tp_subtract*/ -X int_mul, /*tp_multiply*/ -X int_div, /*tp_divide*/ -X int_rem, /*tp_remainder*/ -X int_pow, /*tp_power*/ -X int_neg, /*tp_negate*/ -X int_pos, /*tp_plus*/ +X int_add, /*tp_add*/ +X int_sub, /*tp_subtract*/ +X int_mul, /*tp_multiply*/ +X int_div, /*tp_divide*/ +X int_rem, /*tp_remainder*/ +X int_pow, /*tp_power*/ +X int_neg, /*tp_negate*/ +X int_pos, /*tp_plus*/ X}; X Xtypeobject Inttype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "int", -X sizeof(intobject), -X 0, -X int_dealloc, /*tp_dealloc*/ -X int_print, /*tp_print*/ -X 0, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X int_compare, /*tp_compare*/ -X int_repr, /*tp_repr*/ -X &int_as_number, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "int", +X sizeof(intobject), +X 0, +X int_dealloc, /*tp_dealloc*/ +X int_print, /*tp_print*/ +X 0, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X int_compare, /*tp_compare*/ +X int_repr, /*tp_repr*/ +X &int_as_number, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; EOF fi echo 'Part 13 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-14-21.shar b/shar/python-0.9.1-14-21.shar index c819377..bdccfcf 100644 --- a/shar/python-0.9.1-14-21.shar +++ b/shar/python-0.9.1-14-21.shar @@ -26,14 +26,14 @@ Xfrom WindowParent import WindowParent Xfrom HVSplit import HSplit, VSplit X Xclass TimeOutToggleButton() = ToggleButton(): -X def define(self, parent): -X self = ToggleButton.define(self, parent) -X self.parent.need_timer(self) -X self.timer_hook = 0 -X return self -X def timer(self): -X if self.timer_hook: -X self.timer_hook(self) +X def define(self, parent): +X self = ToggleButton.define(self, parent) +X self.parent.need_timer(self) +X self.timer_hook = 0 +X return self +X def timer(self): +X if self.timer_hook: +X self.timer_hook(self) X XK = 1024 XBUFSIZE = 30*8*K @@ -44,241 +44,241 @@ Xclass Struct(): pass XG = Struct() X Xdef main(): -X # -X # Set default state -X # -X G.gain = 60 -X G.rate = 3 -X G.nomuting = 0 -X G.savefile = '@rec' -X # -X # Set default values -X # -X G.data = '' -X G.playing = 0 -X G.recording = 0 -X G.sogram = 0 -X # -X # Parse options -X # -X optlist, args = getopt.getopt(sys.argv[1:], 'mdg:r:') -X # -X for optname, optarg in optlist: -X if 0: # (So all cases start with elif) -X pass -X elif optname = '-d': -X G.debug = 1 -X elif optname = '-g': -X G.gain = string.atoi(optarg) -X if not (0 < G.gain < 256): -X raise optarg.error, '-g gain out of range' -X elif optname = '-m': -X G.nomuting = (not G.nomuting) -X elif optname = '-r': -X G.rate = string.atoi(optarg) -X if not (1 <= G.rate <= 3): -X raise optarg.error, '-r rate out of range' -X # -X if args: -X G.savefile = args[0] -X # -X # Initialize the sound package -X # -X audio.setoutgain(G.nomuting * G.gain) # Silence the speaker -X audio.setrate(G.rate) -X # -X # Create the WindowParent and VSplit -X # -X G.window = WindowParent().create('Recorder', (0, 0)) -X w = G.vsplit = VSplit().create(G.window) -X # -X # VU-meter -X # -X G.vubtn = VUMeter().define(w) -X # -X # Radiobuttons for rates -X # -X r1btn = RadioButton().definetext(w, '32 K/sec') -X r1btn.on_hook = rate_hook -X r1btn.rate = 1 -X # -X r2btn = RadioButton().definetext(w, '16 K/sec') -X r2btn.on_hook = rate_hook -X r2btn.rate = 2 -X # -X r3btn = RadioButton().definetext(w, '8 K/sec') -X r3btn.on_hook = rate_hook -X r3btn.rate = 3 -X # -X radios = [r1btn, r2btn, r3btn] -X r1btn.group = r2btn.group = r3btn.group = radios -X for r in radios: -X if r.rate = G.rate: r.select(1) -X # -X # Other controls -X # -X G.recbtn = TimeOutToggleButton().definetext(w, 'Record') -X G.recbtn.on_hook = record_on_hook -X G.recbtn.timer_hook = record_timer_hook -X G.recbtn.off_hook = record_off_hook -X # -X G.mutebtn = CheckButton().definetext(w, 'Mute') -X G.mutebtn.select(not G.nomuting) -X G.mutebtn.hook = mute_hook -X # -X G.playbtn = TimeOutToggleButton().definetext(w, 'Playback') -X G.playbtn.on_hook = play_on_hook -X G.playbtn.timer_hook = play_timer_hook -X G.playbtn.off_hook = play_off_hook -X # -X G.gainbtn = ComplexSlider().define(w) -X G.gainbtn.settexts(' Volume: ', ' ') -X G.gainbtn.setminvalmax(0, G.gain, 255) -X G.gainbtn.sethook(gain_hook) -X # -X G.sizebtn = Label().definetext(w, `len(G.data)` + ' bytes') -X # -X #G.showbtn = PushButton().definetext(w, 'Sound-o-gram...') -X #G.showbtn.hook = show_hook -X # -X G.savebtn = PushButton().definetext(w, 'Save...') -X G.savebtn.hook = save_hook -X # -X G.quitbtn = PushButton().definetext(w, 'Quit') -X G.quitbtn.hook = quit_hook -X G.playbtn.enable(0) -X G.savebtn.enable(0) -X #G.showbtn.enable(0) -X start_vu() -X G.window.realize() -X # -X # Event loop -X # -X while 1: -X e = stdwin.getevent() -X G.window.dispatch(e) +X # +X # Set default state +X # +X G.gain = 60 +X G.rate = 3 +X G.nomuting = 0 +X G.savefile = '@rec' +X # +X # Set default values +X # +X G.data = '' +X G.playing = 0 +X G.recording = 0 +X G.sogram = 0 +X # +X # Parse options +X # +X optlist, args = getopt.getopt(sys.argv[1:], 'mdg:r:') +X # +X for optname, optarg in optlist: +X if 0: # (So all cases start with elif) +X pass +X elif optname = '-d': +X G.debug = 1 +X elif optname = '-g': +X G.gain = string.atoi(optarg) +X if not (0 < G.gain < 256): +X raise optarg.error, '-g gain out of range' +X elif optname = '-m': +X G.nomuting = (not G.nomuting) +X elif optname = '-r': +X G.rate = string.atoi(optarg) +X if not (1 <= G.rate <= 3): +X raise optarg.error, '-r rate out of range' +X # +X if args: +X G.savefile = args[0] +X # +X # Initialize the sound package +X # +X audio.setoutgain(G.nomuting * G.gain) # Silence the speaker +X audio.setrate(G.rate) +X # +X # Create the WindowParent and VSplit +X # +X G.window = WindowParent().create('Recorder', (0, 0)) +X w = G.vsplit = VSplit().create(G.window) +X # +X # VU-meter +X # +X G.vubtn = VUMeter().define(w) +X # +X # Radiobuttons for rates +X # +X r1btn = RadioButton().definetext(w, '32 K/sec') +X r1btn.on_hook = rate_hook +X r1btn.rate = 1 +X # +X r2btn = RadioButton().definetext(w, '16 K/sec') +X r2btn.on_hook = rate_hook +X r2btn.rate = 2 +X # +X r3btn = RadioButton().definetext(w, '8 K/sec') +X r3btn.on_hook = rate_hook +X r3btn.rate = 3 +X # +X radios = [r1btn, r2btn, r3btn] +X r1btn.group = r2btn.group = r3btn.group = radios +X for r in radios: +X if r.rate = G.rate: r.select(1) +X # +X # Other controls +X # +X G.recbtn = TimeOutToggleButton().definetext(w, 'Record') +X G.recbtn.on_hook = record_on_hook +X G.recbtn.timer_hook = record_timer_hook +X G.recbtn.off_hook = record_off_hook +X # +X G.mutebtn = CheckButton().definetext(w, 'Mute') +X G.mutebtn.select(not G.nomuting) +X G.mutebtn.hook = mute_hook +X # +X G.playbtn = TimeOutToggleButton().definetext(w, 'Playback') +X G.playbtn.on_hook = play_on_hook +X G.playbtn.timer_hook = play_timer_hook +X G.playbtn.off_hook = play_off_hook +X # +X G.gainbtn = ComplexSlider().define(w) +X G.gainbtn.settexts(' Volume: ', ' ') +X G.gainbtn.setminvalmax(0, G.gain, 255) +X G.gainbtn.sethook(gain_hook) +X # +X G.sizebtn = Label().definetext(w, `len(G.data)` + ' bytes') +X # +X #G.showbtn = PushButton().definetext(w, 'Sound-o-gram...') +X #G.showbtn.hook = show_hook +X # +X G.savebtn = PushButton().definetext(w, 'Save...') +X G.savebtn.hook = save_hook +X # +X G.quitbtn = PushButton().definetext(w, 'Quit') +X G.quitbtn.hook = quit_hook +X G.playbtn.enable(0) +X G.savebtn.enable(0) +X #G.showbtn.enable(0) +X start_vu() +X G.window.realize() +X # +X # Event loop +X # +X while 1: +X e = stdwin.getevent() +X G.window.dispatch(e) X X# XXX Disabled... Xdef show_hook(self): -X savetext = self.text -X self.settext('Be patient...') -X close_sogram() -X stdwin.setdefwinsize(400, 300) -X win = stdwin.open('Sound-o-gram') -X G.sogram = Soundogram().define(win, G.data) -X win.buttons = [G.sogram] -X self.settext(savetext) +X savetext = self.text +X self.settext('Be patient...') +X close_sogram() +X stdwin.setdefwinsize(400, 300) +X win = stdwin.open('Sound-o-gram') +X G.sogram = Soundogram().define(win, G.data) +X win.buttons = [G.sogram] +X self.settext(savetext) X Xdef close_sogram(): -X if G.sogram: -X # Break circular references -X G.sogram.win.buttons[:] = [] -X del G.sogram.win -X G.sogram = 0 +X if G.sogram: +X # Break circular references +X G.sogram.win.buttons[:] = [] +X del G.sogram.win +X G.sogram = 0 X Xdef mute_hook(self): -X G.nomuting = (not self.selected) -X audio.setoutgain(G.nomuting * G.gain) +X G.nomuting = (not self.selected) +X audio.setoutgain(G.nomuting * G.gain) X Xdef rate_hook(self): -X G.rate = self.rate -X audio.setrate(G.rate) +X G.rate = self.rate +X audio.setrate(G.rate) X Xdef record_on_hook(self): -X stop_vu() -X close_sogram() -X audio.setrate(G.rate) -X audio.setoutgain(G.nomuting * G.gain) -X audio.start_recording(BUFSIZE) -X G.recording = 1 -X G.playbtn.enable(0) -X G.window.settimer(10 * BUFSIZE / Rates[G.rate]) +X stop_vu() +X close_sogram() +X audio.setrate(G.rate) +X audio.setoutgain(G.nomuting * G.gain) +X audio.start_recording(BUFSIZE) +X G.recording = 1 +X G.playbtn.enable(0) +X G.window.settimer(10 * BUFSIZE / Rates[G.rate]) X Xdef record_timer_hook(self): -X if G.recording: -X if audio.poll_recording(): -X self.hilite(0) -X record_off_hook(self) -X else: -X self.parent.settimer(5) +X if G.recording: +X if audio.poll_recording(): +X self.hilite(0) +X record_off_hook(self) +X else: +X self.parent.settimer(5) X Xdef record_off_hook(self): -X if not G.recording: -X return -X G.data = audio.stop_recording() -X G.recording = 0 -X G.sizebtn.settext(`len(G.data)` + ' bytes') -X audio.setoutgain(G.nomuting * G.gain) -X G.playbtn.enable((len(G.data) > 0)) -X G.savebtn.enable((len(G.data) > 0)) -X #G.showbtn.enable((len(G.data) > 0)) -X G.window.settimer(0) -X start_vu() +X if not G.recording: +X return +X G.data = audio.stop_recording() +X G.recording = 0 +X G.sizebtn.settext(`len(G.data)` + ' bytes') +X audio.setoutgain(G.nomuting * G.gain) +X G.playbtn.enable((len(G.data) > 0)) +X G.savebtn.enable((len(G.data) > 0)) +X #G.showbtn.enable((len(G.data) > 0)) +X G.window.settimer(0) +X start_vu() X Xdef play_on_hook(self): -X stop_vu() -X audio.setrate(G.rate) -X audio.setoutgain(G.gain) -X audio.start_playing(G.data) -X G.playing = 1 -X G.recbtn.enable(0) -X G.window.settimer(max(10 * len(G.data) / Rates[G.rate], 1)) +X stop_vu() +X audio.setrate(G.rate) +X audio.setoutgain(G.gain) +X audio.start_playing(G.data) +X G.playing = 1 +X G.recbtn.enable(0) +X G.window.settimer(max(10 * len(G.data) / Rates[G.rate], 1)) X Xdef play_timer_hook(self): -X if G.playing: -X if audio.poll_playing(): -X self.hilite(0) -X play_off_hook(self) -X else: -X self.parent.settimer(5) +X if G.playing: +X if audio.poll_playing(): +X self.hilite(0) +X play_off_hook(self) +X else: +X self.parent.settimer(5) X Xdef play_off_hook(self): -X if not G.playing: -X return -X x = audio.stop_playing() -X G.playing = 0 -X audio.setoutgain(G.nomuting * G.gain) -X G.recbtn.enable(1) -X G.window.settimer(0) -X start_vu() +X if not G.playing: +X return +X x = audio.stop_playing() +X G.playing = 0 +X audio.setoutgain(G.nomuting * G.gain) +X G.recbtn.enable(1) +X G.window.settimer(0) +X start_vu() X Xdef gain_hook(self): -X G.gain = self.val -X if G.playing or G.nomuting: audio.setoutgain(G.gain) +X G.gain = self.val +X if G.playing or G.nomuting: audio.setoutgain(G.gain) X Xdef save_hook(self): -X if not G.data: -X stdwin.fleep() -X else: -X prompt = 'Store sampled data on file: ' -X try: -X G.savefile = stdwin.askfile(prompt, G.savefile, 1) -X except KeyboardInterrupt: -X return -X try: -X fp = open(G.savefile, 'w') -X fp.write(Magics[G.rate] + G.data) -X except: -X stdwin.message('Cannot create ' + file) +X if not G.data: +X stdwin.fleep() +X else: +X prompt = 'Store sampled data on file: ' +X try: +X G.savefile = stdwin.askfile(prompt, G.savefile, 1) +X except KeyboardInterrupt: +X return +X try: +X fp = open(G.savefile, 'w') +X fp.write(Magics[G.rate] + G.data) +X except: +X stdwin.message('Cannot create ' + file) X Xdef stop_vu(): -X G.vubtn.stop() +X G.vubtn.stop() X Xdef start_vu(): -X G.vubtn.start() +X G.vubtn.start() X XExit = 'exit' # exception X Xdef quit_hook(self): -X raise Exit, 0 +X raise Exit, 0 X Xtry: -X try: -X main() -X finally: -X audio.setoutgain(0) +X try: +X main() +X finally: +X audio.setoutgain(0) Xexcept Exit, sts: -X sys.exit(sts) +X sys.exit(sts) EOF chmod +x 'demo/sgi/audio_stdwin/rec.py' fi @@ -299,249 +299,249 @@ X XUsageError = TclRuntimeError X Xclass ShellInterpreter() = Interpreter(): -X # -X def ResetVariables(interp): -X interp.globals['ps1'] = '$ ' -X interp.globals['ps2'] = '> ' -X interp.globals['home'] = mac.getcwd() -X # -X def DefineCommands(interp): -X interp.commands['cd'] = interp.CdCmd -X interp.commands['grep'] = interp.GrepCmd -X interp.commands['ls'] = interp.LsCmd -X interp.commands['mkdir'] = interp.MkdirCmd -X interp.commands['mv'] = interp.MvCmd -X interp.commands['pg'] = interp.PgCmd -X interp.commands['pwd'] = interp.PwdCmd -X interp.commands['rm'] = interp.RmCmd -X interp.commands['rmdir'] = interp.RmdirCmd -X interp.commands['sync'] = interp.SyncCmd -X # -X def Reset(interp): -X interp.ResetVariables() -X interp.DefineCommands() -X # -X def Create(interp): -X interp = Interpreter.Create(interp) # initialize base class -X interp.Reset() -X return interp -X # -X # Command-implementing functions -X # -X def CdCmd(interp, argv): -X if len(argv) > 2: -X raise UsageError, 'usage: cd [dirname]' -X if len(argv) = 2: -X chdirto(argv[1]) -X else: -X chdirto(interp.globals['home']) -X return '' -X # -X def GrepCmd(interp, argv): -X if len(argv) < 3: -X raise UsageError, 'usage: grep regexp file ...' -X import regexp -X try: -X prog = regexp.compile(argv[1]) -X except regexp.error, msg: -X raise TclRuntimeError, \ -X ('grep', argv[1], ': bad regexp :', msg) -X for file in argv[2:]: -X grepfile(prog, file) -X return '' -X # -X def LsCmd(interp, argv): -X if len(argv) < 2: -X lsdir(':') -X else: -X for dirname in argv[1:]: -X lsdir(dirname) -X return '' -X # -X def MkdirCmd(interp, argv): -X if len(argv) < 2: -X raise UsageError, 'usage: mkdir name ...' -X for name in argv[1:]: -X makedir(name) -X return '' -X # -X def MvCmd(interp, argv): -X if len(argv) <> 3: -X raise UsageError, 'usage: mv src dst' -X src, dst = argv[1], argv[2] -X if not exists(src): -X raise TclRuntimeError, \ -X ('mv', src, dst, ': source does not exist') -X if exists(dst): -X raise TclRuntimeError, \ -X ('mv', src, dst, ': destination already exists') -X try: -X mac.rename(src, dst) -X except mac.error, msg: -X raise TclRuntimeError, \ -X (src, dst, ': rename failed :', msg) -X return '' -X # -X def PgCmd(interp, argv): -X if len(argv) < 2: -X raise UsageError, 'usage: page file ...' -X for name in argv[1:]: -X pagefile(name) -X return '' -X # -X def PwdCmd(interp, argv): -X if len(argv) > 1: -X raise UsageError, 'usage: pwd' -X else: -X return mac.getcwd() -X # -X def RmCmd(interp, argv): -X if len(argv) < 2: -X raise UsageError, 'usage: rm file ...' -X for name in argv[1:]: -X remove(name) -X return '' -X # -X def RmdirCmd(interp, argv): -X if len(argv) < 2: -X raise UsageError, 'usage: rmdir dir ...' -X for name in argv[1:]: -X rmdir(name) -X return '' -X # -X def SyncCmd(interp, argv): -X if len(argv) > 1: -X raise UsageError, 'usage: sync' -X try: -X mac.sync() -X except mac.error, msg: -X raise TclRuntimeError, ('sync failed :', msg) -X # +X # +X def ResetVariables(interp): +X interp.globals['ps1'] = '$ ' +X interp.globals['ps2'] = '> ' +X interp.globals['home'] = mac.getcwd() +X # +X def DefineCommands(interp): +X interp.commands['cd'] = interp.CdCmd +X interp.commands['grep'] = interp.GrepCmd +X interp.commands['ls'] = interp.LsCmd +X interp.commands['mkdir'] = interp.MkdirCmd +X interp.commands['mv'] = interp.MvCmd +X interp.commands['pg'] = interp.PgCmd +X interp.commands['pwd'] = interp.PwdCmd +X interp.commands['rm'] = interp.RmCmd +X interp.commands['rmdir'] = interp.RmdirCmd +X interp.commands['sync'] = interp.SyncCmd +X # +X def Reset(interp): +X interp.ResetVariables() +X interp.DefineCommands() +X # +X def Create(interp): +X interp = Interpreter.Create(interp) # initialize base class +X interp.Reset() +X return interp +X # +X # Command-implementing functions +X # +X def CdCmd(interp, argv): +X if len(argv) > 2: +X raise UsageError, 'usage: cd [dirname]' +X if len(argv) = 2: +X chdirto(argv[1]) +X else: +X chdirto(interp.globals['home']) +X return '' +X # +X def GrepCmd(interp, argv): +X if len(argv) < 3: +X raise UsageError, 'usage: grep regexp file ...' +X import regexp +X try: +X prog = regexp.compile(argv[1]) +X except regexp.error, msg: +X raise TclRuntimeError, \ +X ('grep', argv[1], ': bad regexp :', msg) +X for file in argv[2:]: +X grepfile(prog, file) +X return '' +X # +X def LsCmd(interp, argv): +X if len(argv) < 2: +X lsdir(':') +X else: +X for dirname in argv[1:]: +X lsdir(dirname) +X return '' +X # +X def MkdirCmd(interp, argv): +X if len(argv) < 2: +X raise UsageError, 'usage: mkdir name ...' +X for name in argv[1:]: +X makedir(name) +X return '' +X # +X def MvCmd(interp, argv): +X if len(argv) <> 3: +X raise UsageError, 'usage: mv src dst' +X src, dst = argv[1], argv[2] +X if not exists(src): +X raise TclRuntimeError, \ +X ('mv', src, dst, ': source does not exist') +X if exists(dst): +X raise TclRuntimeError, \ +X ('mv', src, dst, ': destination already exists') +X try: +X mac.rename(src, dst) +X except mac.error, msg: +X raise TclRuntimeError, \ +X (src, dst, ': rename failed :', msg) +X return '' +X # +X def PgCmd(interp, argv): +X if len(argv) < 2: +X raise UsageError, 'usage: page file ...' +X for name in argv[1:]: +X pagefile(name) +X return '' +X # +X def PwdCmd(interp, argv): +X if len(argv) > 1: +X raise UsageError, 'usage: pwd' +X else: +X return mac.getcwd() +X # +X def RmCmd(interp, argv): +X if len(argv) < 2: +X raise UsageError, 'usage: rm file ...' +X for name in argv[1:]: +X remove(name) +X return '' +X # +X def RmdirCmd(interp, argv): +X if len(argv) < 2: +X raise UsageError, 'usage: rmdir dir ...' +X for name in argv[1:]: +X rmdir(name) +X return '' +X # +X def SyncCmd(interp, argv): +X if len(argv) > 1: +X raise UsageError, 'usage: sync' +X try: +X mac.sync() +X except mac.error, msg: +X raise TclRuntimeError, ('sync failed :', msg) +X # X Xdef chdirto(dirname): -X try: -X mac.chdir(dirname) -X except mac.error, msg: -X raise TclRuntimeError, (dirname, ': chdir failed :', msg) +X try: +X mac.chdir(dirname) +X except mac.error, msg: +X raise TclRuntimeError, (dirname, ': chdir failed :', msg) X Xdef grepfile(prog, file): -X try: -X fp = open(file, 'r') -X except RuntimeError, msg: -X raise TclRuntimeError, (file, ': open failed :', msg) -X lineno = 0 -X while 1: -X line = fp.readline() -X if not line: break -X lineno = lineno+1 -X if prog.exec(line): -X print file+'('+`lineno`+'):', line, +X try: +X fp = open(file, 'r') +X except RuntimeError, msg: +X raise TclRuntimeError, (file, ': open failed :', msg) +X lineno = 0 +X while 1: +X line = fp.readline() +X if not line: break +X lineno = lineno+1 +X if prog.exec(line): +X print file+'('+`lineno`+'):', line, X Xdef lsdir(dirname): -X if not isdir(dirname): -X print dirname, ': no such directory' -X return -X names = mac.listdir(dirname) -X lsfiles(names, dirname) +X if not isdir(dirname): +X print dirname, ': no such directory' +X return +X names = mac.listdir(dirname) +X lsfiles(names, dirname) X Xdef lsfiles(names, dirname): -X names = names[:] # Make a copy so we can modify it -X for i in range(len(names)): -X name = names[i] -X if isdir(macpath.cat(dirname, name)): -X names[i] = ':' + name + ':' -X columnize(names) +X names = names[:] # Make a copy so we can modify it +X for i in range(len(names)): +X name = names[i] +X if isdir(macpath.cat(dirname, name)): +X names[i] = ':' + name + ':' +X columnize(names) X Xdef makedir(name): -X if exists(name): -X print name, ': already exists' -X return -X try: -X mac.mkdir(name, 0777) -X except mac.error, msg: -X raise TclRuntimeError, (name, ': mkdir failed :', msg) +X if exists(name): +X print name, ': already exists' +X return +X try: +X mac.mkdir(name, 0777) +X except mac.error, msg: +X raise TclRuntimeError, (name, ': mkdir failed :', msg) X Xdef pagefile(name): -X import string -X if not isfile(name): -X print name, ': no such file' -X return -X LINES = 24 - 1 -X # For THINK C 3.0, make the path absolute: -X # if not macpath.isabs(name): -X # name = macpath.cat(mac.getcwd(), name) -X try: -X fp = open(name, 'r') -X except RuntimeError, msg: -X raise TclRuntimeError, (name, ': open failed :', msg) -X line = fp.readline() -X while line: -X for i in range(LINES): -X print line, -X line = fp.readline() -X if not line: break -X if line: -X try: -X more = raw_input('[more]') -X except (EOFError, KeyboardInterrupt): -X print -X break -X if string.strip(more)[:1] in ('q', 'Q'): -X break +X import string +X if not isfile(name): +X print name, ': no such file' +X return +X LINES = 24 - 1 +X # For THINK C 3.0, make the path absolute: +X # if not macpath.isabs(name): +X # name = macpath.cat(mac.getcwd(), name) +X try: +X fp = open(name, 'r') +X except RuntimeError, msg: +X raise TclRuntimeError, (name, ': open failed :', msg) +X line = fp.readline() +X while line: +X for i in range(LINES): +X print line, +X line = fp.readline() +X if not line: break +X if line: +X try: +X more = raw_input('[more]') +X except (EOFError, KeyboardInterrupt): +X print +X break +X if string.strip(more)[:1] in ('q', 'Q'): +X break X Xdef remove(name): -X if not isfile(name): -X print name, ': no such file' -X return -X try: -X mac.unlink(name) -X except mac.error, msg: -X raise TclRuntimeError, (name, ': unlink failed :', msg) +X if not isfile(name): +X print name, ': no such file' +X return +X try: +X mac.unlink(name) +X except mac.error, msg: +X raise TclRuntimeError, (name, ': unlink failed :', msg) X Xdef rmdir(name): -X if not isdir(name): -X raise TclRuntimeError, (name, ': no such directory') -X try: -X mac.rmdir(name) -X except mac.error, msg: -X raise TclRuntimeError, (name, ': rmdir failed :', msg) +X if not isdir(name): +X raise TclRuntimeError, (name, ': no such directory') +X try: +X mac.rmdir(name) +X except mac.error, msg: +X raise TclRuntimeError, (name, ': rmdir failed :', msg) X Xdef printlist(list): -X for word in list: -X print word, +X for word in list: +X print word, X Xdef columnize(list): -X import string -X COLUMNS = 80-1 -X n = len(list) -X colwidth = maxwidth(list) -X ncols = (COLUMNS + 1) / (colwidth + 1) -X if ncols < 1: ncols = 1 -X nrows = (n + ncols - 1) / ncols -X for irow in range(nrows): -X line = '' -X for icol in range(ncols): -X i = irow + nrows*icol -X if 0 <= i < n: -X word = list[i] -X if i+nrows < n: -X word = string.ljust(word, colwidth) -X if icol > 0: -X word = ' ' + word -X line = line + word -X print line +X import string +X COLUMNS = 80-1 +X n = len(list) +X colwidth = maxwidth(list) +X ncols = (COLUMNS + 1) / (colwidth + 1) +X if ncols < 1: ncols = 1 +X nrows = (n + ncols - 1) / ncols +X for irow in range(nrows): +X line = '' +X for icol in range(ncols): +X i = irow + nrows*icol +X if 0 <= i < n: +X word = list[i] +X if i+nrows < n: +X word = string.ljust(word, colwidth) +X if icol > 0: +X word = ' ' + word +X line = line + word +X print line X Xdef maxwidth(list): -X width = 0 -X for word in list: -X if len(word) > width: -X width = len(word) -X return width +X width = 0 +X for word in list: +X if len(word) > width: +X width = len(word) +X return width X Xthe_interpreter = ShellInterpreter().Create() X Xdef main(): -X Tcl.MainLoop(the_interpreter) +X Tcl.MainLoop(the_interpreter) EOF fi if test -s 'lib/tablewin.py' @@ -553,11 +553,11 @@ X# Module 'tablewin' X X# Display a table, with per-item actions: X -X# A1 | A2 | A3 | .... | AN -X# B1 | B2 | B3 | .... | BN -X# C1 | C2 | C3 | .... | CN -X# .. | .. | .. | .... | .. -X# Z1 | Z2 | Z3 | .... | ZN +X# A1 | A2 | A3 | .... | AN +X# B1 | B2 | B3 | .... | BN +X# C1 | C2 | C3 | .... | CN +X# .. | .. | .. | .... | .. +X# Z1 | Z2 | Z3 | .... | ZN X X# Not all columns need to have the same length. X# The data structure is a list of columns; @@ -569,223 +569,223 @@ Ximport stdwin Ximport gwin X Xdef open(title, data): # Public function to open a table window -X # -X # Set geometry parameters (one day, these may be changeable) -X # -X margin = stdwin.textwidth(' ') -X lineheight = stdwin.lineheight() -X # -X # Geometry calculations -X # -X colstarts = [0] -X totwidth = 0 -X maxrows = 0 -X for coldata in data: -X # Height calculations -X rows = len(coldata) -X if rows > maxrows: maxrows = rows -X # Width calculations -X width = colwidth(coldata) + margin -X totwidth = totwidth + width -X colstarts.append(totwidth) -X # -X # Calculate document and window height -X # -X docwidth, docheight = totwidth, maxrows*lineheight -X winwidth, winheight = docwidth, docheight -X if winwidth > stdwin.textwidth('n')*100: winwidth = 0 -X if winheight > stdwin.lineheight()*30: winheight = 0 -X # -X # Create the window -X # -X stdwin.setdefwinsize(winwidth, winheight) -X w = gwin.open(title) -X # -X # Set properties and override methods -X # -X w.data = data -X w.margin = margin -X w.lineheight = lineheight -X w.colstarts = colstarts -X w.totwidth = totwidth -X w.maxrows = maxrows -X w.selection = (-1, -1) -X w.lastselection = (-1, -1) -X w.selshown = 0 -X w.setdocsize(docwidth, docheight) -X w.draw = draw -X w.mup = mup -X w.arrow = arrow -X # -X # Return -X # -X return w +X # +X # Set geometry parameters (one day, these may be changeable) +X # +X margin = stdwin.textwidth(' ') +X lineheight = stdwin.lineheight() +X # +X # Geometry calculations +X # +X colstarts = [0] +X totwidth = 0 +X maxrows = 0 +X for coldata in data: +X # Height calculations +X rows = len(coldata) +X if rows > maxrows: maxrows = rows +X # Width calculations +X width = colwidth(coldata) + margin +X totwidth = totwidth + width +X colstarts.append(totwidth) +X # +X # Calculate document and window height +X # +X docwidth, docheight = totwidth, maxrows*lineheight +X winwidth, winheight = docwidth, docheight +X if winwidth > stdwin.textwidth('n')*100: winwidth = 0 +X if winheight > stdwin.lineheight()*30: winheight = 0 +X # +X # Create the window +X # +X stdwin.setdefwinsize(winwidth, winheight) +X w = gwin.open(title) +X # +X # Set properties and override methods +X # +X w.data = data +X w.margin = margin +X w.lineheight = lineheight +X w.colstarts = colstarts +X w.totwidth = totwidth +X w.maxrows = maxrows +X w.selection = (-1, -1) +X w.lastselection = (-1, -1) +X w.selshown = 0 +X w.setdocsize(docwidth, docheight) +X w.draw = draw +X w.mup = mup +X w.arrow = arrow +X # +X # Return +X # +X return w X Xdef update(w, data): # Change the data -X # -X # Hide selection -X # -X hidesel(w, w.begindrawing()) -X # -X # Get old geometry parameters -X # -X margin = w.margin -X lineheight = w.lineheight -X # -X # Geometry calculations -X # -X colstarts = [0] -X totwidth = 0 -X maxrows = 0 -X for coldata in data: -X # Height calculations -X rows = len(coldata) -X if rows > maxrows: maxrows = rows -X # Width calculations -X width = colwidth(coldata) + margin -X totwidth = totwidth + width -X colstarts.append(totwidth) -X # -X # Calculate document and window height -X # -X docwidth, docheight = totwidth, maxrows*lineheight -X # -X # Set changed properties and change window size -X # -X w.data = data -X w.colstarts = colstarts -X w.totwidth = totwidth -X w.maxrows = maxrows -X w.change((0, 0), (10000, 10000)) -X w.setdocsize(docwidth, docheight) -X w.change((0, 0), (docwidth, docheight)) -X # -X # Show selection, or forget it if out of range -X # -X showsel(w, w.begindrawing()) -X if not w.selshown: w.selection = (-1, -1) +X # +X # Hide selection +X # +X hidesel(w, w.begindrawing()) +X # +X # Get old geometry parameters +X # +X margin = w.margin +X lineheight = w.lineheight +X # +X # Geometry calculations +X # +X colstarts = [0] +X totwidth = 0 +X maxrows = 0 +X for coldata in data: +X # Height calculations +X rows = len(coldata) +X if rows > maxrows: maxrows = rows +X # Width calculations +X width = colwidth(coldata) + margin +X totwidth = totwidth + width +X colstarts.append(totwidth) +X # +X # Calculate document and window height +X # +X docwidth, docheight = totwidth, maxrows*lineheight +X # +X # Set changed properties and change window size +X # +X w.data = data +X w.colstarts = colstarts +X w.totwidth = totwidth +X w.maxrows = maxrows +X w.change((0, 0), (10000, 10000)) +X w.setdocsize(docwidth, docheight) +X w.change((0, 0), (docwidth, docheight)) +X # +X # Show selection, or forget it if out of range +X # +X showsel(w, w.begindrawing()) +X if not w.selshown: w.selection = (-1, -1) X Xdef colwidth(coldata): # Subroutine to calculate column width -X maxwidth = 0 -X for string, action in coldata: -X width = stdwin.textwidth(string) -X if width > maxwidth: maxwidth = width -X return maxwidth +X maxwidth = 0 +X for string, action in coldata: +X width = stdwin.textwidth(string) +X if width > maxwidth: maxwidth = width +X return maxwidth X Xdef draw(w, ((left, top), (right, bottom))): # Draw method -X ileft = whichcol(w, left) -X iright = whichcol(w, right-1) + 1 -X if iright > len(w.data): iright = len(w.data) -X itop = divmod(top, w.lineheight)[0] -X if itop < 0: itop = 0 -X ibottom, remainder = divmod(bottom, w.lineheight) -X if remainder: ibottom = ibottom + 1 -X d = w.begindrawing() -X if ileft <= w.selection[0] < iright: -X if itop <= w.selection[1] < ibottom: -X hidesel(w, d) -X d.erase((left, top), (right, bottom)) -X for i in range(ileft, iright): -X col = w.data[i] -X jbottom = len(col) -X if ibottom < jbottom: jbottom = ibottom -X h = w.colstarts[i] -X v = itop * w.lineheight -X for j in range(itop, jbottom): -X string, action = col[j] -X d.text((h, v), string) -X v = v + w.lineheight -X showsel(w, d) +X ileft = whichcol(w, left) +X iright = whichcol(w, right-1) + 1 +X if iright > len(w.data): iright = len(w.data) +X itop = divmod(top, w.lineheight)[0] +X if itop < 0: itop = 0 +X ibottom, remainder = divmod(bottom, w.lineheight) +X if remainder: ibottom = ibottom + 1 +X d = w.begindrawing() +X if ileft <= w.selection[0] < iright: +X if itop <= w.selection[1] < ibottom: +X hidesel(w, d) +X d.erase((left, top), (right, bottom)) +X for i in range(ileft, iright): +X col = w.data[i] +X jbottom = len(col) +X if ibottom < jbottom: jbottom = ibottom +X h = w.colstarts[i] +X v = itop * w.lineheight +X for j in range(itop, jbottom): +X string, action = col[j] +X d.text((h, v), string) +X v = v + w.lineheight +X showsel(w, d) X Xdef mup(w, detail): # Mouse up method -X (h, v), nclicks, button, mask = detail -X icol = whichcol(w, h) -X if 0 <= icol < len(w.data): -X irow = divmod(v, w.lineheight)[0] -X col = w.data[icol] -X if 0 <= irow < len(col): -X string, action = col[irow] -X action(w, string, (icol, irow), detail) +X (h, v), nclicks, button, mask = detail +X icol = whichcol(w, h) +X if 0 <= icol < len(w.data): +X irow = divmod(v, w.lineheight)[0] +X col = w.data[icol] +X if 0 <= irow < len(col): +X string, action = col[irow] +X action(w, string, (icol, irow), detail) X Xdef whichcol(w, h): # Return column number (may be >= len(w.data)) -X for icol in range(0, len(w.data)): -X if h < w.colstarts[icol+1]: -X return icol -X return len(w.data) +X for icol in range(0, len(w.data)): +X if h < w.colstarts[icol+1]: +X return icol +X return len(w.data) X Xdef arrow(w, type): -X import stdwinsupport -X S = stdwinsupport -X if type = S.wc_left: -X incr = -1, 0 -X elif type = S.wc_up: -X incr = 0, -1 -X elif type = S.wc_right: -X incr = 1, 0 -X elif type = S.wc_down: -X incr = 0, 1 -X else: -X return -X icol, irow = w.lastselection -X icol = icol + incr[0] -X if icol < 0: icol = len(w.data)-1 -X if icol >= len(w.data): icol = 0 -X if 0 <= icol < len(w.data): -X irow = irow + incr[1] -X if irow < 0: irow = len(w.data[icol]) - 1 -X if irow >= len(w.data[icol]): irow = 0 -X else: -X irow = 0 -X if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): -X w.lastselection = icol, irow -X string, action = w.data[icol][irow] -X detail = (0, 0), 1, 1, 1 -X action(w, string, (icol, irow), detail) +X import stdwinsupport +X S = stdwinsupport +X if type = S.wc_left: +X incr = -1, 0 +X elif type = S.wc_up: +X incr = 0, -1 +X elif type = S.wc_right: +X incr = 1, 0 +X elif type = S.wc_down: +X incr = 0, 1 +X else: +X return +X icol, irow = w.lastselection +X icol = icol + incr[0] +X if icol < 0: icol = len(w.data)-1 +X if icol >= len(w.data): icol = 0 +X if 0 <= icol < len(w.data): +X irow = irow + incr[1] +X if irow < 0: irow = len(w.data[icol]) - 1 +X if irow >= len(w.data[icol]): irow = 0 +X else: +X irow = 0 +X if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): +X w.lastselection = icol, irow +X string, action = w.data[icol][irow] +X detail = (0, 0), 1, 1, 1 +X action(w, string, (icol, irow), detail) X X X# Selection management X# TO DO: allow multiple selected entries X Xdef select(w, selection): # Public function to set the item selection -X d = w.begindrawing() -X hidesel(w, d) -X w.selection = selection -X showsel(w, d) -X if w.selshown: lastselection = selection +X d = w.begindrawing() +X hidesel(w, d) +X w.selection = selection +X showsel(w, d) +X if w.selshown: lastselection = selection X Xdef hidesel(w, d): # Hide the selection, if shown -X if w.selshown: invertsel(w, d) +X if w.selshown: invertsel(w, d) X Xdef showsel(w, d): # Show the selection, if hidden -X if not w.selshown: invertsel(w, d) +X if not w.selshown: invertsel(w, d) X Xdef invertsel(w, d): # Invert the selection, if valid -X icol, irow = w.selection -X if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): -X left = w.colstarts[icol] -X right = w.colstarts[icol+1] -X top = irow * w.lineheight -X bottom = (irow+1) * w.lineheight -X d.invert((left, top), (right, bottom)) -X w.selshown = (not w.selshown) +X icol, irow = w.selection +X if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): +X left = w.colstarts[icol] +X right = w.colstarts[icol+1] +X top = irow * w.lineheight +X bottom = (irow+1) * w.lineheight +X d.invert((left, top), (right, bottom)) +X w.selshown = (not w.selshown) X X X# Demonstration X Xdef demo_action(w, string, (icol, irow), detail): # Action function for demo -X select(w, (irow, icol)) +X select(w, (irow, icol)) X Xdef demo(): # Demonstration -X da = demo_action # shorthand -X col0 = [('a1', da), ('bbb1', da), ('c1', da)] -X col1 = [('a2', da), ('bbb2', da)] -X col2 = [('a3', da), ('b3', da), ('c3', da), ('d4', da), ('d5', da)] -X col3 = [] -X for i in range(1, 31): col3.append('xxx' + `i`, da) -X data = [col0, col1, col2, col3] -X w = open('tablewin.demo', data) -X gwin.mainloop() -X return w +X da = demo_action # shorthand +X col0 = [('a1', da), ('bbb1', da), ('c1', da)] +X col1 = [('a2', da), ('bbb2', da)] +X col2 = [('a3', da), ('b3', da), ('c3', da), ('d4', da), ('d5', da)] +X col3 = [] +X for i in range(1, 31): col3.append('xxx' + `i`, da) +X data = [col0, col1, col2, col3] +X w = open('tablewin.demo', data) +X gwin.mainloop() +X return w EOF fi if test -s 'src/fileobject.c' @@ -797,12 +797,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -819,11 +819,11 @@ X******************************************************************/ X X/* File object implementation */ X -X/* XXX This should become a built-in module 'io'. It should support more -X functionality, better exception handling for invalid calls, etc. -X (Especially reading on a write-only file or vice versa!) -X It should also cooperate with posix to support popen(), which should -X share most code but have a special close function. */ +X/* XXX This should become a built-in module 'io'. It should support more +X functionality, better exception handling for invalid calls, etc. +X (Especially reading on a write-only file or vice versa!) +X It should also cooperate with posix to support popen(), which should +X share most code but have a special close function. */ X X#include "allobjects.h" X @@ -833,258 +833,258 @@ Xextern int errno; X#endif X Xtypedef struct { -X OB_HEAD -X FILE *f_fp; -X object *f_name; -X object *f_mode; -X /* XXX Should move the 'need space' on printing flag here */ +X OB_HEAD +X FILE *f_fp; +X object *f_name; +X object *f_mode; +X /* XXX Should move the 'need space' on printing flag here */ X} fileobject; X XFILE * Xgetfilefile(f) -X object *f; +X object *f; X{ -X if (!is_fileobject(f)) { -X err_badcall(); -X return NULL; -X } -X return ((fileobject *)f)->f_fp; +X if (!is_fileobject(f)) { +X err_badcall(); +X return NULL; +X } +X return ((fileobject *)f)->f_fp; X} X Xobject * Xnewopenfileobject(fp, name, mode) -X FILE *fp; -X char *name; -X char *mode; -X{ -X fileobject *f = NEWOBJ(fileobject, &Filetype); -X if (f == NULL) -X return NULL; -X f->f_fp = NULL; -X f->f_name = newstringobject(name); -X f->f_mode = newstringobject(mode); -X if (f->f_name == NULL || f->f_mode == NULL) { -X DECREF(f); -X return NULL; -X } -X f->f_fp = fp; -X return (object *) f; +X FILE *fp; +X char *name; +X char *mode; +X{ +X fileobject *f = NEWOBJ(fileobject, &Filetype); +X if (f == NULL) +X return NULL; +X f->f_fp = NULL; +X f->f_name = newstringobject(name); +X f->f_mode = newstringobject(mode); +X if (f->f_name == NULL || f->f_mode == NULL) { +X DECREF(f); +X return NULL; +X } +X f->f_fp = fp; +X return (object *) f; X} X Xobject * Xnewfileobject(name, mode) -X char *name, *mode; +X char *name, *mode; X{ -X fileobject *f; -X FILE *fp; -X f = (fileobject *) newopenfileobject((FILE *)NULL, name, mode); -X if (f == NULL) -X return NULL; +X fileobject *f; +X FILE *fp; +X f = (fileobject *) newopenfileobject((FILE *)NULL, name, mode); +X if (f == NULL) +X return NULL; X#ifdef THINK_C -X if (*mode == '*') { -X FILE *fopenRF(); -X f->f_fp = fopenRF(name, mode+1); -X } -X else +X if (*mode == '*') { +X FILE *fopenRF(); +X f->f_fp = fopenRF(name, mode+1); +X } +X else X#endif -X f->f_fp = fopen(name, mode); -X if (f->f_fp == NULL) { -X err_errno(RuntimeError); -X DECREF(f); -X return NULL; -X } -X return (object *)f; +X f->f_fp = fopen(name, mode); +X if (f->f_fp == NULL) { +X err_errno(RuntimeError); +X DECREF(f); +X return NULL; +X } +X return (object *)f; X} X X/* Methods */ X Xstatic void Xfile_dealloc(f) -X fileobject *f; +X fileobject *f; X{ -X if (f->f_fp != NULL) -X fclose(f->f_fp); -X if (f->f_name != NULL) -X DECREF(f->f_name); -X if (f->f_mode != NULL) -X DECREF(f->f_mode); -X free((char *)f); +X if (f->f_fp != NULL) +X fclose(f->f_fp); +X if (f->f_name != NULL) +X DECREF(f->f_name); +X if (f->f_mode != NULL) +X DECREF(f->f_mode); +X free((char *)f); X} X Xstatic void Xfile_print(f, fp, flags) -X fileobject *f; -X FILE *fp; -X int flags; +X fileobject *f; +X FILE *fp; +X int flags; X{ -X fprintf(fp, "<%s file ", f->f_fp == NULL ? "closed" : "open"); -X printobject(f->f_name, fp, flags); -X fprintf(fp, ", mode "); -X printobject(f->f_mode, fp, flags); -X fprintf(fp, ">"); +X fprintf(fp, "<%s file ", f->f_fp == NULL ? "closed" : "open"); +X printobject(f->f_name, fp, flags); +X fprintf(fp, ", mode "); +X printobject(f->f_mode, fp, flags); +X fprintf(fp, ">"); X} X Xstatic object * Xfile_repr(f) -X fileobject *f; +X fileobject *f; X{ -X char buf[300]; -X /* XXX This differs from file_print if the filename contains -X quotes or other funny characters. */ -X sprintf(buf, "<%s file '%.256s', mode '%.10s'>", -X f->f_fp == NULL ? "closed" : "open", -X getstringvalue(f->f_name), -X getstringvalue(f->f_mode)); -X return newstringobject(buf); +X char buf[300]; +X /* XXX This differs from file_print if the filename contains +X quotes or other funny characters. */ +X sprintf(buf, "<%s file '%.256s', mode '%.10s'>", +X f->f_fp == NULL ? "closed" : "open", +X getstringvalue(f->f_name), +X getstringvalue(f->f_mode)); +X return newstringobject(buf); X} X Xstatic object * Xfile_close(f, args) -X fileobject *f; -X object *args; +X fileobject *f; +X object *args; X{ -X if (args != NULL) { -X err_badarg(); -X return NULL; -X } -X if (f->f_fp != NULL) { -X fclose(f->f_fp); -X f->f_fp = NULL; -X } -X INCREF(None); -X return None; +X if (args != NULL) { +X err_badarg(); +X return NULL; +X } +X if (f->f_fp != NULL) { +X fclose(f->f_fp); +X f->f_fp = NULL; +X } +X INCREF(None); +X return None; X} X Xstatic object * Xfile_read(f, args) -X fileobject *f; -X object *args; -X{ -X int n; -X object *v; -X if (f->f_fp == NULL) { -X err_badarg(); -X return NULL; -X } -X if (args == NULL || !is_intobject(args)) { -X err_badarg(); -X return NULL; -X } -X n = getintvalue(args); -X if (n < 0) { -X err_badarg(); -X return NULL; -X } -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return NULL; -X n = fread(getstringvalue(v), 1, n, f->f_fp); -X /* EOF is reported as an empty string */ -X /* XXX should detect real I/O errors? */ -X resizestring(&v, n); -X return v; +X fileobject *f; +X object *args; +X{ +X int n; +X object *v; +X if (f->f_fp == NULL) { +X err_badarg(); +X return NULL; +X } +X if (args == NULL || !is_intobject(args)) { +X err_badarg(); +X return NULL; +X } +X n = getintvalue(args); +X if (n < 0) { +X err_badarg(); +X return NULL; +X } +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return NULL; +X n = fread(getstringvalue(v), 1, n, f->f_fp); +X /* EOF is reported as an empty string */ +X /* XXX should detect real I/O errors? */ +X resizestring(&v, n); +X return v; X} X X/* XXX Should this be unified with raw_input()? */ X Xstatic object * Xfile_readline(f, args) -X fileobject *f; -X object *args; -X{ -X int n; -X object *v; -X if (f->f_fp == NULL) { -X err_badarg(); -X return NULL; -X } -X if (args == NULL) { -X n = 10000; /* XXX should really be unlimited */ -X } -X else if (is_intobject(args)) { -X n = getintvalue(args); -X if (n < 0) { -X err_badarg(); -X return NULL; -X } -X } -X else { -X err_badarg(); -X return NULL; -X } -X v = newsizedstringobject((char *)NULL, n); -X if (v == NULL) -X return NULL; +X fileobject *f; +X object *args; +X{ +X int n; +X object *v; +X if (f->f_fp == NULL) { +X err_badarg(); +X return NULL; +X } +X if (args == NULL) { +X n = 10000; /* XXX should really be unlimited */ +X } +X else if (is_intobject(args)) { +X n = getintvalue(args); +X if (n < 0) { +X err_badarg(); +X return NULL; +X } +X } +X else { +X err_badarg(); +X return NULL; +X } +X v = newsizedstringobject((char *)NULL, n); +X if (v == NULL) +X return NULL; X#ifndef THINK_C_3_0 -X /* XXX Think C 3.0 wrongly reads up to n characters... */ -X n = n+1; +X /* XXX Think C 3.0 wrongly reads up to n characters... */ +X n = n+1; X#endif -X if (fgets(getstringvalue(v), n, f->f_fp) == NULL) { -X /* EOF is reported as an empty string */ -X /* XXX should detect real I/O errors? */ -X n = 0; -X } -X else { -X n = strlen(getstringvalue(v)); -X } -X resizestring(&v, n); -X return v; +X if (fgets(getstringvalue(v), n, f->f_fp) == NULL) { +X /* EOF is reported as an empty string */ +X /* XXX should detect real I/O errors? */ +X n = 0; +X } +X else { +X n = strlen(getstringvalue(v)); +X } +X resizestring(&v, n); +X return v; X} X Xstatic object * Xfile_write(f, args) -X fileobject *f; -X object *args; -X{ -X int n, n2; -X if (f->f_fp == NULL) { -X err_badarg(); -X return NULL; -X } -X if (args == NULL || !is_stringobject(args)) { -X err_badarg(); -X return NULL; -X } -X errno = 0; -X n2 = fwrite(getstringvalue(args), 1, n = getstringsize(args), f->f_fp); -X if (n2 != n) { -X if (errno == 0) -X errno = EIO; -X err_errno(RuntimeError); -X return NULL; -X } -X INCREF(None); -X return None; +X fileobject *f; +X object *args; +X{ +X int n, n2; +X if (f->f_fp == NULL) { +X err_badarg(); +X return NULL; +X } +X if (args == NULL || !is_stringobject(args)) { +X err_badarg(); +X return NULL; +X } +X errno = 0; +X n2 = fwrite(getstringvalue(args), 1, n = getstringsize(args), f->f_fp); +X if (n2 != n) { +X if (errno == 0) +X errno = EIO; +X err_errno(RuntimeError); +X return NULL; +X } +X INCREF(None); +X return None; X} X Xstatic struct methodlist file_methods[] = { -X {"write", file_write}, -X {"read", file_read}, -X {"readline", file_readline}, -X {"close", file_close}, -X {NULL, NULL} /* sentinel */ +X {"write", file_write}, +X {"read", file_read}, +X {"readline", file_readline}, +X {"close", file_close}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xfile_getattr(f, name) -X fileobject *f; -X char *name; +X fileobject *f; +X char *name; X{ -X return findmethod(file_methods, (object *)f, name); +X return findmethod(file_methods, (object *)f, name); X} X Xtypeobject Filetype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "file", -X sizeof(fileobject), -X 0, -X file_dealloc, /*tp_dealloc*/ -X file_print, /*tp_print*/ -X file_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X file_repr, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "file", +X sizeof(fileobject), +X 0, +X file_dealloc, /*tp_dealloc*/ +X file_print, /*tp_print*/ +X file_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X file_repr, /*tp_repr*/ X}; EOF fi @@ -1097,12 +1097,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1120,7 +1120,7 @@ X X/* Float object implementation */ X X/* XXX There should be overflow checks here, but it's hard to check -X for any kind of float exception without losing portability. */ +X for any kind of float exception without losing portability. */ X X#include "allobjects.h" X @@ -1139,227 +1139,227 @@ X#endif X Xobject * Xnewfloatobject(fval) -X double fval; +X double fval; X{ -X /* For efficiency, this code is copied from newobject() */ -X register floatobject *op = (floatobject *) malloc(sizeof(floatobject)); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = &Floattype; -X op->ob_fval = fval; -X return (object *) op; +X /* For efficiency, this code is copied from newobject() */ +X register floatobject *op = (floatobject *) malloc(sizeof(floatobject)); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = &Floattype; +X op->ob_fval = fval; +X return (object *) op; X} X Xdouble Xgetfloatvalue(op) -X object *op; +X object *op; X{ -X if (!is_floatobject(op)) { -X err_badarg(); -X return -1; -X } -X else -X return ((floatobject *)op) -> ob_fval; +X if (!is_floatobject(op)) { +X err_badarg(); +X return -1; +X } +X else +X return ((floatobject *)op) -> ob_fval; X} X X/* Methods */ X Xstatic void Xfloat_buf_repr(buf, v) -X char *buf; -X floatobject *v; -X{ -X register char *cp; -X /* Subroutine for float_repr and float_print. -X We want float numbers to be recognizable as such, -X i.e., they should contain a decimal point or an exponent. -X However, %g may print the number as an integer; -X in such cases, we append ".0" to the string. */ -X sprintf(buf, "%.12g", v->ob_fval); -X cp = buf; -X if (*cp == '-') -X cp++; -X for (; *cp != '\0'; cp++) { -X /* Any non-digit means it's not an integer; -X this takes care of NAN and INF as well. */ -X if (!isdigit(*cp)) -X break; -X } -X if (*cp == '\0') { -X *cp++ = '.'; -X *cp++ = '0'; -X *cp++ = '\0'; -X } +X char *buf; +X floatobject *v; +X{ +X register char *cp; +X /* Subroutine for float_repr and float_print. +X We want float numbers to be recognizable as such, +X i.e., they should contain a decimal point or an exponent. +X However, %g may print the number as an integer; +X in such cases, we append ".0" to the string. */ +X sprintf(buf, "%.12g", v->ob_fval); +X cp = buf; +X if (*cp == '-') +X cp++; +X for (; *cp != '\0'; cp++) { +X /* Any non-digit means it's not an integer; +X this takes care of NAN and INF as well. */ +X if (!isdigit(*cp)) +X break; +X } +X if (*cp == '\0') { +X *cp++ = '.'; +X *cp++ = '0'; +X *cp++ = '\0'; +X } X} X Xstatic void Xfloat_print(v, fp, flags) -X floatobject *v; -X FILE *fp; -X int flags; +X floatobject *v; +X FILE *fp; +X int flags; X{ -X char buf[100]; -X float_buf_repr(buf, v); -X fputs(buf, fp); +X char buf[100]; +X float_buf_repr(buf, v); +X fputs(buf, fp); X} X Xstatic object * Xfloat_repr(v) -X floatobject *v; +X floatobject *v; X{ -X char buf[100]; -X float_buf_repr(buf, v); -X return newstringobject(buf); +X char buf[100]; +X float_buf_repr(buf, v); +X return newstringobject(buf); X} X Xstatic int Xfloat_compare(v, w) -X floatobject *v, *w; +X floatobject *v, *w; X{ -X double i = v->ob_fval; -X double j = w->ob_fval; -X return (i < j) ? -1 : (i > j) ? 1 : 0; +X double i = v->ob_fval; +X double j = w->ob_fval; +X return (i < j) ? -1 : (i > j) ? 1 : 0; X} X Xstatic object * Xfloat_add(v, w) -X floatobject *v; -X object *w; +X floatobject *v; +X object *w; X{ -X if (!is_floatobject(w)) { -X err_badarg(); -X return NULL; -X } -X return newfloatobject(v->ob_fval + ((floatobject *)w) -> ob_fval); +X if (!is_floatobject(w)) { +X err_badarg(); +X return NULL; +X } +X return newfloatobject(v->ob_fval + ((floatobject *)w) -> ob_fval); X} X Xstatic object * Xfloat_sub(v, w) -X floatobject *v; -X object *w; +X floatobject *v; +X object *w; X{ -X if (!is_floatobject(w)) { -X err_badarg(); -X return NULL; -X } -X return newfloatobject(v->ob_fval - ((floatobject *)w) -> ob_fval); +X if (!is_floatobject(w)) { +X err_badarg(); +X return NULL; +X } +X return newfloatobject(v->ob_fval - ((floatobject *)w) -> ob_fval); X} X Xstatic object * Xfloat_mul(v, w) -X floatobject *v; -X object *w; +X floatobject *v; +X object *w; X{ -X if (!is_floatobject(w)) { -X err_badarg(); -X return NULL; -X } -X return newfloatobject(v->ob_fval * ((floatobject *)w) -> ob_fval); +X if (!is_floatobject(w)) { +X err_badarg(); +X return NULL; +X } +X return newfloatobject(v->ob_fval * ((floatobject *)w) -> ob_fval); X} X Xstatic object * Xfloat_div(v, w) -X floatobject *v; -X object *w; +X floatobject *v; +X object *w; X{ -X if (!is_floatobject(w)) { -X err_badarg(); -X return NULL; -X } -X if (((floatobject *)w) -> ob_fval == 0) { -X err_setstr(ZeroDivisionError, "float division by zero"); -X return NULL; -X } -X return newfloatobject(v->ob_fval / ((floatobject *)w) -> ob_fval); +X if (!is_floatobject(w)) { +X err_badarg(); +X return NULL; +X } +X if (((floatobject *)w) -> ob_fval == 0) { +X err_setstr(ZeroDivisionError, "float division by zero"); +X return NULL; +X } +X return newfloatobject(v->ob_fval / ((floatobject *)w) -> ob_fval); X} X Xstatic object * Xfloat_rem(v, w) -X floatobject *v; -X object *w; -X{ -X double wx; -X if (!is_floatobject(w)) { -X err_badarg(); -X return NULL; -X } -X wx = ((floatobject *)w) -> ob_fval; -X if (wx == 0.0) { -X err_setstr(ZeroDivisionError, "float division by zero"); -X return NULL; -X } -X return newfloatobject(fmod(v->ob_fval, wx)); +X floatobject *v; +X object *w; +X{ +X double wx; +X if (!is_floatobject(w)) { +X err_badarg(); +X return NULL; +X } +X wx = ((floatobject *)w) -> ob_fval; +X if (wx == 0.0) { +X err_setstr(ZeroDivisionError, "float division by zero"); +X return NULL; +X } +X return newfloatobject(fmod(v->ob_fval, wx)); X} X Xstatic object * Xfloat_pow(v, w) -X floatobject *v; -X object *w; -X{ -X double iv, iw, ix; -X if (!is_floatobject(w)) { -X err_badarg(); -X return NULL; -X } -X iv = v->ob_fval; -X iw = ((floatobject *)w)->ob_fval; -X if (iw == 0.0) -X return newfloatobject(1.0); /* x**0 is always 1, even 0**0 */ -X errno = 0; -X ix = pow(iv, iw); -X if (errno != 0) { -X /* XXX could it be another type of error? */ -X err_errno(OverflowError); -X return NULL; -X } -X return newfloatobject(ix); +X floatobject *v; +X object *w; +X{ +X double iv, iw, ix; +X if (!is_floatobject(w)) { +X err_badarg(); +X return NULL; +X } +X iv = v->ob_fval; +X iw = ((floatobject *)w)->ob_fval; +X if (iw == 0.0) +X return newfloatobject(1.0); /* x**0 is always 1, even 0**0 */ +X errno = 0; +X ix = pow(iv, iw); +X if (errno != 0) { +X /* XXX could it be another type of error? */ +X err_errno(OverflowError); +X return NULL; +X } +X return newfloatobject(ix); X} X Xstatic object * Xfloat_neg(v) -X floatobject *v; +X floatobject *v; X{ -X return newfloatobject(-v->ob_fval); +X return newfloatobject(-v->ob_fval); X} X Xstatic object * Xfloat_pos(v) -X floatobject *v; +X floatobject *v; X{ -X return newfloatobject(v->ob_fval); +X return newfloatobject(v->ob_fval); X} X Xstatic number_methods float_as_number = { -X float_add, /*tp_add*/ -X float_sub, /*tp_subtract*/ -X float_mul, /*tp_multiply*/ -X float_div, /*tp_divide*/ -X float_rem, /*tp_remainder*/ -X float_pow, /*tp_power*/ -X float_neg, /*tp_negate*/ -X float_pos, /*tp_plus*/ +X float_add, /*tp_add*/ +X float_sub, /*tp_subtract*/ +X float_mul, /*tp_multiply*/ +X float_div, /*tp_divide*/ +X float_rem, /*tp_remainder*/ +X float_pow, /*tp_power*/ +X float_neg, /*tp_negate*/ +X float_pos, /*tp_plus*/ X}; X Xtypeobject Floattype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "float", -X sizeof(floatobject), -X 0, -X free, /*tp_dealloc*/ -X float_print, /*tp_print*/ -X 0, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X float_compare, /*tp_compare*/ -X float_repr, /*tp_repr*/ -X &float_as_number, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "float", +X sizeof(floatobject), +X 0, +X free, /*tp_dealloc*/ +X float_print, /*tp_print*/ +X 0, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X float_compare, /*tp_compare*/ +X float_repr, /*tp_repr*/ +X &float_as_number, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X X/* -XXXX This is not enough. Need: +XXXX This is not enough. Need: X- automatic casts for mixed arithmetic (3.1 * 4) X- mixed comparisons (!) X- look at other uses of ints that could be extended to floats @@ -1375,12 +1375,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1409,118 +1409,118 @@ Xextern int debugging; X Xgrammar * Xnewgrammar(start) -X int start; +X int start; X{ -X grammar *g; -X -X g = NEW(grammar, 1); -X if (g == NULL) -X fatal("no mem for new grammar"); -X g->g_ndfas = 0; -X g->g_dfa = NULL; -X g->g_start = start; -X g->g_ll.ll_nlabels = 0; -X g->g_ll.ll_label = NULL; -X return g; +X grammar *g; +X +X g = NEW(grammar, 1); +X if (g == NULL) +X fatal("no mem for new grammar"); +X g->g_ndfas = 0; +X g->g_dfa = NULL; +X g->g_start = start; +X g->g_ll.ll_nlabels = 0; +X g->g_ll.ll_label = NULL; +X return g; X} X Xdfa * Xadddfa(g, type, name) -X grammar *g; -X int type; -X char *name; -X{ -X dfa *d; -X -X RESIZE(g->g_dfa, dfa, g->g_ndfas + 1); -X if (g->g_dfa == NULL) -X fatal("no mem to resize dfa in adddfa"); -X d = &g->g_dfa[g->g_ndfas++]; -X d->d_type = type; -X d->d_name = name; -X d->d_nstates = 0; -X d->d_state = NULL; -X d->d_initial = -1; -X d->d_first = NULL; -X return d; /* Only use while fresh! */ +X grammar *g; +X int type; +X char *name; +X{ +X dfa *d; +X +X RESIZE(g->g_dfa, dfa, g->g_ndfas + 1); +X if (g->g_dfa == NULL) +X fatal("no mem to resize dfa in adddfa"); +X d = &g->g_dfa[g->g_ndfas++]; +X d->d_type = type; +X d->d_name = name; +X d->d_nstates = 0; +X d->d_state = NULL; +X d->d_initial = -1; +X d->d_first = NULL; +X return d; /* Only use while fresh! */ X} X Xint Xaddstate(d) -X dfa *d; +X dfa *d; X{ -X state *s; -X -X RESIZE(d->d_state, state, d->d_nstates + 1); -X if (d->d_state == NULL) -X fatal("no mem to resize state in addstate"); -X s = &d->d_state[d->d_nstates++]; -X s->s_narcs = 0; -X s->s_arc = NULL; -X return s - d->d_state; +X state *s; +X +X RESIZE(d->d_state, state, d->d_nstates + 1); +X if (d->d_state == NULL) +X fatal("no mem to resize state in addstate"); +X s = &d->d_state[d->d_nstates++]; +X s->s_narcs = 0; +X s->s_arc = NULL; +X return s - d->d_state; X} X Xvoid Xaddarc(d, from, to, lbl) -X dfa *d; -X int lbl; -X{ -X state *s; -X arc *a; -X -X assert(0 <= from && from < d->d_nstates); -X assert(0 <= to && to < d->d_nstates); -X -X s = &d->d_state[from]; -X RESIZE(s->s_arc, arc, s->s_narcs + 1); -X if (s->s_arc == NULL) -X fatal("no mem to resize arc list in addarc"); -X a = &s->s_arc[s->s_narcs++]; -X a->a_lbl = lbl; -X a->a_arrow = to; +X dfa *d; +X int lbl; +X{ +X state *s; +X arc *a; +X +X assert(0 <= from && from < d->d_nstates); +X assert(0 <= to && to < d->d_nstates); +X +X s = &d->d_state[from]; +X RESIZE(s->s_arc, arc, s->s_narcs + 1); +X if (s->s_arc == NULL) +X fatal("no mem to resize arc list in addarc"); +X a = &s->s_arc[s->s_narcs++]; +X a->a_lbl = lbl; +X a->a_arrow = to; X} X Xint Xaddlabel(ll, type, str) -X labellist *ll; -X int type; -X char *str; -X{ -X int i; -X label *lb; -X -X for (i = 0; i < ll->ll_nlabels; i++) { -X if (ll->ll_label[i].lb_type == type && -X strcmp(ll->ll_label[i].lb_str, str) == 0) -X return i; -X } -X RESIZE(ll->ll_label, label, ll->ll_nlabels + 1); -X if (ll->ll_label == NULL) -X fatal("no mem to resize labellist in addlabel"); -X lb = &ll->ll_label[ll->ll_nlabels++]; -X lb->lb_type = type; -X lb->lb_str = str; /* XXX strdup(str) ??? */ -X return lb - ll->ll_label; +X labellist *ll; +X int type; +X char *str; +X{ +X int i; +X label *lb; +X +X for (i = 0; i < ll->ll_nlabels; i++) { +X if (ll->ll_label[i].lb_type == type && +X strcmp(ll->ll_label[i].lb_str, str) == 0) +X return i; +X } +X RESIZE(ll->ll_label, label, ll->ll_nlabels + 1); +X if (ll->ll_label == NULL) +X fatal("no mem to resize labellist in addlabel"); +X lb = &ll->ll_label[ll->ll_nlabels++]; +X lb->lb_type = type; +X lb->lb_str = str; /* XXX strdup(str) ??? */ +X return lb - ll->ll_label; X} X X/* Same, but rather dies than adds */ X Xint Xfindlabel(ll, type, str) -X labellist *ll; -X int type; -X char *str; -X{ -X int i; -X label *lb; -X -X for (i = 0; i < ll->ll_nlabels; i++) { -X if (ll->ll_label[i].lb_type == type /*&& -X strcmp(ll->ll_label[i].lb_str, str) == 0*/) -X return i; -X } -X fprintf(stderr, "Label %d/'%s' not found\n", type, str); -X abort(); +X labellist *ll; +X int type; +X char *str; +X{ +X int i; +X label *lb; +X +X for (i = 0; i < ll->ll_nlabels; i++) { +X if (ll->ll_label[i].lb_type == type /*&& +X strcmp(ll->ll_label[i].lb_str, str) == 0*/) +X return i; +X } +X fprintf(stderr, "Label %d/'%s' not found\n", type, str); +X abort(); X} X X/* Forward */ @@ -1528,81 +1528,81 @@ Xstatic void translabel PROTO((grammar *, label *)); X Xvoid Xtranslatelabels(g) -X grammar *g; +X grammar *g; X{ -X int i; -X -X printf("Translating labels ...\n"); -X /* Don't translate EMPTY */ -X for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) -X translabel(g, &g->g_ll.ll_label[i]); +X int i; +X +X printf("Translating labels ...\n"); +X /* Don't translate EMPTY */ +X for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) +X translabel(g, &g->g_ll.ll_label[i]); X} X Xstatic void Xtranslabel(g, lb) -X grammar *g; -X label *lb; -X{ -X int i; -X -X if (debugging) -X printf("Translating label %s ...\n", labelrepr(lb)); -X -X if (lb->lb_type == NAME) { -X for (i = 0; i < g->g_ndfas; i++) { -X if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { -X if (debugging) -X printf("Label %s is non-terminal %d.\n", -X lb->lb_str, -X g->g_dfa[i].d_type); -X lb->lb_type = g->g_dfa[i].d_type; -X lb->lb_str = NULL; -X return; -X } -X } -X for (i = 0; i < (int)N_TOKENS; i++) { -X if (strcmp(lb->lb_str, tok_name[i]) == 0) { -X if (debugging) -X printf("Label %s is terminal %d.\n", -X lb->lb_str, i); -X lb->lb_type = i; -X lb->lb_str = NULL; -X return; -X } -X } -X printf("Can't translate NAME label '%s'\n", lb->lb_str); -X return; -X } -X -X if (lb->lb_type == STRING) { -X if (isalpha(lb->lb_str[1])) { -X char *p, *strchr(); -X if (debugging) -X printf("Label %s is a keyword\n", lb->lb_str); -X lb->lb_type = NAME; -X lb->lb_str++; -X p = strchr(lb->lb_str, '\''); -X if (p) -X *p = '\0'; -X } -X else { -X if (lb->lb_str[2] == lb->lb_str[0]) { -X int type = (int) tok_1char(lb->lb_str[1]); -X if (type != OP) { -X lb->lb_type = type; -X lb->lb_str = NULL; -X } -X else -X printf("Unknown OP label %s\n", -X lb->lb_str); -X } -X else -X printf("Can't translate STRING label %s\n", -X lb->lb_str); -X } -X } -X else -X printf("Can't translate label '%s'\n", labelrepr(lb)); +X grammar *g; +X label *lb; +X{ +X int i; +X +X if (debugging) +X printf("Translating label %s ...\n", labelrepr(lb)); +X +X if (lb->lb_type == NAME) { +X for (i = 0; i < g->g_ndfas; i++) { +X if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { +X if (debugging) +X printf("Label %s is non-terminal %d.\n", +X lb->lb_str, +X g->g_dfa[i].d_type); +X lb->lb_type = g->g_dfa[i].d_type; +X lb->lb_str = NULL; +X return; +X } +X } +X for (i = 0; i < (int)N_TOKENS; i++) { +X if (strcmp(lb->lb_str, tok_name[i]) == 0) { +X if (debugging) +X printf("Label %s is terminal %d.\n", +X lb->lb_str, i); +X lb->lb_type = i; +X lb->lb_str = NULL; +X return; +X } +X } +X printf("Can't translate NAME label '%s'\n", lb->lb_str); +X return; +X } +X +X if (lb->lb_type == STRING) { +X if (isalpha(lb->lb_str[1])) { +X char *p, *strchr(); +X if (debugging) +X printf("Label %s is a keyword\n", lb->lb_str); +X lb->lb_type = NAME; +X lb->lb_str++; +X p = strchr(lb->lb_str, '\''); +X if (p) +X *p = '\0'; +X } +X else { +X if (lb->lb_str[2] == lb->lb_str[0]) { +X int type = (int) tok_1char(lb->lb_str[1]); +X if (type != OP) { +X lb->lb_type = type; +X lb->lb_str = NULL; +X } +X else +X printf("Unknown OP label %s\n", +X lb->lb_str); +X } +X else +X printf("Can't translate STRING label %s\n", +X lb->lb_str); +X } +X } +X else +X printf("Can't translate label '%s'\n", labelrepr(lb)); X} EOF fi @@ -1615,12 +1615,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1664,211 +1664,211 @@ X Xvoid Xinitimport() X{ -X if ((modules = newdictobject()) == NULL) -X fatal("no mem for dictionary of modules"); +X if ((modules = newdictobject()) == NULL) +X fatal("no mem for dictionary of modules"); X} X Xobject * Xget_modules() X{ -X return modules; +X return modules; X} X Xobject * Xadd_module(name) -X char *name; -X{ -X object *m; -X if ((m = dictlookup(modules, name)) != NULL && is_moduleobject(m)) -X return m; -X m = newmoduleobject(name); -X if (m == NULL) -X return NULL; -X if (dictinsert(modules, name, m) != 0) { -X DECREF(m); -X return NULL; -X } -X DECREF(m); /* Yes, it still exists, in modules! */ -X return m; +X char *name; +X{ +X object *m; +X if ((m = dictlookup(modules, name)) != NULL && is_moduleobject(m)) +X return m; +X m = newmoduleobject(name); +X if (m == NULL) +X return NULL; +X if (dictinsert(modules, name, m) != 0) { +X DECREF(m); +X return NULL; +X } +X DECREF(m); /* Yes, it still exists, in modules! */ +X return m; X} X Xstatic FILE * Xopen_module(name, suffix, namebuf) -X char *name; -X char *suffix; -X char *namebuf; /* XXX No buffer overflow checks! */ -X{ -X object *path; -X FILE *fp; -X -X path = sysget("path"); -X if (path == NULL || !is_listobject(path)) { -X strcpy(namebuf, name); -X strcat(namebuf, suffix); -X fp = fopen(namebuf, "r"); -X } -X else { -X int npath = getlistsize(path); -X int i; -X fp = NULL; -X for (i = 0; i < npath; i++) { -X object *v = getlistitem(path, i); -X int len; -X if (!is_stringobject(v)) -X continue; -X strcpy(namebuf, getstringvalue(v)); -X len = getstringsize(v); -X if (len > 0 && namebuf[len-1] != SEP) -X namebuf[len++] = SEP; -X strcpy(namebuf+len, name); -X strcat(namebuf, suffix); -X fp = fopen(namebuf, "r"); -X if (fp != NULL) -X break; -X } -X } -X return fp; +X char *name; +X char *suffix; +X char *namebuf; /* XXX No buffer overflow checks! */ +X{ +X object *path; +X FILE *fp; +X +X path = sysget("path"); +X if (path == NULL || !is_listobject(path)) { +X strcpy(namebuf, name); +X strcat(namebuf, suffix); +X fp = fopen(namebuf, "r"); +X } +X else { +X int npath = getlistsize(path); +X int i; +X fp = NULL; +X for (i = 0; i < npath; i++) { +X object *v = getlistitem(path, i); +X int len; +X if (!is_stringobject(v)) +X continue; +X strcpy(namebuf, getstringvalue(v)); +X len = getstringsize(v); +X if (len > 0 && namebuf[len-1] != SEP) +X namebuf[len++] = SEP; +X strcpy(namebuf+len, name); +X strcat(namebuf, suffix); +X fp = fopen(namebuf, "r"); +X if (fp != NULL) +X break; +X } +X } +X return fp; X} X Xstatic object * Xget_module(m, name, m_ret) -X /*module*/object *m; -X char *name; -X object **m_ret; -X{ -X object *d; -X FILE *fp; -X node *n; -X int err; -X char namebuf[256]; -X -X fp = open_module(name, ".py", namebuf); -X if (fp == NULL) { -X if (m == NULL) -X err_setstr(NameError, name); -X else -X err_setstr(RuntimeError, "no module source file"); -X return NULL; -X } -X err = parse_file(fp, namebuf, file_input, &n); -X fclose(fp); -X if (err != E_DONE) { -X err_input(err); -X return NULL; -X } -X if (m == NULL) { -X m = add_module(name); -X if (m == NULL) { -X freetree(n); -X return NULL; -X } -X *m_ret = m; -X } -X d = getmoduledict(m); -X return run_node(n, namebuf, d, d); +X /*module*/object *m; +X char *name; +X object **m_ret; +X{ +X object *d; +X FILE *fp; +X node *n; +X int err; +X char namebuf[256]; +X +X fp = open_module(name, ".py", namebuf); +X if (fp == NULL) { +X if (m == NULL) +X err_setstr(NameError, name); +X else +X err_setstr(RuntimeError, "no module source file"); +X return NULL; +X } +X err = parse_file(fp, namebuf, file_input, &n); +X fclose(fp); +X if (err != E_DONE) { +X err_input(err); +X return NULL; +X } +X if (m == NULL) { +X m = add_module(name); +X if (m == NULL) { +X freetree(n); +X return NULL; +X } +X *m_ret = m; +X } +X d = getmoduledict(m); +X return run_node(n, namebuf, d, d); X} X Xstatic object * Xload_module(name) -X char *name; +X char *name; X{ -X object *m, *v; -X v = get_module((object *)NULL, name, &m); -X if (v == NULL) -X return NULL; -X DECREF(v); -X return m; +X object *m, *v; +X v = get_module((object *)NULL, name, &m); +X if (v == NULL) +X return NULL; +X DECREF(v); +X return m; X} X Xobject * Ximport_module(name) -X char *name; +X char *name; X{ -X object *m; -X if ((m = dictlookup(modules, name)) == NULL) { -X if (init_builtin(name)) { -X if ((m = dictlookup(modules, name)) == NULL) -X err_setstr(SystemError, "builtin module missing"); -X } -X else { -X m = load_module(name); -X } -X } -X return m; +X object *m; +X if ((m = dictlookup(modules, name)) == NULL) { +X if (init_builtin(name)) { +X if ((m = dictlookup(modules, name)) == NULL) +X err_setstr(SystemError, "builtin module missing"); +X } +X else { +X m = load_module(name); +X } +X } +X return m; X} X Xobject * Xreload_module(m) -X object *m; +X object *m; X{ -X if (m == NULL || !is_moduleobject(m)) { -X err_setstr(TypeError, "reload() argument must be module"); -X return NULL; -X } -X /* XXX Ought to check for builtin modules -- can't reload these... */ -X return get_module(m, getmodulename(m), (object **)NULL); +X if (m == NULL || !is_moduleobject(m)) { +X err_setstr(TypeError, "reload() argument must be module"); +X return NULL; +X } +X /* XXX Ought to check for builtin modules -- can't reload these... */ +X return get_module(m, getmodulename(m), (object **)NULL); X} X Xstatic void Xcleardict(d) -X object *d; +X object *d; X{ -X int i; -X for (i = getdictsize(d); --i >= 0; ) { -X char *k; -X k = getdictkey(d, i); -X if (k != NULL) -X (void) dictremove(d, k); -X } +X int i; +X for (i = getdictsize(d); --i >= 0; ) { +X char *k; +X k = getdictkey(d, i); +X if (k != NULL) +X (void) dictremove(d, k); +X } X} X Xvoid Xdoneimport() X{ -X if (modules != NULL) { -X int i; -X /* Explicitly erase all modules; this is the safest way -X to get rid of at least *some* circular dependencies */ -X for (i = getdictsize(modules); --i >= 0; ) { -X char *k; -X k = getdictkey(modules, i); -X if (k != NULL) { -X object *m; -X m = dictlookup(modules, k); -X if (m != NULL && is_moduleobject(m)) { -X object *d; -X d = getmoduledict(m); -X if (d != NULL && is_dictobject(d)) { -X cleardict(d); -X } -X } -X } -X } -X cleardict(modules); -X } -X DECREF(modules); +X if (modules != NULL) { +X int i; +X /* Explicitly erase all modules; this is the safest way +X to get rid of at least *some* circular dependencies */ +X for (i = getdictsize(modules); --i >= 0; ) { +X char *k; +X k = getdictkey(modules, i); +X if (k != NULL) { +X object *m; +X m = dictlookup(modules, k); +X if (m != NULL && is_moduleobject(m)) { +X object *d; +X d = getmoduledict(m); +X if (d != NULL && is_dictobject(d)) { +X cleardict(d); +X } +X } +X } +X } +X cleardict(modules); +X } +X DECREF(modules); X} X X X/* Initialize built-in modules when first imported */ X Xextern struct { -X char *name; -X void (*initfunc)(); +X char *name; +X void (*initfunc)(); X} inittab[]; X Xstatic int Xinit_builtin(name) -X char *name; +X char *name; X{ -X int i; -X for (i = 0; inittab[i].name != NULL; i++) { -X if (strcmp(name, inittab[i].name) == 0) { -X (*inittab[i].initfunc)(); -X return 1; -X } -X } -X return 0; +X int i; +X for (i = 0; inittab[i].name != NULL; i++) { +X if (strcmp(name, inittab[i].name) == 0) { +X (*inittab[i].initfunc)(); +X return 1; +X } +X } +X return 0; X} EOF fi @@ -1881,12 +1881,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1918,210 +1918,210 @@ X X Xstatic object * Xmac_chdir(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *path; -X if (!getstrarg(args, &path)) -X return NULL; -X if (chdir(getstringvalue(path)) != 0) -X return err_errno(MacError); -X INCREF(None); -X return None; +X object *path; +X if (!getstrarg(args, &path)) +X return NULL; +X if (chdir(getstringvalue(path)) != 0) +X return err_errno(MacError); +X INCREF(None); +X return None; X} X X Xstatic object * Xmac_getcwd(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X extern char *getwd(); -X char buf[1025]; -X if (!getnoarg(args)) -X return NULL; -X strcpy(buf, "mac.getcwd() failed"); /* In case getwd() doesn't set a msg */ -X if (getwd(buf) == NULL) { -X err_setstr(MacError, buf); -X return NULL; -X } -X return newstringobject(buf); +X extern char *getwd(); +X char buf[1025]; +X if (!getnoarg(args)) +X return NULL; +X strcpy(buf, "mac.getcwd() failed"); /* In case getwd() doesn't set a msg */ +X if (getwd(buf) == NULL) { +X err_setstr(MacError, buf); +X return NULL; +X } +X return newstringobject(buf); X} X X Xstatic object * Xmac_listdir(self, args) -X object *self; -X object *args; -X{ -X object *name, *d, *v; -X DIR *dirp; -X struct direct *ep; -X if (!getstrarg(args, &name)) -X return NULL; -X if ((dirp = opendir(getstringvalue(name))) == NULL) -X return err_errno(MacError); -X if ((d = newlistobject(0)) == NULL) { -X closedir(dirp); -X return NULL; -X } -X while ((ep = readdir(dirp)) != NULL) { -X v = newstringobject(ep->d_name); -X if (v == NULL) { -X DECREF(d); -X d = NULL; -X break; -X } -X if (addlistitem(d, v) != 0) { -X DECREF(v); -X DECREF(d); -X d = NULL; -X break; -X } -X DECREF(v); -X } -X closedir(dirp); -X return d; +X object *self; +X object *args; +X{ +X object *name, *d, *v; +X DIR *dirp; +X struct direct *ep; +X if (!getstrarg(args, &name)) +X return NULL; +X if ((dirp = opendir(getstringvalue(name))) == NULL) +X return err_errno(MacError); +X if ((d = newlistobject(0)) == NULL) { +X closedir(dirp); +X return NULL; +X } +X while ((ep = readdir(dirp)) != NULL) { +X v = newstringobject(ep->d_name); +X if (v == NULL) { +X DECREF(d); +X d = NULL; +X break; +X } +X if (addlistitem(d, v) != 0) { +X DECREF(v); +X DECREF(d); +X d = NULL; +X break; +X } +X DECREF(v); +X } +X closedir(dirp); +X return d; X} X X Xstatic object * Xmac_mkdir(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *path; -X int mode; -X if (!getstrintarg(args, &path, &mode)) -X return NULL; -X if (mkdir(getstringvalue(path), mode) != 0) -X return err_errno(MacError); -X INCREF(None); -X return None; +X object *path; +X int mode; +X if (!getstrintarg(args, &path, &mode)) +X return NULL; +X if (mkdir(getstringvalue(path), mode) != 0) +X return err_errno(MacError); +X INCREF(None); +X return None; X} X X Xstatic object * Xmac_rename(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *src, *dst; -X if (!getstrstrarg(args, &src, &dst)) -X return NULL; -X if (rename(getstringvalue(src), getstringvalue(dst)) != 0) -X return err_errno(MacError); -X INCREF(None); -X return None; +X object *src, *dst; +X if (!getstrstrarg(args, &src, &dst)) +X return NULL; +X if (rename(getstringvalue(src), getstringvalue(dst)) != 0) +X return err_errno(MacError); +X INCREF(None); +X return None; X} X X Xstatic object * Xmac_rmdir(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *path; -X if (!getstrarg(args, &path)) -X return NULL; -X if (rmdir(getstringvalue(path)) != 0) -X return err_errno(MacError); -X INCREF(None); -X return None; +X object *path; +X if (!getstrarg(args, &path)) +X return NULL; +X if (rmdir(getstringvalue(path)) != 0) +X return err_errno(MacError); +X INCREF(None); +X return None; X} X X Xstatic object * Xmac_stat(self, args) -X object *self; -X object *args; -X{ -X struct stat st; -X object *path; -X object *v; -X if (!getstrarg(args, &path)) -X return NULL; -X if (stat(getstringvalue(path), &st) != 0) -X return err_errno(MacError); -X v = newtupleobject(11); -X if (v == NULL) -X return NULL; +X object *self; +X object *args; +X{ +X struct stat st; +X object *path; +X object *v; +X if (!getstrarg(args, &path)) +X return NULL; +X if (stat(getstringvalue(path), &st) != 0) +X return err_errno(MacError); +X v = newtupleobject(11); +X if (v == NULL) +X return NULL; X#define SET(i, val) settupleitem(v, i, newintobject((long)(val))) X#define XXX(i, val) SET(i, 0) /* For values my Mac stat doesn't support */ -X SET(0, st.st_mode); -X XXX(1, st.st_ino); -X XXX(2, st.st_dev); -X XXX(3, st.st_nlink); -X XXX(4, st.st_uid); -X XXX(5, st.st_gid); -X SET(6, st.st_size); -X XXX(7, st.st_atime); -X SET(8, st.st_mtime); -X XXX(9, st.st_ctime); -X SET(10, st.st_rsize); /* Mac-specific: resource size */ +X SET(0, st.st_mode); +X XXX(1, st.st_ino); +X XXX(2, st.st_dev); +X XXX(3, st.st_nlink); +X XXX(4, st.st_uid); +X XXX(5, st.st_gid); +X SET(6, st.st_size); +X XXX(7, st.st_atime); +X SET(8, st.st_mtime); +X XXX(9, st.st_ctime); +X SET(10, st.st_rsize); /* Mac-specific: resource size */ X#undef SET -X if (err_occurred()) { -X DECREF(v); -X return NULL; -X } -X return v; +X if (err_occurred()) { +X DECREF(v); +X return NULL; +X } +X return v; X} X X Xstatic object * Xmac_sync(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X sync(); -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X sync(); +X INCREF(None); +X return None; X} X X Xstatic object * Xmac_unlink(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X object *path; -X if (!getstrarg(args, &path)) -X return NULL; -X if (unlink(getstringvalue(path)) != 0) -X return err_errno(MacError); -X INCREF(None); -X return None; +X object *path; +X if (!getstrarg(args, &path)) +X return NULL; +X if (unlink(getstringvalue(path)) != 0) +X return err_errno(MacError); +X INCREF(None); +X return None; X} X X Xstatic struct methodlist mac_methods[] = { -X {"chdir", mac_chdir}, -X {"getcwd", mac_getcwd}, -X {"listdir", mac_listdir}, -X {"mkdir", mac_mkdir}, -X {"rename", mac_rename}, -X {"rmdir", mac_rmdir}, -X {"stat", mac_stat}, -X {"sync", mac_sync}, -X {"unlink", mac_unlink}, -X {NULL, NULL} /* Sentinel */ +X {"chdir", mac_chdir}, +X {"getcwd", mac_getcwd}, +X {"listdir", mac_listdir}, +X {"mkdir", mac_mkdir}, +X {"rename", mac_rename}, +X {"rmdir", mac_rmdir}, +X {"stat", mac_stat}, +X {"sync", mac_sync}, +X {"unlink", mac_unlink}, +X {NULL, NULL} /* Sentinel */ X}; X X Xvoid Xinitmac() X{ -X object *m, *d; -X -X m = initmodule("mac", mac_methods); -X d = getmoduledict(m); -X -X /* Initialize mac.error exception */ -X MacError = newstringobject("mac.error"); -X if (MacError == NULL || dictinsert(d, "error", MacError) != 0) -X fatal("can't define mac.error"); +X object *m, *d; +X +X m = initmodule("mac", mac_methods); +X d = getmoduledict(m); +X +X /* Initialize mac.error exception */ +X MacError = newstringobject("mac.error"); +X if (MacError == NULL || dictinsert(d, "error", MacError) != 0) +X fatal("can't define mac.error"); X} EOF fi @@ -2134,12 +2134,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2163,36 +2163,36 @@ Xlong ref_total; X#endif X X/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros. -X These are used by the individual routines for object creation. -X Do not call them otherwise, they do not initialize the object! */ +X These are used by the individual routines for object creation. +X Do not call them otherwise, they do not initialize the object! */ X Xobject * Xnewobject(tp) -X typeobject *tp; +X typeobject *tp; X{ -X object *op = (object *) malloc(tp->tp_basicsize); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = tp; -X return op; +X object *op = (object *) malloc(tp->tp_basicsize); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = tp; +X return op; X} X X#if 0 /* unused */ X Xvarobject * Xnewvarobject(tp, size) -X typeobject *tp; -X unsigned int size; +X typeobject *tp; +X unsigned int size; X{ -X varobject *op = (varobject *) -X malloc(tp->tp_basicsize + size * tp->tp_itemsize); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = tp; -X op->ob_size = size; -X return op; +X varobject *op = (varobject *) +X malloc(tp->tp_basicsize + size * tp->tp_itemsize); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = tp; +X op->ob_size = size; +X return op; X} X X#endif @@ -2203,121 +2203,121 @@ Xstatic int prlevel; X Xvoid Xprintobject(op, fp, flags) -X object *op; -X FILE *fp; -X int flags; -X{ -X /* Hacks to make printing a long or recursive object interruptible */ -X /* XXX Interrupts should leave a more permanent error */ -X prlevel++; -X if (!StopPrint && intrcheck()) { -X fprintf(fp, "\n[print interrupted]\n"); -X StopPrint = 1; -X } -X if (!StopPrint) { -X if (op == NULL) { -X fprintf(fp, "<nil>"); -X } -X else { -X if (op->ob_refcnt <= 0) -X fprintf(fp, "(refcnt %d):", op->ob_refcnt); -X if (op->ob_type->tp_print == NULL) { -X fprintf(fp, "<%s object at %lx>", -X op->ob_type->tp_name, (long)op); -X } -X else { -X (*op->ob_type->tp_print)(op, fp, flags); -X } -X } -X } -X prlevel--; -X if (prlevel == 0) -X StopPrint = 0; +X object *op; +X FILE *fp; +X int flags; +X{ +X /* Hacks to make printing a long or recursive object interruptible */ +X /* XXX Interrupts should leave a more permanent error */ +X prlevel++; +X if (!StopPrint && intrcheck()) { +X fprintf(fp, "\n[print interrupted]\n"); +X StopPrint = 1; +X } +X if (!StopPrint) { +X if (op == NULL) { +X fprintf(fp, "<nil>"); +X } +X else { +X if (op->ob_refcnt <= 0) +X fprintf(fp, "(refcnt %d):", op->ob_refcnt); +X if (op->ob_type->tp_print == NULL) { +X fprintf(fp, "<%s object at %lx>", +X op->ob_type->tp_name, (long)op); +X } +X else { +X (*op->ob_type->tp_print)(op, fp, flags); +X } +X } +X } +X prlevel--; +X if (prlevel == 0) +X StopPrint = 0; X} X Xobject * Xreprobject(v) -X object *v; -X{ -X object *w = NULL; -X /* Hacks to make converting a long or recursive object interruptible */ -X prlevel++; -X if (!StopPrint && intrcheck()) { -X StopPrint = 1; -X err_set(KeyboardInterrupt); -X } -X if (!StopPrint) { -X if (v == NULL) { -X w = newstringobject("<NULL>"); -X } -X else if (v->ob_type->tp_repr == NULL) { -X char buf[100]; -X sprintf(buf, "<%.80s object at %lx>", -X v->ob_type->tp_name, (long)v); -X w = newstringobject(buf); -X } -X else { -X w = (*v->ob_type->tp_repr)(v); -X } -X if (StopPrint) { -X XDECREF(w); -X w = NULL; -X } -X } -X prlevel--; -X if (prlevel == 0) -X StopPrint = 0; -X return w; +X object *v; +X{ +X object *w = NULL; +X /* Hacks to make converting a long or recursive object interruptible */ +X prlevel++; +X if (!StopPrint && intrcheck()) { +X StopPrint = 1; +X err_set(KeyboardInterrupt); +X } +X if (!StopPrint) { +X if (v == NULL) { +X w = newstringobject("<NULL>"); +X } +X else if (v->ob_type->tp_repr == NULL) { +X char buf[100]; +X sprintf(buf, "<%.80s object at %lx>", +X v->ob_type->tp_name, (long)v); +X w = newstringobject(buf); +X } +X else { +X w = (*v->ob_type->tp_repr)(v); +X } +X if (StopPrint) { +X XDECREF(w); +X w = NULL; +X } +X } +X prlevel--; +X if (prlevel == 0) +X StopPrint = 0; +X return w; X} X Xint Xcmpobject(v, w) -X object *v, *w; -X{ -X typeobject *tp; -X if (v == w) -X return 0; -X if (v == NULL) -X return -1; -X if (w == NULL) -X return 1; -X if ((tp = v->ob_type) != w->ob_type) -X return strcmp(tp->tp_name, w->ob_type->tp_name); -X if (tp->tp_compare == NULL) -X return (v < w) ? -1 : 1; -X return ((*tp->tp_compare)(v, w)); +X object *v, *w; +X{ +X typeobject *tp; +X if (v == w) +X return 0; +X if (v == NULL) +X return -1; +X if (w == NULL) +X return 1; +X if ((tp = v->ob_type) != w->ob_type) +X return strcmp(tp->tp_name, w->ob_type->tp_name); +X if (tp->tp_compare == NULL) +X return (v < w) ? -1 : 1; +X return ((*tp->tp_compare)(v, w)); X} X Xobject * Xgetattr(v, name) -X object *v; -X char *name; +X object *v; +X char *name; X{ -X if (v->ob_type->tp_getattr == NULL) { -X err_setstr(TypeError, "attribute-less object"); -X return NULL; -X } -X else { -X return (*v->ob_type->tp_getattr)(v, name); -X } +X if (v->ob_type->tp_getattr == NULL) { +X err_setstr(TypeError, "attribute-less object"); +X return NULL; +X } +X else { +X return (*v->ob_type->tp_getattr)(v, name); +X } X} X Xint Xsetattr(v, name, w) -X object *v; -X char *name; -X object *w; +X object *v; +X char *name; +X object *w; X{ -X if (v->ob_type->tp_setattr == NULL) { -X if (v->ob_type->tp_getattr == NULL) -X err_setstr(TypeError, "attribute-less object"); -X else -X err_setstr(TypeError, "object has read-only attributes"); -X return -1; -X } -X else { -X return (*v->ob_type->tp_setattr)(v, name, w); -X } +X if (v->ob_type->tp_setattr == NULL) { +X if (v->ob_type->tp_getattr == NULL) +X err_setstr(TypeError, "attribute-less object"); +X else +X err_setstr(TypeError, "object has read-only attributes"); +X return -1; +X } +X else { +X return (*v->ob_type->tp_setattr)(v, name, w); +X } X} X X @@ -2329,39 +2329,39 @@ X*/ X Xstatic void Xnone_print(op, fp, flags) -X object *op; -X FILE *fp; -X int flags; +X object *op; +X FILE *fp; +X int flags; X{ -X fprintf(fp, "None"); +X fprintf(fp, "None"); X} X Xstatic object * Xnone_repr(op) -X object *op; +X object *op; X{ -X return newstringobject("None"); +X return newstringobject("None"); X} X Xstatic typeobject Notype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "None", -X 0, -X 0, -X 0, /*tp_dealloc*/ /*never called*/ -X none_print, /*tp_print*/ -X 0, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X none_repr, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "None", +X 0, +X 0, +X 0, /*tp_dealloc*/ /*never called*/ +X none_print, /*tp_print*/ +X 0, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X none_repr, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X Xobject NoObject = { -X OB_HEAD_INIT(&Notype) +X OB_HEAD_INIT(&Notype) X}; X X @@ -2370,53 +2370,53 @@ X Xstatic object refchain = {&refchain, &refchain}; X XNEWREF(op) -X object *op; +X object *op; X{ -X ref_total++; -X op->ob_refcnt = 1; -X op->_ob_next = refchain._ob_next; -X op->_ob_prev = &refchain; -X refchain._ob_next->_ob_prev = op; -X refchain._ob_next = op; +X ref_total++; +X op->ob_refcnt = 1; +X op->_ob_next = refchain._ob_next; +X op->_ob_prev = &refchain; +X refchain._ob_next->_ob_prev = op; +X refchain._ob_next = op; X} X XUNREF(op) -X register object *op; -X{ -X register object *p; -X if (op->ob_refcnt < 0) { -X fprintf(stderr, "UNREF negative refcnt\n"); -X abort(); -X } -X for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { -X if (p == op) -X break; -X } -X if (p == &refchain) { /* Not found */ -X fprintf(stderr, "UNREF unknown object\n"); -X abort(); -X } -X op->_ob_next->_ob_prev = op->_ob_prev; -X op->_ob_prev->_ob_next = op->_ob_next; +X register object *op; +X{ +X register object *p; +X if (op->ob_refcnt < 0) { +X fprintf(stderr, "UNREF negative refcnt\n"); +X abort(); +X } +X for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { +X if (p == op) +X break; +X } +X if (p == &refchain) { /* Not found */ +X fprintf(stderr, "UNREF unknown object\n"); +X abort(); +X } +X op->_ob_next->_ob_prev = op->_ob_prev; +X op->_ob_prev->_ob_next = op->_ob_next; X} X XDELREF(op) -X object *op; +X object *op; X{ -X UNREF(op); -X (*(op)->ob_type->tp_dealloc)(op); +X UNREF(op); +X (*(op)->ob_type->tp_dealloc)(op); X} X Xprintrefs(fp) -X FILE *fp; +X FILE *fp; X{ -X object *op; -X fprintf(fp, "Remaining objects:\n"); -X for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { -X fprintf(fp, "[%d] ", op->ob_refcnt); -X printobject(op, fp, 0); -X putc('\n', fp); -X } +X object *op; +X fprintf(fp, "Remaining objects:\n"); +X for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { +X fprintf(fp, "[%d] ", op->ob_refcnt); +X printobject(op, fp, 0); +X putc('\n', fp); +X } X} X X#endif @@ -2431,12 +2431,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2457,264 +2457,264 @@ X#include "allobjects.h" X Xobject * Xnewtupleobject(size) -X register int size; -X{ -X register int i; -X register tupleobject *op; -X if (size < 0) { -X err_badcall(); -X return NULL; -X } -X op = (tupleobject *) -X malloc(sizeof(tupleobject) + size * sizeof(object *)); -X if (op == NULL) -X return err_nomem(); -X NEWREF(op); -X op->ob_type = &Tupletype; -X op->ob_size = size; -X for (i = 0; i < size; i++) -X op->ob_item[i] = NULL; -X return (object *) op; +X register int size; +X{ +X register int i; +X register tupleobject *op; +X if (size < 0) { +X err_badcall(); +X return NULL; +X } +X op = (tupleobject *) +X malloc(sizeof(tupleobject) + size * sizeof(object *)); +X if (op == NULL) +X return err_nomem(); +X NEWREF(op); +X op->ob_type = &Tupletype; +X op->ob_size = size; +X for (i = 0; i < size; i++) +X op->ob_item[i] = NULL; +X return (object *) op; X} X Xint Xgettuplesize(op) -X register object *op; +X register object *op; X{ -X if (!is_tupleobject(op)) { -X err_badcall(); -X return -1; -X } -X else -X return ((tupleobject *)op)->ob_size; +X if (!is_tupleobject(op)) { +X err_badcall(); +X return -1; +X } +X else +X return ((tupleobject *)op)->ob_size; X} X Xobject * Xgettupleitem(op, i) -X register object *op; -X register int i; +X register object *op; +X register int i; X{ -X if (!is_tupleobject(op)) { -X err_badcall(); -X return NULL; -X } -X if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { -X err_setstr(IndexError, "tuple index out of range"); -X return NULL; -X } -X return ((tupleobject *)op) -> ob_item[i]; +X if (!is_tupleobject(op)) { +X err_badcall(); +X return NULL; +X } +X if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { +X err_setstr(IndexError, "tuple index out of range"); +X return NULL; +X } +X return ((tupleobject *)op) -> ob_item[i]; X} X Xint Xsettupleitem(op, i, newitem) -X register object *op; -X register int i; -X register object *newitem; -X{ -X register object *olditem; -X if (!is_tupleobject(op)) { -X if (newitem != NULL) -X DECREF(newitem); -X err_badcall(); -X return -1; -X } -X if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { -X if (newitem != NULL) -X DECREF(newitem); -X err_setstr(IndexError, "tuple assignment index out of range"); -X return -1; -X } -X olditem = ((tupleobject *)op) -> ob_item[i]; -X ((tupleobject *)op) -> ob_item[i] = newitem; -X if (olditem != NULL) -X DECREF(olditem); -X return 0; +X register object *op; +X register int i; +X register object *newitem; +X{ +X register object *olditem; +X if (!is_tupleobject(op)) { +X if (newitem != NULL) +X DECREF(newitem); +X err_badcall(); +X return -1; +X } +X if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { +X if (newitem != NULL) +X DECREF(newitem); +X err_setstr(IndexError, "tuple assignment index out of range"); +X return -1; +X } +X olditem = ((tupleobject *)op) -> ob_item[i]; +X ((tupleobject *)op) -> ob_item[i] = newitem; +X if (olditem != NULL) +X DECREF(olditem); +X return 0; X} X X/* Methods */ X Xstatic void Xtupledealloc(op) -X register tupleobject *op; +X register tupleobject *op; X{ -X register int i; -X for (i = 0; i < op->ob_size; i++) { -X if (op->ob_item[i] != NULL) -X DECREF(op->ob_item[i]); -X } -X free((ANY *)op); +X register int i; +X for (i = 0; i < op->ob_size; i++) { +X if (op->ob_item[i] != NULL) +X DECREF(op->ob_item[i]); +X } +X free((ANY *)op); X} X Xstatic void Xtupleprint(op, fp, flags) -X tupleobject *op; -X FILE *fp; -X int flags; -X{ -X int i; -X fprintf(fp, "("); -X for (i = 0; i < op->ob_size && !StopPrint; i++) { -X if (i > 0) { -X fprintf(fp, ", "); -X } -X printobject(op->ob_item[i], fp, flags); -X } -X if (op->ob_size == 1) -X fprintf(fp, ","); -X fprintf(fp, ")"); +X tupleobject *op; +X FILE *fp; +X int flags; +X{ +X int i; +X fprintf(fp, "("); +X for (i = 0; i < op->ob_size && !StopPrint; i++) { +X if (i > 0) { +X fprintf(fp, ", "); +X } +X printobject(op->ob_item[i], fp, flags); +X } +X if (op->ob_size == 1) +X fprintf(fp, ","); +X fprintf(fp, ")"); X} X Xobject * Xtuplerepr(v) -X tupleobject *v; -X{ -X object *s, *t, *comma; -X int i; -X s = newstringobject("("); -X comma = newstringobject(", "); -X for (i = 0; i < v->ob_size && s != NULL; i++) { -X if (i > 0) -X joinstring(&s, comma); -X t = reprobject(v->ob_item[i]); -X joinstring(&s, t); -X if (t != NULL) -X DECREF(t); -X } -X DECREF(comma); -X if (v->ob_size == 1) { -X t = newstringobject(","); -X joinstring(&s, t); -X DECREF(t); -X } -X t = newstringobject(")"); -X joinstring(&s, t); -X DECREF(t); -X return s; +X tupleobject *v; +X{ +X object *s, *t, *comma; +X int i; +X s = newstringobject("("); +X comma = newstringobject(", "); +X for (i = 0; i < v->ob_size && s != NULL; i++) { +X if (i > 0) +X joinstring(&s, comma); +X t = reprobject(v->ob_item[i]); +X joinstring(&s, t); +X if (t != NULL) +X DECREF(t); +X } +X DECREF(comma); +X if (v->ob_size == 1) { +X t = newstringobject(","); +X joinstring(&s, t); +X DECREF(t); +X } +X t = newstringobject(")"); +X joinstring(&s, t); +X DECREF(t); +X return s; X} X Xstatic int Xtuplecompare(v, w) -X register tupleobject *v, *w; +X register tupleobject *v, *w; X{ -X register int len = -X (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; -X register int i; -X for (i = 0; i < len; i++) { -X int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); -X if (cmp != 0) -X return cmp; -X } -X return v->ob_size - w->ob_size; +X register int len = +X (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; +X register int i; +X for (i = 0; i < len; i++) { +X int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); +X if (cmp != 0) +X return cmp; +X } +X return v->ob_size - w->ob_size; X} X Xstatic int Xtuplelength(a) -X tupleobject *a; +X tupleobject *a; X{ -X return a->ob_size; +X return a->ob_size; X} X Xstatic object * Xtupleitem(a, i) -X register tupleobject *a; -X register int i; +X register tupleobject *a; +X register int i; X{ -X if (i < 0 || i >= a->ob_size) { -X err_setstr(IndexError, "tuple index out of range"); -X return NULL; -X } -X INCREF(a->ob_item[i]); -X return a->ob_item[i]; +X if (i < 0 || i >= a->ob_size) { +X err_setstr(IndexError, "tuple index out of range"); +X return NULL; +X } +X INCREF(a->ob_item[i]); +X return a->ob_item[i]; X} X Xstatic object * Xtupleslice(a, ilow, ihigh) -X register tupleobject *a; -X register int ilow, ihigh; -X{ -X register tupleobject *np; -X register int i; -X if (ilow < 0) -X ilow = 0; -X if (ihigh > a->ob_size) -X ihigh = a->ob_size; -X if (ihigh < ilow) -X ihigh = ilow; -X if (ilow == 0 && ihigh == a->ob_size) { -X /* XXX can only do this if tuples are immutable! */ -X INCREF(a); -X return (object *)a; -X } -X np = (tupleobject *)newtupleobject(ihigh - ilow); -X if (np == NULL) -X return NULL; -X for (i = ilow; i < ihigh; i++) { -X object *v = a->ob_item[i]; -X INCREF(v); -X np->ob_item[i - ilow] = v; -X } -X return (object *)np; +X register tupleobject *a; +X register int ilow, ihigh; +X{ +X register tupleobject *np; +X register int i; +X if (ilow < 0) +X ilow = 0; +X if (ihigh > a->ob_size) +X ihigh = a->ob_size; +X if (ihigh < ilow) +X ihigh = ilow; +X if (ilow == 0 && ihigh == a->ob_size) { +X /* XXX can only do this if tuples are immutable! */ +X INCREF(a); +X return (object *)a; +X } +X np = (tupleobject *)newtupleobject(ihigh - ilow); +X if (np == NULL) +X return NULL; +X for (i = ilow; i < ihigh; i++) { +X object *v = a->ob_item[i]; +X INCREF(v); +X np->ob_item[i - ilow] = v; +X } +X return (object *)np; X} X Xstatic object * Xtupleconcat(a, bb) -X register tupleobject *a; -X register object *bb; -X{ -X register int size; -X register int i; -X tupleobject *np; -X if (!is_tupleobject(bb)) { -X err_badarg(); -X return NULL; -X } +X register tupleobject *a; +X register object *bb; +X{ +X register int size; +X register int i; +X tupleobject *np; +X if (!is_tupleobject(bb)) { +X err_badarg(); +X return NULL; +X } X#define b ((tupleobject *)bb) -X size = a->ob_size + b->ob_size; -X np = (tupleobject *) newtupleobject(size); -X if (np == NULL) { -X return err_nomem(); -X } -X for (i = 0; i < a->ob_size; i++) { -X object *v = a->ob_item[i]; -X INCREF(v); -X np->ob_item[i] = v; -X } -X for (i = 0; i < b->ob_size; i++) { -X object *v = b->ob_item[i]; -X INCREF(v); -X np->ob_item[i + a->ob_size] = v; -X } -X return (object *)np; +X size = a->ob_size + b->ob_size; +X np = (tupleobject *) newtupleobject(size); +X if (np == NULL) { +X return err_nomem(); +X } +X for (i = 0; i < a->ob_size; i++) { +X object *v = a->ob_item[i]; +X INCREF(v); +X np->ob_item[i] = v; +X } +X for (i = 0; i < b->ob_size; i++) { +X object *v = b->ob_item[i]; +X INCREF(v); +X np->ob_item[i + a->ob_size] = v; +X } +X return (object *)np; X#undef b X} X Xstatic sequence_methods tuple_as_sequence = { -X tuplelength, /*sq_length*/ -X tupleconcat, /*sq_concat*/ -X 0, /*sq_repeat*/ -X tupleitem, /*sq_item*/ -X tupleslice, /*sq_slice*/ -X 0, /*sq_ass_item*/ -X 0, /*sq_ass_slice*/ +X tuplelength, /*sq_length*/ +X tupleconcat, /*sq_concat*/ +X 0, /*sq_repeat*/ +X tupleitem, /*sq_item*/ +X tupleslice, /*sq_slice*/ +X 0, /*sq_ass_item*/ +X 0, /*sq_ass_slice*/ X}; X Xtypeobject Tupletype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "tuple", -X sizeof(tupleobject) - sizeof(object *), -X sizeof(object *), -X tupledealloc, /*tp_dealloc*/ -X tupleprint, /*tp_print*/ -X 0, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X tuplecompare, /*tp_compare*/ -X tuplerepr, /*tp_repr*/ -X 0, /*tp_as_number*/ -X &tuple_as_sequence, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "tuple", +X sizeof(tupleobject) - sizeof(object *), +X sizeof(object *), +X tupledealloc, /*tp_dealloc*/ +X tupleprint, /*tp_print*/ +X 0, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X tuplecompare, /*tp_compare*/ +X tuplerepr, /*tp_repr*/ +X 0, /*tp_as_number*/ +X &tuple_as_sequence, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; EOF fi echo 'Part 14 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-15-21.shar b/shar/python-0.9.1-15-21.shar index 3cc3c78..a715ac5 100644 --- a/shar/python-0.9.1-15-21.shar +++ b/shar/python-0.9.1-15-21.shar @@ -22,15 +22,15 @@ X# on the 4D/25G. X# X# This program show 3 kites flying around the screen. It uses X# -X# * bgnpolygon, endpolygon -X# * v3, n3 -X# * lmdef, lmbind +X# * bgnpolygon, endpolygon +X# * v3, n3 +X# * lmdef, lmbind X# X# Usage : -X# -X# ESC -> exit program -X# MOUSE3 -> freeze toggle -X# MOUSE2 -> one step (use this in freeze state) +X# +X# ESC -> exit program +X# MOUSE3 -> freeze toggle +X# MOUSE2 -> one step (use this in freeze state) X Xfrom GL import * Xfrom gl import * @@ -42,28 +42,28 @@ X# viewobj : sets the rotation, translation and scaling X# set appropiate material, call drawobject() X# Xdef viewobj (r, s, t, mat) : -X pushmatrix() -X rot (r * 10.0, 'X') -X rot (r * 10.0, 'Y') -X rot (r * 10.0, 'Z') -X scale (s[0], s[1], s[2]) -X translate (t[0], t[1], t[2]) -X lmbind(MATERIAL, mat) -X drawobject() -X popmatrix() +X pushmatrix() +X rot (r * 10.0, 'X') +X rot (r * 10.0, 'Y') +X rot (r * 10.0, 'Z') +X scale (s[0], s[1], s[2]) +X translate (t[0], t[1], t[2]) +X lmbind(MATERIAL, mat) +X drawobject() +X popmatrix() X X# X# makeobj : the contructor of the object X# Xdef mkobj () : -X v0 = (-5.0 ,0.0, 0.0) -X v1 = (0.0 ,5.0, 0.0) -X v2 = (5.0 ,0.0, 0.0) -X v3 = (0.0 ,2.0, 0.0) -X n0 = (sqrt(2.0)/2.0, sqrt(2.0)/2.0, 0.0) -X vn = ((v0, n0), (v1, n0), (v2, n0), (v3, n0)) -X # -X return vn +X v0 = (-5.0 ,0.0, 0.0) +X v1 = (0.0 ,5.0, 0.0) +X v2 = (5.0 ,0.0, 0.0) +X v3 = (0.0 ,2.0, 0.0) +X n0 = (sqrt(2.0)/2.0, sqrt(2.0)/2.0, 0.0) +X vn = ((v0, n0), (v1, n0), (v2, n0), (v3, n0)) +X # +X return vn X X# X# the object itself as an array of vertices and normals @@ -74,10 +74,10 @@ X# X# drawobject : draw a triangle. with bgnpolygon X# Xdef drawobject () : -X # -X bgnpolygon() -X vnarray (kite) -X endpolygon() +X # +X bgnpolygon() +X vnarray (kite) +X endpolygon() X X# X# identity matrix @@ -85,7 +85,7 @@ X# Xidmat=[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] X X# -X# the rgb-value of light-blue +X# the rgb-value of light-blue X# XLightBlue = (43,169,255) X @@ -112,96 +112,96 @@ X# initgl : opens the window, configures the pipeline to 2buf and zbuf, X# sets the viewing, defines and binds the materials X# Xdef initgl () : -X # -X # open window -X # -X foreground () -X keepaspect (1, 1) -X prefposition (100, 500, 100, 500) -X w = winopen ('PYTHON lights') -X keepaspect (1, 1) -X winconstraints() -X # -X # configure pipeline (zbuf, 2buf, GOURAUD and RGBmode) -X # -X zbuffer (1) -X doublebuffer () -X shademodel (GOURAUD) -X RGBmode () -X gconfig () -X # -X # define and bind materials (set perspective BEFORE loadmat !) -X # -X mmode(MVIEWING) -X perspective (900, 1.0, 1.0, 20.0) -X loadmatrix(idmat) -X lmdef(DEFMATERIAL, 1, m1) -X lmdef(DEFMATERIAL, 2, m2) -X lmdef(DEFMATERIAL, 3, m3) -X lmdef(DEFLIGHT, 1, light1) -X lmdef(DEFLIGHT, 2, light2) -X lmdef(DEFLMODEL, 1, model) -X lmbind(LIGHT0,1) -X lmbind(LIGHT1,2) -X lmbind(LMODEL,1) -X # -X # set viewing -X # -X lookat (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0) -X # -X # ask for the REDRAW and ESCKEY events -X # -X qdevice(DEVICE.MOUSE3) -X qdevice(DEVICE.MOUSE2) -X qdevice(DEVICE.REDRAW) -X qdevice(DEVICE.ESCKEY) +X # +X # open window +X # +X foreground () +X keepaspect (1, 1) +X prefposition (100, 500, 100, 500) +X w = winopen ('PYTHON lights') +X keepaspect (1, 1) +X winconstraints() +X # +X # configure pipeline (zbuf, 2buf, GOURAUD and RGBmode) +X # +X zbuffer (1) +X doublebuffer () +X shademodel (GOURAUD) +X RGBmode () +X gconfig () +X # +X # define and bind materials (set perspective BEFORE loadmat !) +X # +X mmode(MVIEWING) +X perspective (900, 1.0, 1.0, 20.0) +X loadmatrix(idmat) +X lmdef(DEFMATERIAL, 1, m1) +X lmdef(DEFMATERIAL, 2, m2) +X lmdef(DEFMATERIAL, 3, m3) +X lmdef(DEFLIGHT, 1, light1) +X lmdef(DEFLIGHT, 2, light2) +X lmdef(DEFLMODEL, 1, model) +X lmbind(LIGHT0,1) +X lmbind(LIGHT1,2) +X lmbind(LMODEL,1) +X # +X # set viewing +X # +X lookat (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0) +X # +X # ask for the REDRAW and ESCKEY events +X # +X qdevice(DEVICE.MOUSE3) +X qdevice(DEVICE.MOUSE2) +X qdevice(DEVICE.REDRAW) +X qdevice(DEVICE.ESCKEY) X X# -X# GoForIT : use 2buf to redraw the object 2n times. index i is used as +X# GoForIT : use 2buf to redraw the object 2n times. index i is used as X# the (smoothly changing) rotation angle X# Xdef GoForIt(i) : -X freeze = 1 -X while 1 : -X if freeze <> 0 : -X i = i + 1 -X # -X # clear z-buffer and clear background to light-blue -X # -X zclear() -X c3i (LightBlue) -X clear() -X # -X # draw the 3 traiangles scaled above each other. -X # -X viewobj(float(i),[1.0,1.0,1.0],[1.0,1.0,1.0],1) -X viewobj(float(i),[0.75,0.75,0.75],[0.0,2.0,2.0],2) -X viewobj(float(i),[0.5,0.5,0.5],[0.0,4.0,4.0],3) -X # -X swapbuffers() -X # -X if qtest() <> 0 : -X dev, val = qread() -X if dev = DEVICE.ESCKEY : -X break -X elif dev = DEVICE.REDRAW : -X reshapeviewport () -X elif dev = DEVICE.MOUSE3 and val <> 0 : -X freeze = 1 - freeze -X elif dev = DEVICE.MOUSE2 and val <> 0 : -X i = i + 1 +X freeze = 1 +X while 1 : +X if freeze <> 0 : +X i = i + 1 +X # +X # clear z-buffer and clear background to light-blue +X # +X zclear() +X c3i (LightBlue) +X clear() +X # +X # draw the 3 traiangles scaled above each other. +X # +X viewobj(float(i),[1.0,1.0,1.0],[1.0,1.0,1.0],1) +X viewobj(float(i),[0.75,0.75,0.75],[0.0,2.0,2.0],2) +X viewobj(float(i),[0.5,0.5,0.5],[0.0,4.0,4.0],3) +X # +X swapbuffers() +X # +X if qtest() <> 0 : +X dev, val = qread() +X if dev = DEVICE.ESCKEY : +X break +X elif dev = DEVICE.REDRAW : +X reshapeviewport () +X elif dev = DEVICE.MOUSE3 and val <> 0 : +X freeze = 1 - freeze +X elif dev = DEVICE.MOUSE2 and val <> 0 : +X i = i + 1 X X X# the main program X# Xdef main () : -X initgl () -X GoForIt (0) +X initgl () +X GoForIt (0) X X# X# exec main X# -Xmain () +Xmain () EOF chmod +x 'demo/sgi/gl/kites.py' fi @@ -323,156 +323,156 @@ X# It does not support any of the triggers or hooks defined by Buttons, X# but defines its own setval_trigger and setval_hook. X# Xclass DragSliderReactivity() = BaseReactivity(): -X # -X def mouse_down(self, detail): -X h, v = hv = detail[_HV] -X if self.enabled and self.mousetest(hv): -X self.anchor = h -X self.oldval = self.val -X self.active = 1 -X # -X def mouse_move(self, detail): -X if self.active: -X h, v = detail[_HV] -X self.setval(self.oldval + (h - self.anchor)) -X # -X def mouse_up(self, detail): -X if self.active: -X h, v = detail[_HV] -X self.setval(self.oldval + (h - self.anchor)) -X self.active = 0 -X # +X # +X def mouse_down(self, detail): +X h, v = hv = detail[_HV] +X if self.enabled and self.mousetest(hv): +X self.anchor = h +X self.oldval = self.val +X self.active = 1 +X # +X def mouse_move(self, detail): +X if self.active: +X h, v = detail[_HV] +X self.setval(self.oldval + (h - self.anchor)) +X # +X def mouse_up(self, detail): +X if self.active: +X h, v = detail[_HV] +X self.setval(self.oldval + (h - self.anchor)) +X self.active = 0 +X # X Xclass DragSliderAppearance() = ButtonAppearance(): -X # -X # INVARIANTS maintained by the setval method: -X # -X # self.min <= self.val <= self.max -X # self.text = self.pretext + `self.val` + self.postext -X # -X # (Notice that unlike Python ranges, the end point belongs -X # to the range.) -X # -X def init_appearance(self): -X ButtonAppearance.init_appearance(self) -X self.min = 0 -X self.val = 0 -X self.max = 100 -X self.hook = 0 -X self.pretext = self.postext = '' -X self.recalctext() -X # -X # The 'get*' and 'set*' methods belong to the generic slider interface -X # -X def getval(self): return self.val -X # -X def sethook(self, hook): -X self.hook = hook -X # -X def setminvalmax(self, (min, val, max)): -X self.min = min -X self.max = max -X self.setval(val) -X # -X def settexts(self, (pretext, postext)): -X self.pretext = pretext -X self.postext = postext -X self.recalctext() -X # -X def setval(self, val): -X val = min(self.max, max(self.min, val)) -X if val <> self.val: -X self.val = val -X self.recalctext() -X self.trigger() -X # -X def trigger(self): -X if self.hook: -X self.hook(self) -X # -X def recalctext(self): -X self.settext(self.pretext + `self.val` + self.postext) -X # +X # +X # INVARIANTS maintained by the setval method: +X # +X # self.min <= self.val <= self.max +X # self.text = self.pretext + `self.val` + self.postext +X # +X # (Notice that unlike Python ranges, the end point belongs +X # to the range.) +X # +X def init_appearance(self): +X ButtonAppearance.init_appearance(self) +X self.min = 0 +X self.val = 0 +X self.max = 100 +X self.hook = 0 +X self.pretext = self.postext = '' +X self.recalctext() +X # +X # The 'get*' and 'set*' methods belong to the generic slider interface +X # +X def getval(self): return self.val +X # +X def sethook(self, hook): +X self.hook = hook +X # +X def setminvalmax(self, (min, val, max)): +X self.min = min +X self.max = max +X self.setval(val) +X # +X def settexts(self, (pretext, postext)): +X self.pretext = pretext +X self.postext = postext +X self.recalctext() +X # +X def setval(self, val): +X val = min(self.max, max(self.min, val)) +X if val <> self.val: +X self.val = val +X self.recalctext() +X self.trigger() +X # +X def trigger(self): +X if self.hook: +X self.hook(self) +X # +X def recalctext(self): +X self.settext(self.pretext + `self.val` + self.postext) +X # X Xclass DragSlider() = DragSliderReactivity(), DragSliderAppearance(), Define(): -X def definetext(self, (parent, text)): -X raise RuntimeError, 'DragSlider.definetext() not supported' +X def definetext(self, (parent, text)): +X raise RuntimeError, 'DragSlider.definetext() not supported' X X X# Auxiliary class for PushButton incorporated in ComplexSlider X# Xclass _StepButton() = PushButton(): -X def define(self, parent): -X self = PushButton.define(self, parent) -X self.step = 0 -X return self -X def setstep(self, step): -X self.step = step -X def definetextstep(self, (parent, text, step)): -X self = self.definetext(parent, text) -X self.setstep(step) -X return self -X def init_reactivity(self): -X PushButton.init_reactivity(self) -X self.parent.need_timer(self) -X def step_trigger(self): -X self.parent.setval(self.parent.getval() + self.step) -X def down_trigger(self): -X self.step_trigger() -X self.parent.settimer(5) -X def timer(self): -X if self.hilited: -X self.step_trigger() -X if self.active: -X self.parent.settimer(1) +X def define(self, parent): +X self = PushButton.define(self, parent) +X self.step = 0 +X return self +X def setstep(self, step): +X self.step = step +X def definetextstep(self, (parent, text, step)): +X self = self.definetext(parent, text) +X self.setstep(step) +X return self +X def init_reactivity(self): +X PushButton.init_reactivity(self) +X self.parent.need_timer(self) +X def step_trigger(self): +X self.parent.setval(self.parent.getval() + self.step) +X def down_trigger(self): +X self.step_trigger() +X self.parent.settimer(5) +X def timer(self): +X if self.hilited: +X self.step_trigger() +X if self.active: +X self.parent.settimer(1) X X X# A complex slider is an HSplit initialized to three buttons: X# one to step down, a dragslider, and one to step up. X# Xclass ComplexSlider() = HSplit(): -X # -X # Override Slider define() method -X # -X def define(self, parent): -X self = self.create(parent) # HSplit -X # -X self.downbutton = _StepButton().definetextstep(self, '-', -1) -X self.dragbutton = DragSlider().define(self) -X self.upbutton = _StepButton().definetextstep(self, '+', 1) -X # -X return self -X # -X # Override HSplit methods -X # -X def minsize(self, m): -X w1, h1 = self.downbutton.minsize(m) -X w2, h2 = self.dragbutton.minsize(m) -X w3, h3 = self.upbutton.minsize(m) -X height = max(h1, h2, h3) -X w1 = max(w1, height) -X w3 = max(w3, height) -X return w1+w2+w3, height -X # -X def setbounds(self, bounds): -X (left, top), (right, bottom) = self.bounds = bounds -X size = bottom - top -X self.downbutton.setbounds((left, top), (left+size, bottom)) -X self.dragbutton.setbounds((left+size, top), \ -X (right-size, bottom)) -X self.upbutton.setbounds((right-size, top), (right, bottom)) -X # -X # Pass other Slider methods on to dragbutton -X # -X def getval(self): return self.dragbutton.getval() -X def sethook(self, hook): self.dragbutton.sethook(hook) -X def setminvalmax(self, args): self.dragbutton.setminvalmax(args) -X def settexts(self, args): self.dragbutton.settexts(args) -X def setval(self, val): self.dragbutton.setval(val) -X def enable(self, flag): -X self.downbutton.enable(flag) -X self.dragbutton.enable(flag) -X self.upbutton.enable(flag) +X # +X # Override Slider define() method +X # +X def define(self, parent): +X self = self.create(parent) # HSplit +X # +X self.downbutton = _StepButton().definetextstep(self, '-', -1) +X self.dragbutton = DragSlider().define(self) +X self.upbutton = _StepButton().definetextstep(self, '+', 1) +X # +X return self +X # +X # Override HSplit methods +X # +X def minsize(self, m): +X w1, h1 = self.downbutton.minsize(m) +X w2, h2 = self.dragbutton.minsize(m) +X w3, h3 = self.upbutton.minsize(m) +X height = max(h1, h2, h3) +X w1 = max(w1, height) +X w3 = max(w3, height) +X return w1+w2+w3, height +X # +X def setbounds(self, bounds): +X (left, top), (right, bottom) = self.bounds = bounds +X size = bottom - top +X self.downbutton.setbounds((left, top), (left+size, bottom)) +X self.dragbutton.setbounds((left+size, top), \ +X (right-size, bottom)) +X self.upbutton.setbounds((right-size, top), (right, bottom)) +X # +X # Pass other Slider methods on to dragbutton +X # +X def getval(self): return self.dragbutton.getval() +X def sethook(self, hook): self.dragbutton.sethook(hook) +X def setminvalmax(self, args): self.dragbutton.setminvalmax(args) +X def settexts(self, args): self.dragbutton.settexts(args) +X def setval(self, val): self.dragbutton.setval(val) +X def enable(self, flag): +X self.downbutton.enable(flag) +X self.dragbutton.enable(flag) +X self.upbutton.enable(flag) EOF fi if test -s 'lib/clock.py' @@ -496,7 +496,7 @@ X# Click or activate the window to turn the ringing off. X Ximport stdwin Xfrom stdwinevents import WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP, \ -X WE_TIMER, WE_DRAW, WE_SIZE, WE_CLOSE, WE_ACTIVATE +X WE_TIMER, WE_DRAW, WE_SIZE, WE_CLOSE, WE_ACTIVATE Ximport time Xfrom math import sin, cos, atan2, pi, sqrt X @@ -507,179 +507,179 @@ Xorigin = 0, 0 Xfaraway = 2000, 2000 Xeverywhere = origin, faraway X -Xclass struct(): pass # A class to declare featureless objects +Xclass struct(): pass # A class to declare featureless objects X -XG = struct() # Global variables (most set in setdimensions()) -XG.tzdiff = 5*3600 # THINK computes UCT from local time assuming EST! +XG = struct() # Global variables (most set in setdimensions()) +XG.tzdiff = 5*3600 # THINK computes UCT from local time assuming EST! X -XA = struct() # Globals used by the alarm -XA.set = 1 # True when alarm is set -XA.time = 11*60 + 40 # Time when alarm must go off -XA.ring = 0 # True when alarm is ringing +XA = struct() # Globals used by the alarm +XA.set = 1 # True when alarm is set +XA.time = 11*60 + 40 # Time when alarm must go off +XA.ring = 0 # True when alarm is ringing X Xdef main(): -X try: -X realmain() -X except KeyboardInterrupt: -X print 'KeyboardInterrupt' -X finally: -X G.w = 0 +X try: +X realmain() +X except KeyboardInterrupt: +X print 'KeyboardInterrupt' +X finally: +X G.w = 0 X Xdef realmain(): -X setdimensions(DEFWIDTH, DEFHEIGHT) -X stdwin.setdefwinsize(G.farcorner) -X G.w = stdwin.open('klok') -X settimer() -X while 1: -X type, window, detail = stdwin.getevent() -X if type = WE_DRAW: -X drawproc(detail) -X elif type = WE_TIMER: -X settimer() -X drawproc(everywhere) -X elif type in mouse_events: -X mouseclick(type, detail) -X elif type = WE_ACTIVATE: -X if A.ring: -X # Turn the ringing off -X A.ring = 0 -X G.w.begindrawing().invert(G.mainarea) -X elif type = WE_SIZE: -X G.w.change(everywhere) -X width, height = G.w.getwinsize() -X height = height - stdwin.lineheight() -X setdimensions(width, height) -X elif type = WE_CLOSE: -X break +X setdimensions(DEFWIDTH, DEFHEIGHT) +X stdwin.setdefwinsize(G.farcorner) +X G.w = stdwin.open('klok') +X settimer() +X while 1: +X type, window, detail = stdwin.getevent() +X if type = WE_DRAW: +X drawproc(detail) +X elif type = WE_TIMER: +X settimer() +X drawproc(everywhere) +X elif type in mouse_events: +X mouseclick(type, detail) +X elif type = WE_ACTIVATE: +X if A.ring: +X # Turn the ringing off +X A.ring = 0 +X G.w.begindrawing().invert(G.mainarea) +X elif type = WE_SIZE: +X G.w.change(everywhere) +X width, height = G.w.getwinsize() +X height = height - stdwin.lineheight() +X setdimensions(width, height) +X elif type = WE_CLOSE: +X break X Xdef setdimensions(width, height): -X if width < height: size = width -X else: size = height -X halfwidth = width/2 -X halfheight = height/2 -X G.center = halfwidth, halfheight -X G.radius = size*45/100 -X G.width = width -X G.height = height -X G.corner = width, height -X G.mainarea = origin, G.corner -X G.lineheight = stdwin.lineheight() -X G.farcorner = width, height + G.lineheight -X G.statusarea = (0, height), G.farcorner -X G.fullarea = origin, G.farcorner +X if width < height: size = width +X else: size = height +X halfwidth = width/2 +X halfheight = height/2 +X G.center = halfwidth, halfheight +X G.radius = size*45/100 +X G.width = width +X G.height = height +X G.corner = width, height +X G.mainarea = origin, G.corner +X G.lineheight = stdwin.lineheight() +X G.farcorner = width, height + G.lineheight +X G.statusarea = (0, height), G.farcorner +X G.fullarea = origin, G.farcorner X Xdef settimer(): -X now = getlocaltime() -X G.times = calctime(now) -X delay = 61 - now % 60 -X G.w.settimer(10 * delay) -X minutes = (now/60) % 720 -X if A.ring: -X # Is it time to stop the alarm ringing? -X since = (minutes - A.time + 720) % 720 -X if since >= 5: -X # Stop it now -X A.ring = 0 -X else: -X # Ring again, once every minute -X stdwin.fleep() -X elif A.set and minutes = A.time: -X # Start the alarm ringing -X A.ring = 1 -X stdwin.fleep() +X now = getlocaltime() +X G.times = calctime(now) +X delay = 61 - now % 60 +X G.w.settimer(10 * delay) +X minutes = (now/60) % 720 +X if A.ring: +X # Is it time to stop the alarm ringing? +X since = (minutes - A.time + 720) % 720 +X if since >= 5: +X # Stop it now +X A.ring = 0 +X else: +X # Ring again, once every minute +X stdwin.fleep() +X elif A.set and minutes = A.time: +X # Start the alarm ringing +X A.ring = 1 +X stdwin.fleep() X Xdef drawproc(area): -X hours, minutes, seconds = G.times -X d = G.w.begindrawing() -X d.cliprect(area) -X d.erase(everywhere) -X d.circle(G.center, G.radius) -X d.line(G.center, calcpoint(hours*30 + minutes/2, 0.6)) -X d.line(G.center, calcpoint(minutes*6, 1.0)) -X str = dd(hours) + ':' + dd(minutes) -X p = (G.width - d.textwidth(str))/2, G.height * 3 / 4 -X d.text(p, str) -X if A.set: -X drawalarm(d) -X drawalarmtime(d) -X if A.ring: -X d.invert(G.mainarea) +X hours, minutes, seconds = G.times +X d = G.w.begindrawing() +X d.cliprect(area) +X d.erase(everywhere) +X d.circle(G.center, G.radius) +X d.line(G.center, calcpoint(hours*30 + minutes/2, 0.6)) +X d.line(G.center, calcpoint(minutes*6, 1.0)) +X str = dd(hours) + ':' + dd(minutes) +X p = (G.width - d.textwidth(str))/2, G.height * 3 / 4 +X d.text(p, str) +X if A.set: +X drawalarm(d) +X drawalarmtime(d) +X if A.ring: +X d.invert(G.mainarea) X Xdef mouseclick(type, detail): -X d = G.w.begindrawing() -X if A.ring: -X # First turn the ringing off -X A.ring = 0 -X d.invert(G.mainarea) -X h, v = detail[0] -X ch, cv = G.center -X x, y = h-ch, cv-v -X dist = sqrt(x*x + y*y) / float(G.radius) -X if dist > 1.2: -X if A.set: -X drawalarm(d) -X erasealarmtime(d) -X A.set = 0 -X elif dist < 0.8: -X if not A.set: -X A.set = 1 -X drawalarm(d) -X drawalarmtime(d) -X else: -X # Convert to half-degrees (range 0..720) -X alpha = atan2(y, x) -X hdeg = alpha*360.0/pi -X hdeg = 180.0 - hdeg -X hdeg = (hdeg + 720.0) % 720.0 -X atime = 5*int(hdeg/5.0 + 0.5) -X if atime <> A.time or not A.set: -X if A.set: -X drawalarm(d) -X erasealarmtime(d) -X A.set = 1 -X A.time = atime -X drawalarm(d) -X drawalarmtime(d) +X d = G.w.begindrawing() +X if A.ring: +X # First turn the ringing off +X A.ring = 0 +X d.invert(G.mainarea) +X h, v = detail[0] +X ch, cv = G.center +X x, y = h-ch, cv-v +X dist = sqrt(x*x + y*y) / float(G.radius) +X if dist > 1.2: +X if A.set: +X drawalarm(d) +X erasealarmtime(d) +X A.set = 0 +X elif dist < 0.8: +X if not A.set: +X A.set = 1 +X drawalarm(d) +X drawalarmtime(d) +X else: +X # Convert to half-degrees (range 0..720) +X alpha = atan2(y, x) +X hdeg = alpha*360.0/pi +X hdeg = 180.0 - hdeg +X hdeg = (hdeg + 720.0) % 720.0 +X atime = 5*int(hdeg/5.0 + 0.5) +X if atime <> A.time or not A.set: +X if A.set: +X drawalarm(d) +X erasealarmtime(d) +X A.set = 1 +X A.time = atime +X drawalarm(d) +X drawalarmtime(d) X Xdef drawalarm(d): -X p1 = calcpoint(float(A.time)/2.0, 1.02) -X p2 = calcpoint(float(A.time)/2.0 - 4.0, 1.1) -X p3 = calcpoint(float(A.time)/2.0 + 4.0, 1.1) -X d.xorline(p1, p2) -X d.xorline(p2, p3) -X d.xorline(p3, p1) +X p1 = calcpoint(float(A.time)/2.0, 1.02) +X p2 = calcpoint(float(A.time)/2.0 - 4.0, 1.1) +X p3 = calcpoint(float(A.time)/2.0 + 4.0, 1.1) +X d.xorline(p1, p2) +X d.xorline(p2, p3) +X d.xorline(p3, p1) X Xdef erasealarmtime(d): -X d.erase(G.statusarea) +X d.erase(G.statusarea) X Xdef drawalarmtime(d): -X # A.time is in the range 0..720 with origin at 12 o'clock -X # Convert to hours (0..12) and minutes (12*(0..60)) -X hh = A.time/60 -X mm = A.time%60 -X str = 'Alarm@' + dd(hh) + ':' + dd(mm) -X p1 = (G.width - d.textwidth(str))/2, G.height -X d.text(p1, str) +X # A.time is in the range 0..720 with origin at 12 o'clock +X # Convert to hours (0..12) and minutes (12*(0..60)) +X hh = A.time/60 +X mm = A.time%60 +X str = 'Alarm@' + dd(hh) + ':' + dd(mm) +X p1 = (G.width - d.textwidth(str))/2, G.height +X d.text(p1, str) X Xdef calctime(now): -X seconds = now % 60 -X minutes = (now/60) % 60 -X hours = (now/3600) % 12 -X return hours, minutes, seconds +X seconds = now % 60 +X minutes = (now/60) % 60 +X hours = (now/3600) % 12 +X return hours, minutes, seconds X Xdef calcpoint(degrees, size): -X alpha = pi/2.0 - float(degrees) * pi/180.0 -X x, y = cos(alpha), sin(alpha) -X h, v = G.center -X r = float(G.radius) -X return h + int(x*size*r), v - int(y*size*r) +X alpha = pi/2.0 - float(degrees) * pi/180.0 +X x, y = cos(alpha), sin(alpha) +X h, v = G.center +X r = float(G.radius) +X return h + int(x*size*r), v - int(y*size*r) X Xdef dd(n): -X s = `n` -X return '0'*(2-len(s)) + s +X s = `n` +X return '0'*(2-len(s)) + s X Xdef getlocaltime(): -X return time.time() - G.tzdiff +X return time.time() - G.tzdiff X X#main() EOF @@ -705,193 +705,193 @@ X X# Directory comparison class. X# Xclass dircmp(): -X # -X def new(dd, (a, b)): # Initialize -X dd.a = a -X dd.b = b -X # Properties that caller may change before callingdd. run(): -X dd.hide = ['.', '..'] # Names never to be shown -X dd.ignore = ['RCS', 'tags'] # Names ignored in comparison -X # -X return dd -X # -X def run(dd): # Compare everything except common subdirectories -X dd.a_list = filter(dircache.listdir(dd.a), dd.hide) -X dd.b_list = filter(dircache.listdir(dd.b), dd.hide) -X dd.a_list.sort() -X dd.b_list.sort() -X dd.phase1() -X dd.phase2() -X dd.phase3() -X # -X def phase1(dd): # Compute common names -X dd.a_only = [] -X dd.common = [] -X for x in dd.a_list: -X if x in dd.b_list: -X dd.common.append(x) -X else: -X dd.a_only.append(x) -X # -X dd.b_only = [] -X for x in dd.b_list: -X if x not in dd.common: -X dd.b_only.append(x) -X # -X def phase2(dd): # Distinguish files, directories, funnies -X dd.common_dirs = [] -X dd.common_files = [] -X dd.common_funny = [] -X # -X for x in dd.common: -X a_path = path.cat(dd.a, x) -X b_path = path.cat(dd.b, x) -X # -X ok = 1 -X try: -X a_stat = statcache.stat(a_path) -X except posix.error, why: -X # print 'Can\'t stat', a_path, ':', why[1] -X ok = 0 -X try: -X b_stat = statcache.stat(b_path) -X except posix.error, why: -X # print 'Can\'t stat', b_path, ':', why[1] -X ok = 0 -X # -X if ok: -X a_type = S_IFMT(a_stat[ST_MODE]) -X b_type = S_IFMT(b_stat[ST_MODE]) -X if a_type <> b_type: -X dd.common_funny.append(x) -X elif S_ISDIR(a_type): -X dd.common_dirs.append(x) -X elif S_ISREG(a_type): -X dd.common_files.append(x) -X else: -X dd.common_funny.append(x) -X else: -X dd.common_funny.append(x) -X # -X def phase3(dd): # Find out differences between common files -X xx = cmpfiles(dd.a, dd.b, dd.common_files) -X dd.same_files, dd.diff_files, dd.funny_files = xx -X # -X def phase4(dd): # Find out differences between common subdirectories -X # A new dircmp object is created for each common subdirectory, -X # these are stored in a dictionary indexed by filename. -X # The hide and ignore properties are inherited from the parent -X dd.subdirs = {} -X for x in dd.common_dirs: -X a_x = path.cat(dd.a, x) -X b_x = path.cat(dd.b, x) -X dd.subdirs[x] = newdd = dircmp().new(a_x, b_x) -X newdd.hide = dd.hide -X newdd.ignore = dd.ignore -X newdd.run() -X # -X def phase4_closure(dd): # Recursively call phase4() on subdirectories -X dd.phase4() -X for x in dd.subdirs.keys(): -X dd.subdirs[x].phase4_closure() -X # -X def report(dd): # Print a report on the differences between a and b -X # Assume that phases 1 to 3 have been executed -X # Output format is purposely lousy -X print 'diff', dd.a, dd.b -X if dd.a_only: -X print 'Only in', dd.a, ':', dd.a_only -X if dd.b_only: -X print 'Only in', dd.b, ':', dd.b_only -X if dd.same_files: -X print 'Identical files :', dd.same_files -X if dd.diff_files: -X print 'Differing files :', dd.diff_files -X if dd.funny_files: -X print 'Trouble with common files :', dd.funny_files -X if dd.common_dirs: -X print 'Common subdirectories :', dd.common_dirs -X if dd.common_funny: -X print 'Common funny cases :', dd.common_funny -X # -X def report_closure(dd): # Print reports on dd and on subdirs -X # If phase 4 hasn't been done, no subdir reports are printed -X dd.report() -X try: -X x = dd.subdirs -X except NameError: -X return # No subdirectories computed -X for x in dd.subdirs.keys(): -X print -X dd.subdirs[x].report_closure() -X # -X def report_phase4_closure(dd): # Report and do phase 4 recursively -X dd.report() -X dd.phase4() -X for x in dd.subdirs.keys(): -X print -X dd.subdirs[x].report_phase4_closure() +X # +X def new(dd, (a, b)): # Initialize +X dd.a = a +X dd.b = b +X # Properties that caller may change before callingdd. run(): +X dd.hide = ['.', '..'] # Names never to be shown +X dd.ignore = ['RCS', 'tags'] # Names ignored in comparison +X # +X return dd +X # +X def run(dd): # Compare everything except common subdirectories +X dd.a_list = filter(dircache.listdir(dd.a), dd.hide) +X dd.b_list = filter(dircache.listdir(dd.b), dd.hide) +X dd.a_list.sort() +X dd.b_list.sort() +X dd.phase1() +X dd.phase2() +X dd.phase3() +X # +X def phase1(dd): # Compute common names +X dd.a_only = [] +X dd.common = [] +X for x in dd.a_list: +X if x in dd.b_list: +X dd.common.append(x) +X else: +X dd.a_only.append(x) +X # +X dd.b_only = [] +X for x in dd.b_list: +X if x not in dd.common: +X dd.b_only.append(x) +X # +X def phase2(dd): # Distinguish files, directories, funnies +X dd.common_dirs = [] +X dd.common_files = [] +X dd.common_funny = [] +X # +X for x in dd.common: +X a_path = path.cat(dd.a, x) +X b_path = path.cat(dd.b, x) +X # +X ok = 1 +X try: +X a_stat = statcache.stat(a_path) +X except posix.error, why: +X # print 'Can\'t stat', a_path, ':', why[1] +X ok = 0 +X try: +X b_stat = statcache.stat(b_path) +X except posix.error, why: +X # print 'Can\'t stat', b_path, ':', why[1] +X ok = 0 +X # +X if ok: +X a_type = S_IFMT(a_stat[ST_MODE]) +X b_type = S_IFMT(b_stat[ST_MODE]) +X if a_type <> b_type: +X dd.common_funny.append(x) +X elif S_ISDIR(a_type): +X dd.common_dirs.append(x) +X elif S_ISREG(a_type): +X dd.common_files.append(x) +X else: +X dd.common_funny.append(x) +X else: +X dd.common_funny.append(x) +X # +X def phase3(dd): # Find out differences between common files +X xx = cmpfiles(dd.a, dd.b, dd.common_files) +X dd.same_files, dd.diff_files, dd.funny_files = xx +X # +X def phase4(dd): # Find out differences between common subdirectories +X # A new dircmp object is created for each common subdirectory, +X # these are stored in a dictionary indexed by filename. +X # The hide and ignore properties are inherited from the parent +X dd.subdirs = {} +X for x in dd.common_dirs: +X a_x = path.cat(dd.a, x) +X b_x = path.cat(dd.b, x) +X dd.subdirs[x] = newdd = dircmp().new(a_x, b_x) +X newdd.hide = dd.hide +X newdd.ignore = dd.ignore +X newdd.run() +X # +X def phase4_closure(dd): # Recursively call phase4() on subdirectories +X dd.phase4() +X for x in dd.subdirs.keys(): +X dd.subdirs[x].phase4_closure() +X # +X def report(dd): # Print a report on the differences between a and b +X # Assume that phases 1 to 3 have been executed +X # Output format is purposely lousy +X print 'diff', dd.a, dd.b +X if dd.a_only: +X print 'Only in', dd.a, ':', dd.a_only +X if dd.b_only: +X print 'Only in', dd.b, ':', dd.b_only +X if dd.same_files: +X print 'Identical files :', dd.same_files +X if dd.diff_files: +X print 'Differing files :', dd.diff_files +X if dd.funny_files: +X print 'Trouble with common files :', dd.funny_files +X if dd.common_dirs: +X print 'Common subdirectories :', dd.common_dirs +X if dd.common_funny: +X print 'Common funny cases :', dd.common_funny +X # +X def report_closure(dd): # Print reports on dd and on subdirs +X # If phase 4 hasn't been done, no subdir reports are printed +X dd.report() +X try: +X x = dd.subdirs +X except NameError: +X return # No subdirectories computed +X for x in dd.subdirs.keys(): +X print +X dd.subdirs[x].report_closure() +X # +X def report_phase4_closure(dd): # Report and do phase 4 recursively +X dd.report() +X dd.phase4() +X for x in dd.subdirs.keys(): +X print +X dd.subdirs[x].report_phase4_closure() X X X# Compare common files in two directories. X# Return: -X# - files that compare equal -X# - files that compare different -X# - funny cases (can't stat etc.) +X# - files that compare equal +X# - files that compare different +X# - funny cases (can't stat etc.) X# Xdef cmpfiles(a, b, common): -X res = ([], [], []) -X for x in common: -X res[cmp(path.cat(a, x), path.cat(b, x))].append(x) -X return res +X res = ([], [], []) +X for x in common: +X res[cmp(path.cat(a, x), path.cat(b, x))].append(x) +X return res X X X# Compare two files. X# Return: -X# 0 for equal -X# 1 for different -X# 2 for funny cases (can't stat, etc.) +X# 0 for equal +X# 1 for different +X# 2 for funny cases (can't stat, etc.) X# Xdef cmp(a, b): -X try: -X if cmpcache.cmp(a, b): return 0 -X return 1 -X except posix.error: -X return 2 +X try: +X if cmpcache.cmp(a, b): return 0 +X return 1 +X except posix.error: +X return 2 X X X# Remove a list item. X# NB: This modifies the list argument. X# Xdef remove(list, item): -X for i in range(len(list)): -X if list[i] = item: -X del list[i] -X break +X for i in range(len(list)): +X if list[i] = item: +X del list[i] +X break X X X# Return a copy with items that occur in skip removed. X# Xdef filter(list, skip): -X result = [] -X for item in list: -X if item not in skip: result.append(item) -X return result +X result = [] +X for item in list: +X if item not in skip: result.append(item) +X return result X X X# Demonstration and testing. X# Xdef demo(): -X import sys -X import getopt -X options, args = getopt.getopt(sys.argv[1:], 'r') -X if len(args) <> 2: raise getopt.error, 'need exactly two args' -X dd = dircmp().new(args[0], args[1]) -X dd.run() -X if ('-r', '') in options: -X dd.report_phase4_closure() -X else: -X dd.report() +X import sys +X import getopt +X options, args = getopt.getopt(sys.argv[1:], 'r') +X if len(args) <> 2: raise getopt.error, 'need exactly two args' +X dd = dircmp().new(args[0], args[1]) +X dd.run() +X if ('-r', '') in options: +X dd.report_phase4_closure() +X else: +X dd.report() X X# demo() EOF @@ -907,64 +907,64 @@ Ximport sys Ximport string X Xdef dis(): -X tb = sys.last_traceback -X while tb.tb_next: tb = tb.tb_next -X distb(tb) +X tb = sys.last_traceback +X while tb.tb_next: tb = tb.tb_next +X distb(tb) X Xdef distb(tb): -X disassemble(tb.tb_frame.f_code, tb.tb_lasti) +X disassemble(tb.tb_frame.f_code, tb.tb_lasti) X Xdef disco(co): -X disassemble(co, -1) +X disassemble(co, -1) X Xdef disassemble(co, lasti): -X code = co.co_code -X labels = findlabels(code) -X n = len(code) -X i = 0 -X while i < n: -X c = code[i] -X op = ord(c) -X if op = SET_LINENO and i > 0: print # Extra blank line -X if i = lasti: print '-->', -X else: print ' ', -X if i in labels: print '>>', -X else: print ' ', -X print string.rjust(`i`, 4), -X print string.ljust(opname[op], 15), -X i = i+1 -X if op >= HAVE_ARGUMENT: -X oparg = ord(code[i]) + ord(code[i+1])*256 -X i = i+2 -X print string.rjust(`oparg`, 5), -X if op in hasconst: -X print '(' + `co.co_consts[oparg]` + ')', -X elif op in hasname: -X print '(' + co.co_names[oparg] + ')', -X elif op in hasjrel: -X print '(to ' + `i + oparg` + ')', -X print +X code = co.co_code +X labels = findlabels(code) +X n = len(code) +X i = 0 +X while i < n: +X c = code[i] +X op = ord(c) +X if op = SET_LINENO and i > 0: print # Extra blank line +X if i = lasti: print '-->', +X else: print ' ', +X if i in labels: print '>>', +X else: print ' ', +X print string.rjust(`i`, 4), +X print string.ljust(opname[op], 15), +X i = i+1 +X if op >= HAVE_ARGUMENT: +X oparg = ord(code[i]) + ord(code[i+1])*256 +X i = i+2 +X print string.rjust(`oparg`, 5), +X if op in hasconst: +X print '(' + `co.co_consts[oparg]` + ')', +X elif op in hasname: +X print '(' + co.co_names[oparg] + ')', +X elif op in hasjrel: +X print '(to ' + `i + oparg` + ')', +X print X Xdef findlabels(code): -X labels = [] -X n = len(code) -X i = 0 -X while i < n: -X c = code[i] -X op = ord(c) -X i = i+1 -X if op >= HAVE_ARGUMENT: -X oparg = ord(code[i]) + ord(code[i+1])*256 -X i = i+2 -X label = -1 -X if op in hasjrel: -X label = i+oparg -X elif op in hasjabs: -X label = oparg -X if label >= 0: -X if label not in labels: -X labels.append(label) -X return labels +X labels = [] +X n = len(code) +X i = 0 +X while i < n: +X c = code[i] +X op = ord(c) +X i = i+1 +X if op >= HAVE_ARGUMENT: +X oparg = ord(code[i]) + ord(code[i+1])*256 +X i = i+2 +X label = -1 +X if op in hasjrel: +X label = i+oparg +X elif op in hasjabs: +X label = oparg +X if label >= 0: +X if label not in labels: +X labels.append(label) +X return labels X Xhasconst = [] Xhasname = [] @@ -975,19 +975,19 @@ Xopname = range(256) Xfor op in opname: opname[op] = '<' + `op` + '>' X Xdef def_op(name, op): -X opname[op] = name +X opname[op] = name X Xdef name_op(name, op): -X opname[op] = name -X hasname.append(op) +X opname[op] = name +X hasname.append(op) X Xdef jrel_op(name, op): -X opname[op] = name -X hasjrel.append(op) +X opname[op] = name +X hasjrel.append(op) X Xdef jabs_op(name, op): -X opname[op] = name -X hasjabs.append(op) +X opname[op] = name +X hasjabs.append(op) X X# Instruction opcodes for compiled code X @@ -1044,38 +1044,38 @@ Xdef_op('POP_BLOCK', 87) Xdef_op('END_FINALLY', 88) Xdef_op('BUILD_CLASS', 89) X -XHAVE_ARGUMENT = 90 # Opcodes from here have an argument: +XHAVE_ARGUMENT = 90 # Opcodes from here have an argument: X -Xname_op('STORE_NAME', 90) # Index in name list -Xname_op('DELETE_NAME', 91) # "" -Xdef_op('UNPACK_TUPLE', 92) # Number of tuple items -Xdef_op('UNPACK_LIST', 93) # Number of list items -X# unused: 94 -Xname_op('STORE_ATTR', 95) # Index in name list -Xname_op('DELETE_ATTR', 96) # "" +Xname_op('STORE_NAME', 90) # Index in name list +Xname_op('DELETE_NAME', 91) # "" +Xdef_op('UNPACK_TUPLE', 92) # Number of tuple items +Xdef_op('UNPACK_LIST', 93) # Number of list items +X# unused: 94 +Xname_op('STORE_ATTR', 95) # Index in name list +Xname_op('DELETE_ATTR', 96) # "" X -Xdef_op('LOAD_CONST', 100) # Index in const list +Xdef_op('LOAD_CONST', 100) # Index in const list Xhasconst.append(100) -Xname_op('LOAD_NAME', 101) # Index in name list -Xdef_op('BUILD_TUPLE', 102) # Number of tuple items -Xdef_op('BUILD_LIST', 103) # Number of list items -Xdef_op('BUILD_MAP', 104) # Always zero for now -Xname_op('LOAD_ATTR', 105) # Index in name list -Xdef_op('COMPARE_OP', 106) # Comparison operator -Xname_op('IMPORT_NAME', 107) # Index in name list -Xname_op('IMPORT_FROM', 108) # Index in name list -X -Xjrel_op('JUMP_FORWARD', 110) # Number of bytes to skip -Xjrel_op('JUMP_IF_FALSE', 111) # "" -Xjrel_op('JUMP_IF_TRUE', 112) # "" -Xjabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code -Xjrel_op('FOR_LOOP', 114) # Number of bytes to skip -X -Xjrel_op('SETUP_LOOP', 120) # Distance to target address -Xjrel_op('SETUP_EXCEPT', 121) # "" -Xjrel_op('SETUP_FINALLY', 122) # "" -X -Xdef_op('SET_LINENO', 127) # Current line number +Xname_op('LOAD_NAME', 101) # Index in name list +Xdef_op('BUILD_TUPLE', 102) # Number of tuple items +Xdef_op('BUILD_LIST', 103) # Number of list items +Xdef_op('BUILD_MAP', 104) # Always zero for now +Xname_op('LOAD_ATTR', 105) # Index in name list +Xdef_op('COMPARE_OP', 106) # Comparison operator +Xname_op('IMPORT_NAME', 107) # Index in name list +Xname_op('IMPORT_FROM', 108) # Index in name list +X +Xjrel_op('JUMP_FORWARD', 110) # Number of bytes to skip +Xjrel_op('JUMP_IF_FALSE', 111) # "" +Xjrel_op('JUMP_IF_TRUE', 112) # "" +Xjabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code +Xjrel_op('FOR_LOOP', 114) # Number of bytes to skip +X +Xjrel_op('SETUP_LOOP', 120) # Distance to target address +Xjrel_op('SETUP_EXCEPT', 121) # "" +Xjrel_op('SETUP_FINALLY', 122) # "" +X +Xdef_op('SET_LINENO', 127) # Current line number XSET_LINENO = 127 EOF fi @@ -1099,16 +1099,16 @@ X# To implement this we create a class member, of which fx is a method; X# f and x are stored as data attributes of the member. X Xclass _CurryClass(): -X def new(self, (f, x)): -X self.f = f -X self.x = x -X return self -X def fx(self, y): -X return self.f(self.x, y) +X def new(self, (f, x)): +X self.f = f +X self.x = x +X return self +X def fx(self, y): +X return self.f(self.x, y) X Xdef CURRY(f, x): -X # NB: f is not "simple": it has 2 arguments -X return _CurryClass().new(f, x).fx +X # NB: f is not "simple": it has 2 arguments +X return _CurryClass().new(f, x).fx X X X# Numbers in Lambda Calculus @@ -1118,9 +1118,9 @@ X# higher-order functions Ntimes(f, x) that yield f applied N X# times to x, e.g., Twice(f, x) = f(f(x)). X# As far as I understand, there is no difference in real lambda X# calculus between -X# lambda f x : f(f(x)) +X# lambda f x : f(f(x)) X# and -X# lambda f : f o f # 'o' means function composition +X# lambda f : f o f # 'o' means function composition X# but in Python we have to write the first as Twice(f, x) and X# the second as twice(f). X @@ -1141,9 +1141,9 @@ X X X# NB: actually 'ntimes' is less concrete than 'Ntimes', as X# 'ntimes' returns a function, while 'Ntimes' returns a value -X# similar to what f(x) returns. 'Ntimes' can be derived +X# similar to what f(x) returns. 'Ntimes' can be derived X# from 'ntimes', as follows: -X# def Ntimes(f, x): return ntimes(f)(x) +X# def Ntimes(f, x): return ntimes(f)(x) X# but this doesn't help us since 'ntimes' can only be defined X# using Ntimes (or a trick like the one used by CURRY). X @@ -1151,21 +1151,21 @@ X X# Arithmetic in Lambda Calculus X# X# We can perform simple arithmetic on the un-curried versions, e.g., -X# Successor(Twice) = Thrice (2+1) -X# Sum(Thrice, Twice) = Fivefold (3+2) -X# Product(Thrice, Twice) = Sixfold (3*2) -X# Power(Thrice, Twice) = Ninefold (3**2) +X# Successor(Twice) = Thrice (2+1) +X# Sum(Thrice, Twice) = Fivefold (3+2) +X# Product(Thrice, Twice) = Sixfold (3*2) +X# Power(Thrice, Twice) = Ninefold (3**2) X# X# First we define versions that need f and x arguments. X# They have funny argument forms so the final functions can X# use CURRY, which only works on functions of exactly 2 arguments. X Xdef SUCCESSOR(Ntimes, (f, x)): return f(Ntimes(f, x)) -Xdef SUCCESSOR(Ntimes, (f, x)): return Ntimes(f, f(x)) # Same effect +Xdef SUCCESSOR(Ntimes, (f, x)): return Ntimes(f, f(x)) # Same effect Xdef SUM(Ntimes, (Mtimes, (f, x))): return Ntimes(f, Mtimes(f, x)) Xdef PRODUCT(Ntimes, (Mtimes, (f, x))): return Ntimes(CURRY(Mtimes, f), x) Xdef POWER(Ntimes, (Mtimes, (f, x))): -X return Mtimes(CURRY(CURRY, Ntimes), f)(x) +X return Mtimes(CURRY(CURRY, Ntimes), f)(x) X Xdef Successor(Ntimes): return CURRY(SUCCESSOR, Ntimes) Xdef Sum(Ntimes, Mtimes): return CURRY(CURRY(SUM, Ntimes), Mtimes) @@ -1184,54 +1184,54 @@ X X X# P.S.: Here is a Lambda function in Python. X# It uses 'exec' and expects two strings to describe the arguments -X# and the function expression. Example: -X# lambda('x', 'x+1') +X# and the function expression. Example: +X# lambda('x', 'x+1') X# defines the successor function. X Xdef lambda(args, expr): -X if '\n' in args or '\n' in expr: -X raise RuntimeError, 'lambda: no cheating!' -X stmt = 'def func(' + args + '): return ' + expr + '\n' -X print 'lambda:', stmt, -X exec(stmt) -X return func +X if '\n' in args or '\n' in expr: +X raise RuntimeError, 'lambda: no cheating!' +X stmt = 'def func(' + args + '): return ' + expr + '\n' +X print 'lambda:', stmt, +X exec(stmt) +X return func X X X# P.P.S.S.: Here is a way to construct Ntimes and ntimes directly. X# Example: -X# GenericNtimes(4) +X# GenericNtimes(4) X# is equivalent to Fourfold. X Xclass _GenericNtimesClass(): -X def new(self, n): -X self.n = n -X return self -X def Ntimes(self, (f, x)): -X n = self.n -X while n > 0: x, n = f(x), n-1 -X return x +X def new(self, n): +X self.n = n +X return self +X def Ntimes(self, (f, x)): +X n = self.n +X while n > 0: x, n = f(x), n-1 +X return x X Xdef GenericNtimes(n): -X return _GenericNtimesClass().new(n).Ntimes +X return _GenericNtimesClass().new(n).Ntimes X X X# To construct any 'ntimes' function from the corresponding 'Ntimes', -X# we use a trick as used by CURRY. For example, -X# Ntimes2ntimes(Fourfold) +X# we use a trick as used by CURRY. For example, +X# Ntimes2ntimes(Fourfold) X# yields a function equivalent to fourfold. X Xclass _Ntimes2ntimesClass(): -X def new(self, Ntimes): -X self.Ntimes = Ntimes -X return self -X def ntimes(self, f): -X return CURRY(self.Ntimes, f) +X def new(self, Ntimes): +X self.Ntimes = Ntimes +X return self +X def ntimes(self, f): +X return CURRY(self.Ntimes, f) X Xdef Ntimes2ntimes(Ntimes): return _Ntimes2ntimesClass().new(Ntimes).ntimes X X -X# This allows us to construct generic 'ntimes' functions. Example: -X# generic_ntimes(3) +X# This allows us to construct generic 'ntimes' functions. Example: +X# generic_ntimes(3) X# is the same as thrice. X Xdef generic_ntimes(n): return Ntimes2ntimes(GenericNtimes(n)) @@ -1247,11 +1247,11 @@ X# Also an interactive stack trace browser. X Ximport sys Xtry: -X import mac -X os = mac +X import mac +X os = mac Xexcept NameError: -X import posix -X os = posix +X import posix +X os = posix Xfrom stat import * Ximport string X @@ -1260,208 +1260,208 @@ X Xdef tb(): printtb(sys.last_traceback) X Xdef browser(tb): -X if not tb: -X print 'No traceback.' -X return -X tblist = [] -X while tb: -X tblist.append(tb) -X tb = tb.tb_next -X ptr = len(tblist)-1 -X tb = tblist[ptr] -X while 1: -X if tb <> tblist[ptr]: -X tb = tblist[ptr] -X print `ptr` + ':', -X printtbheader(tb) -X try: -X line = raw_input('TB: ') -X except KeyboardInterrupt: -X print '\n[Interrupted]' -X break -X except EOFError: -X print '\n[EOF]' -X break -X cmd = string.strip(line) -X if cmd: -X if cmd = 'quit': -X break -X elif cmd = 'list': -X browserlist(tb) -X elif cmd = 'up': -X if ptr-1 >= 0: ptr = ptr-1 -X else: print 'Bottom of stack.' -X elif cmd = 'down': -X if ptr+1 < len(tblist): ptr = ptr+1 -X else: print 'Top of stack.' -X elif cmd = 'locals': -X printsymbols(tb.tb_frame.f_locals) -X elif cmd = 'globals': -X printsymbols(tb.tb_frame.f_globals) -X elif cmd in ('?', 'help'): -X browserhelp() -X else: -X browserexec(tb, cmd) +X if not tb: +X print 'No traceback.' +X return +X tblist = [] +X while tb: +X tblist.append(tb) +X tb = tb.tb_next +X ptr = len(tblist)-1 +X tb = tblist[ptr] +X while 1: +X if tb <> tblist[ptr]: +X tb = tblist[ptr] +X print `ptr` + ':', +X printtbheader(tb) +X try: +X line = raw_input('TB: ') +X except KeyboardInterrupt: +X print '\n[Interrupted]' +X break +X except EOFError: +X print '\n[EOF]' +X break +X cmd = string.strip(line) +X if cmd: +X if cmd = 'quit': +X break +X elif cmd = 'list': +X browserlist(tb) +X elif cmd = 'up': +X if ptr-1 >= 0: ptr = ptr-1 +X else: print 'Bottom of stack.' +X elif cmd = 'down': +X if ptr+1 < len(tblist): ptr = ptr+1 +X else: print 'Top of stack.' +X elif cmd = 'locals': +X printsymbols(tb.tb_frame.f_locals) +X elif cmd = 'globals': +X printsymbols(tb.tb_frame.f_globals) +X elif cmd in ('?', 'help'): +X browserhelp() +X else: +X browserexec(tb, cmd) X Xdef browserlist(tb): -X filename = tb.tb_frame.f_code.co_filename -X lineno = tb.tb_lineno -X last = lineno -X first = max(1, last-10) -X for i in range(first, last+1): -X if i = lineno: prefix = '***' + string.rjust(`i`, 4) + ':' -X else: prefix = string.rjust(`i`, 7) + ':' -X line = readfileline(filename, i) -X if line[-1:] = '\n': line = line[:-1] -X print prefix + line +X filename = tb.tb_frame.f_code.co_filename +X lineno = tb.tb_lineno +X last = lineno +X first = max(1, last-10) +X for i in range(first, last+1): +X if i = lineno: prefix = '***' + string.rjust(`i`, 4) + ':' +X else: prefix = string.rjust(`i`, 7) + ':' +X line = readfileline(filename, i) +X if line[-1:] = '\n': line = line[:-1] +X print prefix + line X Xdef browserexec(tb, cmd): -X locals = tb.tb_frame.f_locals -X globals = tb.tb_frame.f_globals -X try: -X exec(cmd+'\n', globals, locals) -X except: -X print '*** Exception:', -X print sys.exc_type, -X if sys.exc_value <> None: -X print ':', sys.exc_value, -X print -X print 'Type help to get help.' +X locals = tb.tb_frame.f_locals +X globals = tb.tb_frame.f_globals +X try: +X exec(cmd+'\n', globals, locals) +X except: +X print '*** Exception:', +X print sys.exc_type, +X if sys.exc_value <> None: +X print ':', sys.exc_value, +X print +X print 'Type help to get help.' X Xdef browserhelp(): -X print -X print ' This is the traceback browser. Commands are:' -X print ' up : move one level up in the call stack' -X print ' down : move one level down in the call stack' -X print ' locals : print all local variables at this level' -X print ' globals : print all global variables at this level' -X print ' list : list source code around the failure' -X print ' help : print help (what you are reading now)' -X print ' quit : back to command interpreter' -X print ' Typing any other 1-line statement will execute it' -X print ' using the current level\'s symbol tables' -X print +X print +X print ' This is the traceback browser. Commands are:' +X print ' up : move one level up in the call stack' +X print ' down : move one level down in the call stack' +X print ' locals : print all local variables at this level' +X print ' globals : print all global variables at this level' +X print ' list : list source code around the failure' +X print ' help : print help (what you are reading now)' +X print ' quit : back to command interpreter' +X print ' Typing any other 1-line statement will execute it' +X print ' using the current level\'s symbol tables' +X print X Xdef printtb(tb): -X while tb: -X print1tb(tb) -X tb = tb.tb_next +X while tb: +X print1tb(tb) +X tb = tb.tb_next X Xdef print1tb(tb): -X printtbheader(tb) -X if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: -X printsymbols(tb.tb_frame.f_locals) +X printtbheader(tb) +X if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: +X printsymbols(tb.tb_frame.f_locals) X Xdef printtbheader(tb): -X filename = tb.tb_frame.f_code.co_filename -X lineno = tb.tb_lineno -X info = '"' + filename + '"(' + `lineno` + ')' -X line = readfileline(filename, lineno) -X if line: -X info = info + ': ' + string.strip(line) -X print info +X filename = tb.tb_frame.f_code.co_filename +X lineno = tb.tb_lineno +X info = '"' + filename + '"(' + `lineno` + ')' +X line = readfileline(filename, lineno) +X if line: +X info = info + ': ' + string.strip(line) +X print info X Xdef printsymbols(d): -X keys = d.keys() -X keys.sort() -X for name in keys: -X print ' ' + string.ljust(name, 12) + ':', -X printobject(d[name], 4) -X print +X keys = d.keys() +X keys.sort() +X for name in keys: +X print ' ' + string.ljust(name, 12) + ':', +X printobject(d[name], 4) +X print X Xdef printobject(v, maxlevel): -X if v = None: -X print 'None', -X elif type(v) in (type(0), type(0.0)): -X print v, -X elif type(v) = type(''): -X if len(v) > 20: -X print `v[:17] + '...'`, -X else: -X print `v`, -X elif type(v) = type(()): -X print '(', -X printlist(v, maxlevel) -X print ')', -X elif type(v) = type([]): -X print '[', -X printlist(v, maxlevel) -X print ']', -X elif type(v) = type({}): -X print '{', -X printdict(v, maxlevel) -X print '}', -X else: -X print v, +X if v = None: +X print 'None', +X elif type(v) in (type(0), type(0.0)): +X print v, +X elif type(v) = type(''): +X if len(v) > 20: +X print `v[:17] + '...'`, +X else: +X print `v`, +X elif type(v) = type(()): +X print '(', +X printlist(v, maxlevel) +X print ')', +X elif type(v) = type([]): +X print '[', +X printlist(v, maxlevel) +X print ']', +X elif type(v) = type({}): +X print '{', +X printdict(v, maxlevel) +X print '}', +X else: +X print v, X Xdef printlist(v, maxlevel): -X n = len(v) -X if n = 0: return -X if maxlevel <= 0: -X print '...', -X return -X for i in range(min(6, n)): -X printobject(v[i], maxlevel-1) -X if i+1 < n: print ',', -X if n > 6: print '...', +X n = len(v) +X if n = 0: return +X if maxlevel <= 0: +X print '...', +X return +X for i in range(min(6, n)): +X printobject(v[i], maxlevel-1) +X if i+1 < n: print ',', +X if n > 6: print '...', X Xdef printdict(v, maxlevel): -X keys = v.keys() -X n = len(keys) -X if n = 0: return -X if maxlevel <= 0: -X print '...', -X return -X keys.sort() -X for i in range(min(6, n)): -X key = keys[i] -X print `key` + ':', -X printobject(v[key], maxlevel-1) -X if i+1 < n: print ',', -X if n > 6: print '...', +X keys = v.keys() +X n = len(keys) +X if n = 0: return +X if maxlevel <= 0: +X print '...', +X return +X keys.sort() +X for i in range(min(6, n)): +X key = keys[i] +X print `key` + ':', +X printobject(v[key], maxlevel-1) +X if i+1 < n: print ',', +X if n > 6: print '...', X X_filecache = {} X Xdef readfileline(filename, lineno): -X try: -X stat = os.stat(filename) -X except os.error, msg: -X print 'Cannot stat', filename, '--', msg -X return '' -X cache_ok = 0 -X if _filecache.has_key(filename): -X cached_stat, lines = _filecache[filename] -X if stat[ST_SIZE] = cached_stat[ST_SIZE] and \ -X stat[ST_MTIME] = cached_stat[ST_MTIME]: -X cache_ok = 1 -X else: -X print 'Stale cache entry for', filename -X del _filecache[filename] -X if not cache_ok: -X lines = readfilelines(filename) -X if not lines: -X return '' -X _filecache[filename] = stat, lines -X if 0 <= lineno-1 < len(lines): -X return lines[lineno-1] -X else: -X print 'Line number out of range, last line is', len(lines) -X return '' +X try: +X stat = os.stat(filename) +X except os.error, msg: +X print 'Cannot stat', filename, '--', msg +X return '' +X cache_ok = 0 +X if _filecache.has_key(filename): +X cached_stat, lines = _filecache[filename] +X if stat[ST_SIZE] = cached_stat[ST_SIZE] and \ +X stat[ST_MTIME] = cached_stat[ST_MTIME]: +X cache_ok = 1 +X else: +X print 'Stale cache entry for', filename +X del _filecache[filename] +X if not cache_ok: +X lines = readfilelines(filename) +X if not lines: +X return '' +X _filecache[filename] = stat, lines +X if 0 <= lineno-1 < len(lines): +X return lines[lineno-1] +X else: +X print 'Line number out of range, last line is', len(lines) +X return '' X Xdef readfilelines(filename): -X try: -X fp = open(filename, 'r') -X except: -X print 'Cannot open', filename -X return [] -X lines = [] -X while 1: -X line = fp.readline() -X if not line: break -X lines.append(line) -X if not lines: -X print 'Empty file', filename -X return lines +X try: +X fp = open(filename, 'r') +X except: +X print 'Cannot open', filename +X return [] +X lines = [] +X while 1: +X line = fp.readline() +X if not line: break +X lines.append(line) +X if not lines: +X print 'Empty file', filename +X return lines EOF fi if test -s 'src/errors.c' @@ -1473,12 +1473,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1497,33 +1497,33 @@ X/* Error handling -- see also run.c */ X X/* New error handling interface. X -X The following problem exists (existed): methods of built-in modules -X are called with 'self' and 'args' arguments, but without a context -X argument, so they have no way to raise a specific exception. -X The same is true for the object implementations: no context argument. -X The old convention was to set 'errno' and to return NULL. -X The caller (usually call_function() in eval.c) detects the NULL -X return value and then calls puterrno(ctx) to turn the errno value -X into a true exception. Problems with this approach are: -X - it used standard errno values to indicate Python-specific errors, -X but this means that when such an error code is reported by a system -X call (e.g., in module posix), the user gets a confusing message -X - errno is a global variable, which makes extensions to a multi- -X threading environment difficult; e.g., in IRIX, multi-threaded -X programs must use the function oserror() instead of looking in errno -X - there is no portable way to add new error numbers for specic -X situations -- the value space for errno is reserved to the OS, yet -X the way to turn module-specific errors into a module-specific -X exception requires module-specific values for errno -X - there is no way to add a more situation-specific message to an -X error. -X -X The new interface solves all these problems. To return an error, a -X built-in function calls err_set(exception), err_setval(exception, -X value) or err_setstr(exception, string), and returns NULL. These -X functions save the value for later use by puterrno(). To adapt this -X scheme to a multi-threaded environment, only the implementation of -X err_setval() has to be changed. +X The following problem exists (existed): methods of built-in modules +X are called with 'self' and 'args' arguments, but without a context +X argument, so they have no way to raise a specific exception. +X The same is true for the object implementations: no context argument. +X The old convention was to set 'errno' and to return NULL. +X The caller (usually call_function() in eval.c) detects the NULL +X return value and then calls puterrno(ctx) to turn the errno value +X into a true exception. Problems with this approach are: +X - it used standard errno values to indicate Python-specific errors, +X but this means that when such an error code is reported by a system +X call (e.g., in module posix), the user gets a confusing message +X - errno is a global variable, which makes extensions to a multi- +X threading environment difficult; e.g., in IRIX, multi-threaded +X programs must use the function oserror() instead of looking in errno +X - there is no portable way to add new error numbers for specic +X situations -- the value space for errno is reserved to the OS, yet +X the way to turn module-specific errors into a module-specific +X exception requires module-specific values for errno +X - there is no way to add a more situation-specific message to an +X error. +X +X The new interface solves all these problems. To return an error, a +X built-in function calls err_set(exception), err_setval(exception, +X value) or err_setstr(exception, string), and returns NULL. These +X functions save the value for later use by puterrno(). To adapt this +X scheme to a multi-threaded environment, only the implementation of +X err_setval() has to be changed. X*/ X X#include "allobjects.h" @@ -1544,59 +1544,59 @@ Xstatic object *last_exc_val; X Xvoid Xerr_setval(exception, value) -X object *exception; -X object *value; +X object *exception; +X object *value; X{ -X XDECREF(last_exception); -X XINCREF(exception); -X last_exception = exception; -X -X XDECREF(last_exc_val); -X XINCREF(value); -X last_exc_val = value; +X XDECREF(last_exception); +X XINCREF(exception); +X last_exception = exception; +X +X XDECREF(last_exc_val); +X XINCREF(value); +X last_exc_val = value; X} X Xvoid Xerr_set(exception) -X object *exception; +X object *exception; X{ -X err_setval(exception, (object *)NULL); +X err_setval(exception, (object *)NULL); X} X Xvoid Xerr_setstr(exception, string) -X object *exception; -X char *string; +X object *exception; +X char *string; X{ -X object *value = newstringobject(string); -X err_setval(exception, value); -X XDECREF(value); +X object *value = newstringobject(string); +X err_setval(exception, value); +X XDECREF(value); X} X Xint Xerr_occurred() X{ -X return last_exception != NULL; +X return last_exception != NULL; X} X Xvoid Xerr_get(p_exc, p_val) -X object **p_exc; -X object **p_val; +X object **p_exc; +X object **p_val; X{ -X *p_exc = last_exception; -X last_exception = NULL; -X *p_val = last_exc_val; -X last_exc_val = NULL; +X *p_exc = last_exception; +X last_exception = NULL; +X *p_val = last_exc_val; +X last_exc_val = NULL; X} X Xvoid Xerr_clear() X{ -X XDECREF(last_exception); -X last_exception = NULL; -X XDECREF(last_exc_val); -X last_exc_val = NULL; +X XDECREF(last_exception); +X last_exception = NULL; +X XDECREF(last_exc_val); +X last_exc_val = NULL; X} X X/* Convenience functions to set a type error exception and return 0 */ @@ -1604,66 +1604,66 @@ X Xint Xerr_badarg() X{ -X err_setstr(TypeError, "illegal argument type for built-in operation"); -X return 0; +X err_setstr(TypeError, "illegal argument type for built-in operation"); +X return 0; X} X Xobject * Xerr_nomem() X{ -X err_set(MemoryError); -X return NULL; +X err_set(MemoryError); +X return NULL; X} X Xobject * Xerr_errno(exc) -X object *exc; +X object *exc; X{ -X object *v = newtupleobject(2); -X if (v != NULL) { -X settupleitem(v, 0, newintobject((long)errno)); -X settupleitem(v, 1, newstringobject(strerror(errno))); -X } -X err_setval(exc, v); -X XDECREF(v); -X return NULL; +X object *v = newtupleobject(2); +X if (v != NULL) { +X settupleitem(v, 0, newintobject((long)errno)); +X settupleitem(v, 1, newstringobject(strerror(errno))); +X } +X err_setval(exc, v); +X XDECREF(v); +X return NULL; X} X Xvoid Xerr_badcall() X{ -X err_setstr(SystemError, "bad argument to internal function"); +X err_setstr(SystemError, "bad argument to internal function"); X} X X/* Set the error appropriate to the given input error code (see errcode.h) */ X Xvoid Xerr_input(err) -X int err; +X int err; X{ -X switch (err) { -X case E_DONE: -X case E_OK: -X break; -X case E_SYNTAX: -X err_setstr(RuntimeError, "syntax error"); -X break; -X case E_TOKEN: -X err_setstr(RuntimeError, "illegal token"); -X break; -X case E_INTR: -X err_set(KeyboardInterrupt); -X break; -X case E_NOMEM: -X err_nomem(); -X break; -X case E_EOF: -X err_set(EOFError); -X break; -X default: -X err_setstr(RuntimeError, "unknown input error"); -X break; -X } +X switch (err) { +X case E_DONE: +X case E_OK: +X break; +X case E_SYNTAX: +X err_setstr(RuntimeError, "syntax error"); +X break; +X case E_TOKEN: +X err_setstr(RuntimeError, "illegal token"); +X break; +X case E_INTR: +X err_set(KeyboardInterrupt); +X break; +X case E_NOMEM: +X err_nomem(); +X break; +X case E_EOF: +X err_set(EOFError); +X break; +X default: +X err_setstr(RuntimeError, "unknown input error"); +X break; +X } X} EOF fi @@ -1676,12 +1676,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1711,74 +1711,74 @@ X#include <math.h> X Xstatic int Xgetdoublearg(args, px) -X register object *args; -X double *px; +X register object *args; +X double *px; X{ -X if (args == NULL) -X return err_badarg(); -X if (is_floatobject(args)) { -X *px = getfloatvalue(args); -X return 1; -X } -X if (is_intobject(args)) { -X *px = getintvalue(args); -X return 1; -X } -X return err_badarg(); +X if (args == NULL) +X return err_badarg(); +X if (is_floatobject(args)) { +X *px = getfloatvalue(args); +X return 1; +X } +X if (is_intobject(args)) { +X *px = getintvalue(args); +X return 1; +X } +X return err_badarg(); X} X Xstatic int Xget2doublearg(args, px, py) -X register object *args; -X double *px, *py; +X register object *args; +X double *px, *py; X{ -X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) -X return err_badarg(); -X return getdoublearg(gettupleitem(args, 0), px) && -X getdoublearg(gettupleitem(args, 1), py); +X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) +X return err_badarg(); +X return getdoublearg(gettupleitem(args, 0), px) && +X getdoublearg(gettupleitem(args, 1), py); X} X Xstatic object * Xmath_1(args, func) -X object *args; -X double (*func) FPROTO((double)); +X object *args; +X double (*func) FPROTO((double)); X{ -X double x; -X if (!getdoublearg(args, &x)) -X return NULL; -X errno = 0; -X x = (*func)(x); -X if (errno != 0) -X return NULL; -X else -X return newfloatobject(x); +X double x; +X if (!getdoublearg(args, &x)) +X return NULL; +X errno = 0; +X x = (*func)(x); +X if (errno != 0) +X return NULL; +X else +X return newfloatobject(x); X} X Xstatic object * Xmath_2(args, func) -X object *args; -X double (*func) FPROTO((double, double)); +X object *args; +X double (*func) FPROTO((double, double)); X{ -X double x, y; -X if (!get2doublearg(args, &x, &y)) -X return NULL; -X errno = 0; -X x = (*func)(x, y); -X if (errno != 0) -X return NULL; -X else -X return newfloatobject(x); +X double x, y; +X if (!get2doublearg(args, &x, &y)) +X return NULL; +X errno = 0; +X x = (*func)(x, y); +X if (errno != 0) +X return NULL; +X else +X return newfloatobject(x); X} X X#define FUNC1(stubname, func) \ -X static object * stubname(self, args) object *self, *args; { \ -X return math_1(args, func); \ -X } +X static object * stubname(self, args) object *self, *args; { \ +X return math_1(args, func); \ +X } X X#define FUNC2(stubname, func) \ -X static object * stubname(self, args) object *self, *args; { \ -X return math_2(args, func); \ -X } +X static object * stubname(self, args) object *self, *args; { \ +X return math_2(args, func); \ +X } X XFUNC1(math_acos, acos) XFUNC1(math_asin, asin) @@ -1805,52 +1805,52 @@ XFUNC1(math_tanh, tanh) X X#if 0 X/* What about these? */ -Xdouble frexp(double x, int *i); -Xdouble ldexp(double x, int n); -Xdouble modf(double x, double *i); +Xdouble frexp(double x, int *i); +Xdouble ldexp(double x, int n); +Xdouble modf(double x, double *i); X#endif X Xstatic struct methodlist math_methods[] = { -X {"acos", math_acos}, -X {"asin", math_asin}, -X {"atan", math_atan}, -X {"atan2", math_atan2}, -X {"ceil", math_ceil}, -X {"cos", math_cos}, -X {"cosh", math_cosh}, -X {"exp", math_exp}, -X {"fabs", math_fabs}, -X {"floor", math_floor}, +X {"acos", math_acos}, +X {"asin", math_asin}, +X {"atan", math_atan}, +X {"atan2", math_atan2}, +X {"ceil", math_ceil}, +X {"cos", math_cos}, +X {"cosh", math_cosh}, +X {"exp", math_exp}, +X {"fabs", math_fabs}, +X {"floor", math_floor}, X#if 0 -X {"fmod", math_fmod}, -X {"frexp", math_freqp}, -X {"ldexp", math_ldexp}, +X {"fmod", math_fmod}, +X {"frexp", math_freqp}, +X {"ldexp", math_ldexp}, X#endif -X {"log", math_log}, -X {"log10", math_log10}, +X {"log", math_log}, +X {"log10", math_log10}, X#if 0 -X {"modf", math_modf}, +X {"modf", math_modf}, X#endif -X {"pow", math_pow}, -X {"sin", math_sin}, -X {"sinh", math_sinh}, -X {"sqrt", math_sqrt}, -X {"tan", math_tan}, -X {"tanh", math_tanh}, -X {NULL, NULL} /* sentinel */ +X {"pow", math_pow}, +X {"sin", math_sin}, +X {"sinh", math_sinh}, +X {"sqrt", math_sqrt}, +X {"tan", math_tan}, +X {"tanh", math_tanh}, +X {NULL, NULL} /* sentinel */ X}; X Xvoid Xinitmath() X{ -X object *m, *d, *v; -X -X m = initmodule("math", math_methods); -X d = getmoduledict(m); -X dictinsert(d, "pi", v = newfloatobject(atan(1.0) * 4.0)); -X DECREF(v); -X dictinsert(d, "e", v = newfloatobject(exp(1.0))); -X DECREF(v); +X object *m, *d, *v; +X +X m = initmodule("math", math_methods); +X d = getmoduledict(m); +X dictinsert(d, "pi", v = newfloatobject(atan(1.0) * 4.0)); +X DECREF(v); +X dictinsert(d, "e", v = newfloatobject(exp(1.0))); +X DECREF(v); X} EOF fi @@ -1863,12 +1863,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1918,52 +1918,52 @@ Xstatic object *sysdict; X Xobject * Xsysget(name) -X char *name; +X char *name; X{ -X return dictlookup(sysdict, name); +X return dictlookup(sysdict, name); X} X XFILE * Xsysgetfile(name, def) -X char *name; -X FILE *def; +X char *name; +X FILE *def; X{ -X FILE *fp = NULL; -X object *v = sysget(name); -X if (v != NULL) -X fp = getfilefile(v); -X if (fp == NULL) -X fp = def; -X return fp; +X FILE *fp = NULL; +X object *v = sysget(name); +X if (v != NULL) +X fp = getfilefile(v); +X if (fp == NULL) +X fp = def; +X return fp; X} X Xint Xsysset(name, v) -X char *name; -X object *v; +X char *name; +X object *v; X{ -X if (v == NULL) -X return dictremove(sysdict, name); -X else -X return dictinsert(sysdict, name, v); +X if (v == NULL) +X return dictremove(sysdict, name); +X else +X return dictinsert(sysdict, name, v); X} X Xstatic object * Xsys_exit(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int sts; -X if (!getintarg(args, &sts)) -X return NULL; -X goaway(sts); -X exit(sts); /* Just in case */ -X /* NOTREACHED */ +X int sts; +X if (!getintarg(args, &sts)) +X return NULL; +X goaway(sts); +X exit(sts); /* Just in case */ +X /* NOTREACHED */ X} X Xstatic struct methodlist sys_methods[] = { -X {"exit", sys_exit}, -X {NULL, NULL} /* sentinel */ +X {"exit", sys_exit}, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object *sysin, *sysout, *syserr; @@ -1971,107 +1971,107 @@ X Xvoid Xinitsys() X{ -X object *m = initmodule("sys", sys_methods); -X sysdict = getmoduledict(m); -X INCREF(sysdict); -X /* NB keep an extra ref to the std files to avoid closing them -X when the user deletes them */ -X /* XXX File objects should have a "don't close" flag instead */ -X sysin = newopenfileobject(stdin, "<stdin>", "r"); -X sysout = newopenfileobject(stdout, "<stdout>", "w"); -X syserr = newopenfileobject(stderr, "<stderr>", "w"); -X if (err_occurred()) -X fatal("can't create sys.std* file objects"); -X dictinsert(sysdict, "stdin", sysin); -X dictinsert(sysdict, "stdout", sysout); -X dictinsert(sysdict, "stderr", syserr); -X dictinsert(sysdict, "modules", get_modules()); -X if (err_occurred()) -X fatal("can't insert sys.* objects in sys dict"); +X object *m = initmodule("sys", sys_methods); +X sysdict = getmoduledict(m); +X INCREF(sysdict); +X /* NB keep an extra ref to the std files to avoid closing them +X when the user deletes them */ +X /* XXX File objects should have a "don't close" flag instead */ +X sysin = newopenfileobject(stdin, "<stdin>", "r"); +X sysout = newopenfileobject(stdout, "<stdout>", "w"); +X syserr = newopenfileobject(stderr, "<stderr>", "w"); +X if (err_occurred()) +X fatal("can't create sys.std* file objects"); +X dictinsert(sysdict, "stdin", sysin); +X dictinsert(sysdict, "stdout", sysout); +X dictinsert(sysdict, "stderr", syserr); +X dictinsert(sysdict, "modules", get_modules()); +X if (err_occurred()) +X fatal("can't insert sys.* objects in sys dict"); X} X Xstatic object * Xmakepathobject(path, delim) -X char *path; -X int delim; +X char *path; +X int delim; X{ -X int i, n; -X char *p; -X object *v, *w; -X -X n = 1; -X p = path; -X while ((p = strchr(p, delim)) != NULL) { -X n++; -X p++; -X } -X v = newlistobject(n); -X if (v == NULL) -X return NULL; -X for (i = 0; ; i++) { -X p = strchr(path, delim); -X if (p == NULL) -X p = strchr(path, '\0'); /* End of string */ -X w = newsizedstringobject(path, (int) (p - path)); -X if (w == NULL) { -X DECREF(v); -X return NULL; -X } -X setlistitem(v, i, w); -X if (*p == '\0') -X break; -X path = p+1; -X } -X return v; +X int i, n; +X char *p; +X object *v, *w; +X +X n = 1; +X p = path; +X while ((p = strchr(p, delim)) != NULL) { +X n++; +X p++; +X } +X v = newlistobject(n); +X if (v == NULL) +X return NULL; +X for (i = 0; ; i++) { +X p = strchr(path, delim); +X if (p == NULL) +X p = strchr(path, '\0'); /* End of string */ +X w = newsizedstringobject(path, (int) (p - path)); +X if (w == NULL) { +X DECREF(v); +X return NULL; +X } +X setlistitem(v, i, w); +X if (*p == '\0') +X break; +X path = p+1; +X } +X return v; X} X Xvoid Xsetpythonpath(path) -X char *path; +X char *path; X{ -X object *v; -X if ((v = makepathobject(path, DELIM)) == NULL) -X fatal("can't create sys.path"); -X if (sysset("path", v) != 0) -X fatal("can't assign sys.path"); -X DECREF(v); +X object *v; +X if ((v = makepathobject(path, DELIM)) == NULL) +X fatal("can't create sys.path"); +X if (sysset("path", v) != 0) +X fatal("can't assign sys.path"); +X DECREF(v); X} X Xstatic object * Xmakeargvobject(argc, argv) -X int argc; -X char **argv; +X int argc; +X char **argv; X{ -X object *av; -X if (argc < 0 || argv == NULL) -X argc = 0; -X av = newlistobject(argc); -X if (av != NULL) { -X int i; -X for (i = 0; i < argc; i++) { -X object *v = newstringobject(argv[i]); -X if (v == NULL) { -X DECREF(av); -X av = NULL; -X break; -X } -X setlistitem(av, i, v); -X } -X } -X return av; +X object *av; +X if (argc < 0 || argv == NULL) +X argc = 0; +X av = newlistobject(argc); +X if (av != NULL) { +X int i; +X for (i = 0; i < argc; i++) { +X object *v = newstringobject(argv[i]); +X if (v == NULL) { +X DECREF(av); +X av = NULL; +X break; +X } +X setlistitem(av, i, v); +X } +X } +X return av; X} X Xvoid Xsetpythonargv(argc, argv) -X int argc; -X char **argv; +X int argc; +X char **argv; X{ -X object *av = makeargvobject(argc, argv); -X if (av == NULL) -X fatal("no mem for sys.argv"); -X if (sysset("argv", av) != 0) -X fatal("can't assign sys.argv"); -X DECREF(av); +X object *av = makeargvobject(argc, argv); +X if (av == NULL) +X fatal("no mem for sys.argv"); +X if (sysset("argv", av) != 0) +X fatal("can't assign sys.argv"); +X DECREF(av); X} EOF fi @@ -2084,12 +2084,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2127,46 +2127,46 @@ X/* Time methods */ X Xstatic object * Xtime_time(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X long secs; -X if (!getnoarg(args)) -X return NULL; -X secs = time((time_t *)NULL); -X return newintobject(secs); +X long secs; +X if (!getnoarg(args)) +X return NULL; +X secs = time((time_t *)NULL); +X return newintobject(secs); X} X Xstatic jmp_buf sleep_intr; X Xstatic void Xsleep_catcher(sig) -X int sig; +X int sig; X{ -X longjmp(sleep_intr, 1); +X longjmp(sleep_intr, 1); X} X Xstatic object * Xtime_sleep(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X int secs; -X SIGTYPE (*sigsave)(); -X if (!getintarg(args, &secs)) -X return NULL; -X if (setjmp(sleep_intr)) { -X signal(SIGINT, sigsave); -X err_set(KeyboardInterrupt); -X return NULL; -X } -X sigsave = signal(SIGINT, SIG_IGN); -X if (sigsave != (SIGTYPE (*)()) SIG_IGN) -X signal(SIGINT, sleep_catcher); -X sleep(secs); -X signal(SIGINT, sigsave); -X INCREF(None); -X return None; +X int secs; +X SIGTYPE (*sigsave)(); +X if (!getintarg(args, &secs)) +X return NULL; +X if (setjmp(sleep_intr)) { +X signal(SIGINT, sigsave); +X err_set(KeyboardInterrupt); +X return NULL; +X } +X sigsave = signal(SIGINT, SIG_IGN); +X if (sigsave != (SIGTYPE (*)()) SIG_IGN) +X signal(SIGINT, sleep_catcher); +X sleep(secs); +X signal(SIGINT, sigsave); +X INCREF(None); +X return None; X} X X#ifdef THINK_C @@ -2187,38 +2187,38 @@ X#ifdef DO_MILLI X Xstatic object * Xtime_millisleep(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X long msecs; -X SIGTYPE (*sigsave)(); -X if (!getlongarg(args, &msecs)) -X return NULL; -X if (setjmp(sleep_intr)) { -X signal(SIGINT, sigsave); -X err_set(KeyboardInterrupt); -X return NULL; -X } -X sigsave = signal(SIGINT, SIG_IGN); -X if (sigsave != (SIGTYPE (*)()) SIG_IGN) -X signal(SIGINT, sleep_catcher); -X millisleep(msecs); -X signal(SIGINT, sigsave); -X INCREF(None); -X return None; +X long msecs; +X SIGTYPE (*sigsave)(); +X if (!getlongarg(args, &msecs)) +X return NULL; +X if (setjmp(sleep_intr)) { +X signal(SIGINT, sigsave); +X err_set(KeyboardInterrupt); +X return NULL; +X } +X sigsave = signal(SIGINT, SIG_IGN); +X if (sigsave != (SIGTYPE (*)()) SIG_IGN) +X signal(SIGINT, sleep_catcher); +X millisleep(msecs); +X signal(SIGINT, sigsave); +X INCREF(None); +X return None; X} X Xstatic object * Xtime_millitimer(self, args) -X object *self; -X object *args; +X object *self; +X object *args; X{ -X long msecs; -X extern long millitimer(); -X if (!getnoarg(args)) -X return NULL; -X msecs = millitimer(); -X return newintobject(msecs); +X long msecs; +X extern long millitimer(); +X if (!getnoarg(args)) +X return NULL; +X msecs = millitimer(); +X return newintobject(msecs); X} X X#endif /* DO_MILLI */ @@ -2226,56 +2226,56 @@ X X Xstatic struct methodlist time_methods[] = { X#ifdef DO_MILLI -X {"millisleep", time_millisleep}, -X {"millitimer", time_millitimer}, +X {"millisleep", time_millisleep}, +X {"millitimer", time_millitimer}, X#endif /* DO_MILLI */ -X {"sleep", time_sleep}, -X {"time", time_time}, -X {NULL, NULL} /* sentinel */ +X {"sleep", time_sleep}, +X {"time", time_time}, +X {NULL, NULL} /* sentinel */ X}; X X Xvoid Xinittime() X{ -X initmodule("time", time_methods); +X initmodule("time", time_methods); X} X X X#ifdef THINK_C X -X#define MacTicks (* (long *)0x16A) +X#define MacTicks (* (long *)0x16A) X Xstatic Xsleep(msecs) -X int msecs; +X int msecs; X{ -X register long deadline; -X -X deadline = MacTicks + msecs * 60; -X while (MacTicks < deadline) { -X if (intrcheck()) -X sleep_catcher(SIGINT); -X } +X register long deadline; +X +X deadline = MacTicks + msecs * 60; +X while (MacTicks < deadline) { +X if (intrcheck()) +X sleep_catcher(SIGINT); +X } X} X Xstatic Xmillisleep(msecs) -X long msecs; +X long msecs; X{ -X register long deadline; -X -X deadline = MacTicks + msecs * 3 / 50; /* msecs * 60 / 1000 */ -X while (MacTicks < deadline) { -X if (intrcheck()) -X sleep_catcher(SIGINT); -X } +X register long deadline; +X +X deadline = MacTicks + msecs * 3 / 50; /* msecs * 60 / 1000 */ +X while (MacTicks < deadline) { +X if (intrcheck()) +X sleep_catcher(SIGINT); +X } X} X Xstatic long Xmillitimer() X{ -X return MacTicks * 50 / 3; /* MacTicks * 1000 / 60 */ +X return MacTicks * 50 / 3; /* MacTicks * 1000 / 60 */ X} X X#endif /* THINK_C */ @@ -2289,22 +2289,22 @@ X Xstatic long Xmillitimer() X{ -X struct timeval t; -X struct timezone tz; -X if (gettimeofday(&t, &tz) != 0) -X return -1; -X return t.tv_sec*1000 + t.tv_usec/1000; -X +X struct timeval t; +X struct timezone tz; +X if (gettimeofday(&t, &tz) != 0) +X return -1; +X return t.tv_sec*1000 + t.tv_usec/1000; +X X} X Xstatic Xmillisleep(msecs) -X long msecs; +X long msecs; X{ -X struct timeval t; -X t.tv_sec = msecs/1000; -X t.tv_usec = (msecs%1000)*1000; -X (void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); +X struct timeval t; +X t.tv_sec = msecs/1000; +X t.tv_usec = (msecs%1000)*1000; +X (void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); X} X X#endif /* BSD_TIME */ @@ -2320,12 +2320,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2350,190 +2350,190 @@ X#include "traceback.h" X#include "structmember.h" X Xtypedef struct _tracebackobject { -X OB_HEAD -X struct _tracebackobject *tb_next; -X frameobject *tb_frame; -X int tb_lasti; -X int tb_lineno; +X OB_HEAD +X struct _tracebackobject *tb_next; +X frameobject *tb_frame; +X int tb_lasti; +X int tb_lineno; X} tracebackobject; X X#define OFF(x) offsetof(tracebackobject, x) X Xstatic struct memberlist tb_memberlist[] = { -X {"tb_next", T_OBJECT, OFF(tb_next)}, -X {"tb_frame", T_OBJECT, OFF(tb_frame)}, -X {"tb_lasti", T_INT, OFF(tb_lasti)}, -X {"tb_lineno", T_INT, OFF(tb_lineno)}, -X {NULL} /* Sentinel */ +X {"tb_next", T_OBJECT, OFF(tb_next)}, +X {"tb_frame", T_OBJECT, OFF(tb_frame)}, +X {"tb_lasti", T_INT, OFF(tb_lasti)}, +X {"tb_lineno", T_INT, OFF(tb_lineno)}, +X {NULL} /* Sentinel */ X}; X Xstatic object * Xtb_getattr(tb, name) -X tracebackobject *tb; -X char *name; +X tracebackobject *tb; +X char *name; X{ -X return getmember((char *)tb, tb_memberlist, name); +X return getmember((char *)tb, tb_memberlist, name); X} X Xstatic void Xtb_dealloc(tb) -X tracebackobject *tb; +X tracebackobject *tb; X{ -X XDECREF(tb->tb_next); -X XDECREF(tb->tb_frame); -X DEL(tb); +X XDECREF(tb->tb_next); +X XDECREF(tb->tb_frame); +X DEL(tb); X} X Xstatic typeobject Tracebacktype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "traceback", -X sizeof(tracebackobject), -X 0, -X tb_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X tb_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "traceback", +X sizeof(tracebackobject), +X 0, +X tb_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X tb_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X X#define is_tracebackobject(v) ((v)->ob_type == &Tracebacktype) X Xstatic tracebackobject * Xnewtracebackobject(next, frame, lasti, lineno) -X tracebackobject *next; -X frameobject *frame; -X int lasti, lineno; +X tracebackobject *next; +X frameobject *frame; +X int lasti, lineno; X{ -X tracebackobject *tb; -X if ((next != NULL && !is_tracebackobject(next)) || -X frame == NULL || !is_frameobject(frame)) { -X err_badcall(); -X return NULL; -X } -X tb = NEWOBJ(tracebackobject, &Tracebacktype); -X if (tb != NULL) { -X XINCREF(next); -X tb->tb_next = next; -X XINCREF(frame); -X tb->tb_frame = frame; -X tb->tb_lasti = lasti; -X tb->tb_lineno = lineno; -X } -X return tb; +X tracebackobject *tb; +X if ((next != NULL && !is_tracebackobject(next)) || +X frame == NULL || !is_frameobject(frame)) { +X err_badcall(); +X return NULL; +X } +X tb = NEWOBJ(tracebackobject, &Tracebacktype); +X if (tb != NULL) { +X XINCREF(next); +X tb->tb_next = next; +X XINCREF(frame); +X tb->tb_frame = frame; +X tb->tb_lasti = lasti; +X tb->tb_lineno = lineno; +X } +X return tb; X} X Xstatic tracebackobject *tb_current = NULL; X Xint Xtb_here(frame, lasti, lineno) -X frameobject *frame; -X int lasti; -X int lineno; +X frameobject *frame; +X int lasti; +X int lineno; X{ -X tracebackobject *tb; -X tb = newtracebackobject(tb_current, frame, lasti, lineno); -X if (tb == NULL) -X return -1; -X XDECREF(tb_current); -X tb_current = tb; -X return 0; +X tracebackobject *tb; +X tb = newtracebackobject(tb_current, frame, lasti, lineno); +X if (tb == NULL) +X return -1; +X XDECREF(tb_current); +X tb_current = tb; +X return 0; X} X Xobject * Xtb_fetch() X{ -X object *v; -X v = (object *)tb_current; -X tb_current = NULL; -X return v; +X object *v; +X v = (object *)tb_current; +X tb_current = NULL; +X return v; X} X Xint Xtb_store(v) -X object *v; +X object *v; X{ -X if (v != NULL && !is_tracebackobject(v)) { -X err_badcall(); -X return -1; -X } -X XDECREF(tb_current); -X XINCREF(v); -X tb_current = (tracebackobject *)v; -X return 0; +X if (v != NULL && !is_tracebackobject(v)) { +X err_badcall(); +X return -1; +X } +X XDECREF(tb_current); +X XINCREF(v); +X tb_current = (tracebackobject *)v; +X return 0; X} X Xstatic void Xtb_displayline(fp, filename, lineno) -X FILE *fp; -X char *filename; -X int lineno; +X FILE *fp; +X char *filename; +X int lineno; X{ -X FILE *xfp; -X char buf[1000]; -X int i; -X if (filename[0] == '<' && filename[strlen(filename)-1] == '>') -X return; -X xfp = fopen(filename, "r"); -X if (xfp == NULL) { -X fprintf(fp, " (cannot open \"%s\")\n", filename); -X return; -X } -X for (i = 0; i < lineno; i++) { -X if (fgets(buf, sizeof buf, xfp) == NULL) -X break; -X } -X if (i == lineno) { -X char *p = buf; -X while (*p == ' ' || *p == '\t') -X p++; -X fprintf(fp, " %s", p); -X if (strchr(p, '\n') == NULL) -X fprintf(fp, "\n"); -X } -X fclose(xfp); +X FILE *xfp; +X char buf[1000]; +X int i; +X if (filename[0] == '<' && filename[strlen(filename)-1] == '>') +X return; +X xfp = fopen(filename, "r"); +X if (xfp == NULL) { +X fprintf(fp, " (cannot open \"%s\")\n", filename); +X return; +X } +X for (i = 0; i < lineno; i++) { +X if (fgets(buf, sizeof buf, xfp) == NULL) +X break; +X } +X if (i == lineno) { +X char *p = buf; +X while (*p == ' ' || *p == '\t') +X p++; +X fprintf(fp, " %s", p); +X if (strchr(p, '\n') == NULL) +X fprintf(fp, "\n"); +X } +X fclose(xfp); X} X Xstatic void Xtb_printinternal(tb, fp) -X tracebackobject *tb; -X FILE *fp; +X tracebackobject *tb; +X FILE *fp; X{ -X while (tb != NULL) { -X if (intrcheck()) { -X fprintf(fp, "[interrupted]\n"); -X break; -X } -X fprintf(fp, " File \""); -X printobject(tb->tb_frame->f_code->co_filename, fp, PRINT_RAW); -X fprintf(fp, "\", line %d\n", tb->tb_lineno); -X tb_displayline(fp, -X getstringvalue(tb->tb_frame->f_code->co_filename), -X tb->tb_lineno); -X tb = tb->tb_next; -X } +X while (tb != NULL) { +X if (intrcheck()) { +X fprintf(fp, "[interrupted]\n"); +X break; +X } +X fprintf(fp, " File \""); +X printobject(tb->tb_frame->f_code->co_filename, fp, PRINT_RAW); +X fprintf(fp, "\", line %d\n", tb->tb_lineno); +X tb_displayline(fp, +X getstringvalue(tb->tb_frame->f_code->co_filename), +X tb->tb_lineno); +X tb = tb->tb_next; +X } X} X Xint Xtb_print(v, fp) -X object *v; -X FILE *fp; +X object *v; +X FILE *fp; X{ -X if (v == NULL) -X return 0; -X if (!is_tracebackobject(v)) { -X err_badcall(); -X return -1; -X } -X sysset("last_traceback", v); -X tb_printinternal((tracebackobject *)v, fp); -X return 0; +X if (v == NULL) +X return 0; +X if (!is_tracebackobject(v)) { +X err_badcall(); +X return -1; +X } +X sysset("last_traceback", v); +X tb_printinternal((tracebackobject *)v, fp); +X return 0; X} EOF fi echo 'Part 15 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-16-21.shar b/shar/python-0.9.1-16-21.shar index dc787e0..ea4965c 100644 --- a/shar/python-0.9.1-16-21.shar +++ b/shar/python-0.9.1-16-21.shar @@ -66,7 +66,7 @@ X(y 2.5) X(h 0.36) X(downfunc move-then-resize) X) -X(pnl_radio_button (name "m4") +X(pnl_radio_button (name "m4") X(prop help creator:user-act-help) X(label "material 4") X(x 6.5) @@ -90,7 +90,7 @@ X(y 4) X(h 0.36) X(downfunc move-then-resize) X) -X(pnl_radio_button (name "m1") +X(pnl_radio_button (name "m1") X(prop help creator:user-act-help) X(label "material 1") X(x 6.5) @@ -180,12 +180,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -213,41 +213,41 @@ X X/*ARGSUSED*/ Xvoid Xinitargs(p_argc, p_argv) -X int *p_argc; -X char ***p_argv; +X int *p_argc; +X char ***p_argv; X{ X#ifdef USE_STDWIN -X extern char *getenv(); -X char *display; -X -X /* Ignore an initial argument of '-s', for backward compatibility */ -X if (*p_argc > 1 && strcmp((*p_argv)[1], "-s") == 0) { -X (*p_argv)[1] = (*p_argv)[0]; -X (*p_argc)--, (*p_argv)++; -X } -X -X /* Assume we have to initialize stdwin if either of the following -X conditions holds: -X - the environment variable $DISPLAY is set -X - there is an argument "-display" somewhere -X */ -X -X display = getenv("DISPLAY"); -X if (display != 0) -X use_stdwin = 1; -X else { -X int i; -X /* Scan through the arguments looking for "-display" */ -X for (i = 1; i < *p_argc; i++) { -X if (strcmp((*p_argv)[i], "-display") == 0) { -X use_stdwin = 1; -X break; -X } -X } -X } -X -X if (use_stdwin) -X wargs(p_argc, p_argv); +X extern char *getenv(); +X char *display; +X +X /* Ignore an initial argument of '-s', for backward compatibility */ +X if (*p_argc > 1 && strcmp((*p_argv)[1], "-s") == 0) { +X (*p_argv)[1] = (*p_argv)[0]; +X (*p_argc)--, (*p_argv)++; +X } +X +X /* Assume we have to initialize stdwin if either of the following +X conditions holds: +X - the environment variable $DISPLAY is set +X - there is an argument "-display" somewhere +X */ +X +X display = getenv("DISPLAY"); +X if (display != 0) +X use_stdwin = 1; +X else { +X int i; +X /* Scan through the arguments looking for "-display" */ +X for (i = 1; i < *p_argc; i++) { +X if (strcmp((*p_argv)[i], "-display") == 0) { +X use_stdwin = 1; +X break; +X } +X } +X } +X +X if (use_stdwin) +X wargs(p_argc, p_argv); X#endif X} X @@ -260,11 +260,11 @@ Xvoid Xdonecalls() X{ X#ifdef USE_STDWIN -X if (use_stdwin) -X wdone(); +X if (use_stdwin) +X wdone(); X#endif X#ifdef USE_AUDIO -X asa_done(); +X asa_done(); X#endif X} X @@ -272,11 +272,11 @@ X#ifdef USE_STDWIN Xstatic void Xmaybeinitstdwin() X{ -X if (use_stdwin) -X initstdwin(); -X else -X fprintf(stderr, -X "No $DISPLAY nor -display arg -- stdwin not available\n"); +X if (use_stdwin) +X initstdwin(); +X else +X fprintf(stderr, +X "No $DISPLAY nor -display arg -- stdwin not available\n"); X} X#endif X @@ -289,15 +289,15 @@ X Xchar * Xgetpythonpath() X{ -X char *path = getenv("PYTHONPATH"); -X if (path == 0) -X path = PYTHONPATH; -X return path; +X char *path = getenv("PYTHONPATH"); +X if (path == 0) +X path = PYTHONPATH; +X return path; X} X X X/* Table of built-in modules. -X These are initialized when first imported. */ +X These are initialized when first imported. */ X X/* Standard modules */ Xextern void inittime(); @@ -321,40 +321,40 @@ Xextern void maybeinitstdwin(); X#endif X Xstruct { -X char *name; -X void (*initfunc)(); +X char *name; +X void (*initfunc)(); X} inittab[] = { X -X /* Standard modules */ +X /* Standard modules */ X -X {"time", inittime}, -X {"math", initmath}, -X {"regexp", initregexp}, -X {"posix", initposix}, +X {"time", inittime}, +X {"math", initmath}, +X {"regexp", initregexp}, +X {"posix", initposix}, X X -X /* Optional modules */ +X /* Optional modules */ X X#ifdef USE_AUDIO -X {"audio", initaudio}, +X {"audio", initaudio}, X#endif X X#ifdef USE_AMOEBA -X {"amoeba", initamoeba}, +X {"amoeba", initamoeba}, X#endif X X#ifdef USE_GL -X {"gl", initgl}, +X {"gl", initgl}, X#ifdef USE_PANEL -X {"pnl", initpanel}, +X {"pnl", initpanel}, X#endif X#endif X X#ifdef USE_STDWIN -X {"stdwin", maybeinitstdwin}, +X {"stdwin", maybeinitstdwin}, X#endif X -X {0, 0} /* Sentinel */ +X {0, 0} /* Sentinel */ X}; EOF fi @@ -367,12 +367,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -399,125 +399,125 @@ X X#define OFF(x) offsetof(frameobject, x) X Xstatic struct memberlist frame_memberlist[] = { -X {"f_back", T_OBJECT, OFF(f_back)}, -X {"f_code", T_OBJECT, OFF(f_code)}, -X {"f_globals", T_OBJECT, OFF(f_globals)}, -X {"f_locals", T_OBJECT, OFF(f_locals)}, -X {NULL} /* Sentinel */ +X {"f_back", T_OBJECT, OFF(f_back)}, +X {"f_code", T_OBJECT, OFF(f_code)}, +X {"f_globals", T_OBJECT, OFF(f_globals)}, +X {"f_locals", T_OBJECT, OFF(f_locals)}, +X {NULL} /* Sentinel */ X}; X Xstatic object * Xframe_getattr(f, name) -X frameobject *f; -X char *name; +X frameobject *f; +X char *name; X{ -X return getmember((char *)f, frame_memberlist, name); +X return getmember((char *)f, frame_memberlist, name); X} X Xstatic void Xframe_dealloc(f) -X frameobject *f; +X frameobject *f; X{ -X XDECREF(f->f_back); -X XDECREF(f->f_code); -X XDECREF(f->f_globals); -X XDECREF(f->f_locals); -X XDEL(f->f_valuestack); -X XDEL(f->f_blockstack); -X DEL(f); +X XDECREF(f->f_back); +X XDECREF(f->f_code); +X XDECREF(f->f_globals); +X XDECREF(f->f_locals); +X XDEL(f->f_valuestack); +X XDEL(f->f_blockstack); +X DEL(f); X} X Xtypeobject Frametype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "frame", -X sizeof(frameobject), -X 0, -X frame_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X frame_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "frame", +X sizeof(frameobject), +X 0, +X frame_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X frame_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X Xframeobject * Xnewframeobject(back, code, globals, locals, nvalues, nblocks) -X frameobject *back; -X codeobject *code; -X object *globals; -X object *locals; -X int nvalues; -X int nblocks; +X frameobject *back; +X codeobject *code; +X object *globals; +X object *locals; +X int nvalues; +X int nblocks; X{ -X frameobject *f; -X if ((back != NULL && !is_frameobject(back)) || -X code == NULL || !is_codeobject(code) || -X globals == NULL || !is_dictobject(globals) || -X locals == NULL || !is_dictobject(locals) || -X nvalues < 0 || nblocks < 0) { -X err_badcall(); -X return NULL; -X } -X f = NEWOBJ(frameobject, &Frametype); -X if (f != NULL) { -X if (back) -X INCREF(back); -X f->f_back = back; -X INCREF(code); -X f->f_code = code; -X INCREF(globals); -X f->f_globals = globals; -X INCREF(locals); -X f->f_locals = locals; -X f->f_valuestack = NEW(object *, nvalues+1); -X f->f_blockstack = NEW(block, nblocks+1); -X f->f_nvalues = nvalues; -X f->f_nblocks = nblocks; -X f->f_iblock = 0; -X if (f->f_valuestack == NULL || f->f_blockstack == NULL) { -X err_nomem(); -X DECREF(f); -X f = NULL; -X } -X } -X return f; +X frameobject *f; +X if ((back != NULL && !is_frameobject(back)) || +X code == NULL || !is_codeobject(code) || +X globals == NULL || !is_dictobject(globals) || +X locals == NULL || !is_dictobject(locals) || +X nvalues < 0 || nblocks < 0) { +X err_badcall(); +X return NULL; +X } +X f = NEWOBJ(frameobject, &Frametype); +X if (f != NULL) { +X if (back) +X INCREF(back); +X f->f_back = back; +X INCREF(code); +X f->f_code = code; +X INCREF(globals); +X f->f_globals = globals; +X INCREF(locals); +X f->f_locals = locals; +X f->f_valuestack = NEW(object *, nvalues+1); +X f->f_blockstack = NEW(block, nblocks+1); +X f->f_nvalues = nvalues; +X f->f_nblocks = nblocks; +X f->f_iblock = 0; +X if (f->f_valuestack == NULL || f->f_blockstack == NULL) { +X err_nomem(); +X DECREF(f); +X f = NULL; +X } +X } +X return f; X} X X/* Block management */ X Xvoid Xsetup_block(f, type, handler, level) -X frameobject *f; -X int type; -X int handler; -X int level; +X frameobject *f; +X int type; +X int handler; +X int level; X{ -X block *b; -X if (f->f_iblock >= f->f_nblocks) { -X fprintf(stderr, "XXX block stack overflow\n"); -X abort(); -X } -X b = &f->f_blockstack[f->f_iblock++]; -X b->b_type = type; -X b->b_level = level; -X b->b_handler = handler; +X block *b; +X if (f->f_iblock >= f->f_nblocks) { +X fprintf(stderr, "XXX block stack overflow\n"); +X abort(); +X } +X b = &f->f_blockstack[f->f_iblock++]; +X b->b_type = type; +X b->b_level = level; +X b->b_handler = handler; X} X Xblock * Xpop_block(f) -X frameobject *f; +X frameobject *f; X{ -X block *b; -X if (f->f_iblock <= 0) { -X fprintf(stderr, "XXX block stack underflow\n"); -X abort(); -X } -X b = &f->f_blockstack[--f->f_iblock]; -X return b; +X block *b; +X if (f->f_iblock <= 0) { +X fprintf(stderr, "XXX block stack underflow\n"); +X abort(); +X } +X b = &f->f_blockstack[--f->f_iblock]; +X return b; X} EOF fi @@ -530,12 +530,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -555,152 +555,152 @@ X#include "metagrammar.h" X#include "grammar.h" X#include "pgen.h" Xstatic arc arcs_0_0[3] = { -X {2, 0}, -X {3, 0}, -X {4, 1}, +X {2, 0}, +X {3, 0}, +X {4, 1}, X}; Xstatic arc arcs_0_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic state states_0[2] = { -X {3, arcs_0_0}, -X {1, arcs_0_1}, +X {3, arcs_0_0}, +X {1, arcs_0_1}, X}; Xstatic arc arcs_1_0[1] = { -X {5, 1}, +X {5, 1}, X}; Xstatic arc arcs_1_1[1] = { -X {6, 2}, +X {6, 2}, X}; Xstatic arc arcs_1_2[1] = { -X {7, 3}, +X {7, 3}, X}; Xstatic arc arcs_1_3[1] = { -X {3, 4}, +X {3, 4}, X}; Xstatic arc arcs_1_4[1] = { -X {0, 4}, +X {0, 4}, X}; Xstatic state states_1[5] = { -X {1, arcs_1_0}, -X {1, arcs_1_1}, -X {1, arcs_1_2}, -X {1, arcs_1_3}, -X {1, arcs_1_4}, +X {1, arcs_1_0}, +X {1, arcs_1_1}, +X {1, arcs_1_2}, +X {1, arcs_1_3}, +X {1, arcs_1_4}, X}; Xstatic arc arcs_2_0[1] = { -X {8, 1}, +X {8, 1}, X}; Xstatic arc arcs_2_1[2] = { -X {9, 0}, -X {0, 1}, +X {9, 0}, +X {0, 1}, X}; Xstatic state states_2[2] = { -X {1, arcs_2_0}, -X {2, arcs_2_1}, +X {1, arcs_2_0}, +X {2, arcs_2_1}, X}; Xstatic arc arcs_3_0[1] = { -X {10, 1}, +X {10, 1}, X}; Xstatic arc arcs_3_1[2] = { -X {10, 1}, -X {0, 1}, +X {10, 1}, +X {0, 1}, X}; Xstatic state states_3[2] = { -X {1, arcs_3_0}, -X {2, arcs_3_1}, +X {1, arcs_3_0}, +X {2, arcs_3_1}, X}; Xstatic arc arcs_4_0[2] = { -X {11, 1}, -X {13, 2}, +X {11, 1}, +X {13, 2}, X}; Xstatic arc arcs_4_1[1] = { -X {7, 3}, +X {7, 3}, X}; Xstatic arc arcs_4_2[3] = { -X {14, 4}, -X {15, 4}, -X {0, 2}, +X {14, 4}, +X {15, 4}, +X {0, 2}, X}; Xstatic arc arcs_4_3[1] = { -X {12, 4}, +X {12, 4}, X}; Xstatic arc arcs_4_4[1] = { -X {0, 4}, +X {0, 4}, X}; Xstatic state states_4[5] = { -X {2, arcs_4_0}, -X {1, arcs_4_1}, -X {3, arcs_4_2}, -X {1, arcs_4_3}, -X {1, arcs_4_4}, +X {2, arcs_4_0}, +X {1, arcs_4_1}, +X {3, arcs_4_2}, +X {1, arcs_4_3}, +X {1, arcs_4_4}, X}; Xstatic arc arcs_5_0[3] = { -X {5, 1}, -X {16, 1}, -X {17, 2}, +X {5, 1}, +X {16, 1}, +X {17, 2}, X}; Xstatic arc arcs_5_1[1] = { -X {0, 1}, +X {0, 1}, X}; Xstatic arc arcs_5_2[1] = { -X {7, 3}, +X {7, 3}, X}; Xstatic arc arcs_5_3[1] = { -X {18, 1}, +X {18, 1}, X}; Xstatic state states_5[4] = { -X {3, arcs_5_0}, -X {1, arcs_5_1}, -X {1, arcs_5_2}, -X {1, arcs_5_3}, +X {3, arcs_5_0}, +X {1, arcs_5_1}, +X {1, arcs_5_2}, +X {1, arcs_5_3}, X}; Xstatic dfa dfas[6] = { -X {256, "MSTART", 0, 2, states_0, -X "\070\000\000"}, -X {257, "RULE", 0, 5, states_1, -X "\040\000\000"}, -X {258, "RHS", 0, 2, states_2, -X "\040\010\003"}, -X {259, "ALT", 0, 2, states_3, -X "\040\010\003"}, -X {260, "ITEM", 0, 5, states_4, -X "\040\010\003"}, -X {261, "ATOM", 0, 4, states_5, -X "\040\000\003"}, +X {256, "MSTART", 0, 2, states_0, +X "\070\000\000"}, +X {257, "RULE", 0, 5, states_1, +X "\040\000\000"}, +X {258, "RHS", 0, 2, states_2, +X "\040\010\003"}, +X {259, "ALT", 0, 2, states_3, +X "\040\010\003"}, +X {260, "ITEM", 0, 5, states_4, +X "\040\010\003"}, +X {261, "ATOM", 0, 4, states_5, +X "\040\000\003"}, X}; Xstatic label labels[19] = { -X {0, "EMPTY"}, -X {256, 0}, -X {257, 0}, -X {4, 0}, -X {0, 0}, -X {1, 0}, -X {11, 0}, -X {258, 0}, -X {259, 0}, -X {18, 0}, -X {260, 0}, -X {9, 0}, -X {10, 0}, -X {261, 0}, -X {16, 0}, -X {14, 0}, -X {3, 0}, -X {7, 0}, -X {8, 0}, +X {0, "EMPTY"}, +X {256, 0}, +X {257, 0}, +X {4, 0}, +X {0, 0}, +X {1, 0}, +X {11, 0}, +X {258, 0}, +X {259, 0}, +X {18, 0}, +X {260, 0}, +X {9, 0}, +X {10, 0}, +X {261, 0}, +X {16, 0}, +X {14, 0}, +X {3, 0}, +X {7, 0}, +X {8, 0}, X}; Xstatic grammar gram = { -X 6, -X dfas, -X {19, labels}, -X 256 +X 6, +X dfas, +X {19, labels}, +X 256 X}; X Xgrammar * Xmeta_grammar() X{ -X return &gram; +X return &gram; X} EOF fi @@ -713,12 +713,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -740,121 +740,121 @@ X X#include "token.h" X Xtypedef struct { -X OB_HEAD -X char *m_name; -X method m_meth; -X object *m_self; +X OB_HEAD +X char *m_name; +X method m_meth; +X object *m_self; X} methodobject; X Xobject * Xnewmethodobject(name, meth, self) -X char *name; /* static string */ -X method meth; -X object *self; +X char *name; /* static string */ +X method meth; +X object *self; X{ -X methodobject *op = NEWOBJ(methodobject, &Methodtype); -X if (op != NULL) { -X op->m_name = name; -X op->m_meth = meth; -X if (self != NULL) -X INCREF(self); -X op->m_self = self; -X } -X return (object *)op; +X methodobject *op = NEWOBJ(methodobject, &Methodtype); +X if (op != NULL) { +X op->m_name = name; +X op->m_meth = meth; +X if (self != NULL) +X INCREF(self); +X op->m_self = self; +X } +X return (object *)op; X} X Xmethod Xgetmethod(op) -X object *op; +X object *op; X{ -X if (!is_methodobject(op)) { -X err_badcall(); -X return NULL; -X } -X return ((methodobject *)op) -> m_meth; +X if (!is_methodobject(op)) { +X err_badcall(); +X return NULL; +X } +X return ((methodobject *)op) -> m_meth; X} X Xobject * Xgetself(op) -X object *op; +X object *op; X{ -X if (!is_methodobject(op)) { -X err_badcall(); -X return NULL; -X } -X return ((methodobject *)op) -> m_self; +X if (!is_methodobject(op)) { +X err_badcall(); +X return NULL; +X } +X return ((methodobject *)op) -> m_self; X} X X/* Methods (the standard built-in methods, that is) */ X Xstatic void Xmeth_dealloc(m) -X methodobject *m; +X methodobject *m; X{ -X if (m->m_self != NULL) -X DECREF(m->m_self); -X free((char *)m); +X if (m->m_self != NULL) +X DECREF(m->m_self); +X free((char *)m); X} X Xstatic void Xmeth_print(m, fp, flags) -X methodobject *m; -X FILE *fp; -X int flags; +X methodobject *m; +X FILE *fp; +X int flags; X{ -X if (m->m_self == NULL) -X fprintf(fp, "<built-in function '%s'>", m->m_name); -X else -X fprintf(fp, "<built-in method '%s' of some %s object>", -X m->m_name, m->m_self->ob_type->tp_name); +X if (m->m_self == NULL) +X fprintf(fp, "<built-in function '%s'>", m->m_name); +X else +X fprintf(fp, "<built-in method '%s' of some %s object>", +X m->m_name, m->m_self->ob_type->tp_name); X} X Xstatic object * Xmeth_repr(m) -X methodobject *m; +X methodobject *m; X{ -X char buf[200]; -X if (m->m_self == NULL) -X sprintf(buf, "<built-in function '%.80s'>", m->m_name); -X else -X sprintf(buf, -X "<built-in method '%.80s' of some %.80s object>", -X m->m_name, m->m_self->ob_type->tp_name); -X return newstringobject(buf); +X char buf[200]; +X if (m->m_self == NULL) +X sprintf(buf, "<built-in function '%.80s'>", m->m_name); +X else +X sprintf(buf, +X "<built-in method '%.80s' of some %.80s object>", +X m->m_name, m->m_self->ob_type->tp_name); +X return newstringobject(buf); X} X Xtypeobject Methodtype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "method", -X sizeof(methodobject), -X 0, -X meth_dealloc, /*tp_dealloc*/ -X meth_print, /*tp_print*/ -X 0, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X meth_repr, /*tp_repr*/ -X 0, /*tp_as_number*/ -X 0, /*tp_as_sequence*/ -X 0, /*tp_as_mapping*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "method", +X sizeof(methodobject), +X 0, +X meth_dealloc, /*tp_dealloc*/ +X meth_print, /*tp_print*/ +X 0, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X meth_repr, /*tp_repr*/ +X 0, /*tp_as_number*/ +X 0, /*tp_as_sequence*/ +X 0, /*tp_as_mapping*/ X}; X X/* Find a method in a module's method table. -X Usually called from an object's getattr method. */ +X Usually called from an object's getattr method. */ X Xobject * Xfindmethod(ml, op, name) -X struct methodlist *ml; -X object *op; -X char *name; +X struct methodlist *ml; +X object *op; +X char *name; X{ -X for (; ml->ml_name != NULL; ml++) { -X if (strcmp(name, ml->ml_name) == 0) -X return newmethodobject(ml->ml_name, ml->ml_meth, op); -X } -X err_setstr(NameError, name); -X return NULL; +X for (; ml->ml_name != NULL; ml++) { +X if (strcmp(name, ml->ml_name) == 0) +X return newmethodobject(ml->ml_name, ml->ml_meth, op); +X } +X err_setstr(NameError, name); +X return NULL; X} EOF fi @@ -867,12 +867,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -892,130 +892,130 @@ X X#include "allobjects.h" X Xtypedef struct { -X OB_HEAD -X object *md_name; -X object *md_dict; +X OB_HEAD +X object *md_name; +X object *md_dict; X} moduleobject; X Xobject * Xnewmoduleobject(name) -X char *name; +X char *name; X{ -X moduleobject *m = NEWOBJ(moduleobject, &Moduletype); -X if (m == NULL) -X return NULL; -X m->md_name = newstringobject(name); -X m->md_dict = newdictobject(); -X if (m->md_name == NULL || m->md_dict == NULL) { -X DECREF(m); -X return NULL; -X } -X return (object *)m; +X moduleobject *m = NEWOBJ(moduleobject, &Moduletype); +X if (m == NULL) +X return NULL; +X m->md_name = newstringobject(name); +X m->md_dict = newdictobject(); +X if (m->md_name == NULL || m->md_dict == NULL) { +X DECREF(m); +X return NULL; +X } +X return (object *)m; X} X Xobject * Xgetmoduledict(m) -X object *m; +X object *m; X{ -X if (!is_moduleobject(m)) { -X err_badcall(); -X return NULL; -X } -X return ((moduleobject *)m) -> md_dict; +X if (!is_moduleobject(m)) { +X err_badcall(); +X return NULL; +X } +X return ((moduleobject *)m) -> md_dict; X} X Xchar * Xgetmodulename(m) -X object *m; +X object *m; X{ -X if (!is_moduleobject(m)) { -X err_badarg(); -X return NULL; -X } -X return getstringvalue(((moduleobject *)m) -> md_name); +X if (!is_moduleobject(m)) { +X err_badarg(); +X return NULL; +X } +X return getstringvalue(((moduleobject *)m) -> md_name); X} X X/* Methods */ X Xstatic void Xmodule_dealloc(m) -X moduleobject *m; +X moduleobject *m; X{ -X if (m->md_name != NULL) -X DECREF(m->md_name); -X if (m->md_dict != NULL) -X DECREF(m->md_dict); -X free((char *)m); +X if (m->md_name != NULL) +X DECREF(m->md_name); +X if (m->md_dict != NULL) +X DECREF(m->md_dict); +X free((char *)m); X} X Xstatic void Xmodule_print(m, fp, flags) -X moduleobject *m; -X FILE *fp; -X int flags; +X moduleobject *m; +X FILE *fp; +X int flags; X{ -X fprintf(fp, "<module '%s'>", getstringvalue(m->md_name)); +X fprintf(fp, "<module '%s'>", getstringvalue(m->md_name)); X} X Xstatic object * Xmodule_repr(m) -X moduleobject *m; +X moduleobject *m; X{ -X char buf[100]; -X sprintf(buf, "<module '%.80s'>", getstringvalue(m->md_name)); -X return newstringobject(buf); +X char buf[100]; +X sprintf(buf, "<module '%.80s'>", getstringvalue(m->md_name)); +X return newstringobject(buf); X} X Xstatic object * Xmodule_getattr(m, name) -X moduleobject *m; -X char *name; +X moduleobject *m; +X char *name; X{ -X object *res; -X if (strcmp(name, "__dict__") == 0) { -X INCREF(m->md_dict); -X return m->md_dict; -X } -X if (strcmp(name, "__name__") == 0) { -X INCREF(m->md_name); -X return m->md_name; -X } -X res = dictlookup(m->md_dict, name); -X if (res == NULL) -X err_setstr(NameError, name); -X else -X INCREF(res); -X return res; +X object *res; +X if (strcmp(name, "__dict__") == 0) { +X INCREF(m->md_dict); +X return m->md_dict; +X } +X if (strcmp(name, "__name__") == 0) { +X INCREF(m->md_name); +X return m->md_name; +X } +X res = dictlookup(m->md_dict, name); +X if (res == NULL) +X err_setstr(NameError, name); +X else +X INCREF(res); +X return res; X} X Xstatic int Xmodule_setattr(m, name, v) -X moduleobject *m; -X char *name; -X object *v; +X moduleobject *m; +X char *name; +X object *v; X{ -X if (strcmp(name, "__dict__") == 0 || strcmp(name, "__name__") == 0) { -X err_setstr(NameError, "can't assign to reserved member name"); -X return -1; -X } -X if (v == NULL) -X return dictremove(m->md_dict, name); -X else -X return dictinsert(m->md_dict, name, v); +X if (strcmp(name, "__dict__") == 0 || strcmp(name, "__name__") == 0) { +X err_setstr(NameError, "can't assign to reserved member name"); +X return -1; +X } +X if (v == NULL) +X return dictremove(m->md_dict, name); +X else +X return dictinsert(m->md_dict, name, v); X} X Xtypeobject Moduletype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "module", /*tp_name*/ -X sizeof(moduleobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X module_dealloc, /*tp_dealloc*/ -X module_print, /*tp_print*/ -X module_getattr, /*tp_getattr*/ -X module_setattr, /*tp_setattr*/ -X 0, /*tp_compare*/ -X module_repr, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "module", /*tp_name*/ +X sizeof(moduleobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X module_dealloc, /*tp_dealloc*/ +X module_print, /*tp_print*/ +X module_getattr, /*tp_getattr*/ +X module_setattr, /*tp_setattr*/ +X 0, /*tp_compare*/ +X module_repr, /*tp_repr*/ X}; EOF fi @@ -1028,12 +1028,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1050,84 +1050,84 @@ X******************************************************************/ X X/* Instruction opcodes for compiled code */ X -X#define STOP_CODE 0 -X#define POP_TOP 1 -X#define ROT_TWO 2 -X#define ROT_THREE 3 -X#define DUP_TOP 4 -X -X#define UNARY_POSITIVE 10 -X#define UNARY_NEGATIVE 11 -X#define UNARY_NOT 12 -X#define UNARY_CONVERT 13 -X#define UNARY_CALL 14 -X -X#define BINARY_MULTIPLY 20 -X#define BINARY_DIVIDE 21 -X#define BINARY_MODULO 22 -X#define BINARY_ADD 23 -X#define BINARY_SUBTRACT 24 -X#define BINARY_SUBSCR 25 -X#define BINARY_CALL 26 -X -X#define SLICE 30 +X#define STOP_CODE 0 +X#define POP_TOP 1 +X#define ROT_TWO 2 +X#define ROT_THREE 3 +X#define DUP_TOP 4 +X +X#define UNARY_POSITIVE 10 +X#define UNARY_NEGATIVE 11 +X#define UNARY_NOT 12 +X#define UNARY_CONVERT 13 +X#define UNARY_CALL 14 +X +X#define BINARY_MULTIPLY 20 +X#define BINARY_DIVIDE 21 +X#define BINARY_MODULO 22 +X#define BINARY_ADD 23 +X#define BINARY_SUBTRACT 24 +X#define BINARY_SUBSCR 25 +X#define BINARY_CALL 26 +X +X#define SLICE 30 X/* Also uses 31-33 */ X -X#define STORE_SLICE 40 +X#define STORE_SLICE 40 X/* Also uses 41-43 */ X -X#define DELETE_SLICE 50 +X#define DELETE_SLICE 50 X/* Also uses 51-53 */ X -X#define STORE_SUBSCR 60 -X#define DELETE_SUBSCR 61 -X -X#define PRINT_EXPR 70 -X#define PRINT_ITEM 71 -X#define PRINT_NEWLINE 72 -X -X#define BREAK_LOOP 80 -X#define RAISE_EXCEPTION 81 -X#define LOAD_LOCALS 82 -X#define RETURN_VALUE 83 -X#define REQUIRE_ARGS 84 -X#define REFUSE_ARGS 85 -X#define BUILD_FUNCTION 86 -X#define POP_BLOCK 87 -X#define END_FINALLY 88 -X#define BUILD_CLASS 89 -X -X#define HAVE_ARGUMENT 90 /* Opcodes from here have an argument: */ -X -X#define STORE_NAME 90 /* Index in name list */ -X#define DELETE_NAME 91 /* "" */ -X#define UNPACK_TUPLE 92 /* Number of tuple items */ -X#define UNPACK_LIST 93 /* Number of list items */ -X/* unused: 94 */ -X#define STORE_ATTR 95 /* Index in name list */ -X#define DELETE_ATTR 96 /* "" */ -X -X#define LOAD_CONST 100 /* Index in const list */ -X#define LOAD_NAME 101 /* Index in name list */ -X#define BUILD_TUPLE 102 /* Number of tuple items */ -X#define BUILD_LIST 103 /* Number of list items */ -X#define BUILD_MAP 104 /* Always zero for now */ -X#define LOAD_ATTR 105 /* Index in name list */ -X#define COMPARE_OP 106 /* Comparison operator */ -X#define IMPORT_NAME 107 /* Index in name list */ -X#define IMPORT_FROM 108 /* Index in name list */ -X -X#define JUMP_FORWARD 110 /* Number of bytes to skip */ -X#define JUMP_IF_FALSE 111 /* "" */ -X#define JUMP_IF_TRUE 112 /* "" */ -X#define JUMP_ABSOLUTE 113 /* Target byte offset from beginning of code */ -X#define FOR_LOOP 114 /* Number of bytes to skip */ -X -X#define SETUP_LOOP 120 /* Target address (absolute) */ -X#define SETUP_EXCEPT 121 /* "" */ -X#define SETUP_FINALLY 122 /* "" */ -X -X#define SET_LINENO 127 /* Current line number */ +X#define STORE_SUBSCR 60 +X#define DELETE_SUBSCR 61 +X +X#define PRINT_EXPR 70 +X#define PRINT_ITEM 71 +X#define PRINT_NEWLINE 72 +X +X#define BREAK_LOOP 80 +X#define RAISE_EXCEPTION 81 +X#define LOAD_LOCALS 82 +X#define RETURN_VALUE 83 +X#define REQUIRE_ARGS 84 +X#define REFUSE_ARGS 85 +X#define BUILD_FUNCTION 86 +X#define POP_BLOCK 87 +X#define END_FINALLY 88 +X#define BUILD_CLASS 89 +X +X#define HAVE_ARGUMENT 90 /* Opcodes from here have an argument: */ +X +X#define STORE_NAME 90 /* Index in name list */ +X#define DELETE_NAME 91 /* "" */ +X#define UNPACK_TUPLE 92 /* Number of tuple items */ +X#define UNPACK_LIST 93 /* Number of list items */ +X/* unused: 94 */ +X#define STORE_ATTR 95 /* Index in name list */ +X#define DELETE_ATTR 96 /* "" */ +X +X#define LOAD_CONST 100 /* Index in const list */ +X#define LOAD_NAME 101 /* Index in name list */ +X#define BUILD_TUPLE 102 /* Number of tuple items */ +X#define BUILD_LIST 103 /* Number of list items */ +X#define BUILD_MAP 104 /* Always zero for now */ +X#define LOAD_ATTR 105 /* Index in name list */ +X#define COMPARE_OP 106 /* Comparison operator */ +X#define IMPORT_NAME 107 /* Index in name list */ +X#define IMPORT_FROM 108 /* Index in name list */ +X +X#define JUMP_FORWARD 110 /* Number of bytes to skip */ +X#define JUMP_IF_FALSE 111 /* "" */ +X#define JUMP_IF_TRUE 112 /* "" */ +X#define JUMP_ABSOLUTE 113 /* Target byte offset from beginning of code */ +X#define FOR_LOOP 114 /* Number of bytes to skip */ +X +X#define SETUP_LOOP 120 /* Target address (absolute) */ +X#define SETUP_EXCEPT 121 /* "" */ +X#define SETUP_FINALLY 122 /* "" */ +X +X#define SET_LINENO 127 /* Current line number */ X X/* Comparison operator codes (argument to COMPARE_OP) */ Xenum cmp_op {LT, LE, EQ, NE, GT, GE, IN, NOT_IN, IS, IS_NOT, EXC_MATCH, BAD}; @@ -1144,12 +1144,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1179,124 +1179,124 @@ X/* Forward */ Xstatic int parsetok PROTO((struct tok_state *, grammar *, int, node **)); X X -X/* Parse input coming from a string. Return error code, print some errors. */ +X/* Parse input coming from a string. Return error code, print some errors. */ X Xint Xparsestring(s, g, start, n_ret) -X char *s; -X grammar *g; -X int start; -X node **n_ret; +X char *s; +X grammar *g; +X int start; +X node **n_ret; X{ -X struct tok_state *tok = tok_setups(s); -X int ret; -X -X if (tok == NULL) { -X fprintf(stderr, "no mem for tok_setups\n"); -X return E_NOMEM; -X } -X ret = parsetok(tok, g, start, n_ret); -X if (ret == E_TOKEN || ret == E_SYNTAX) { -X fprintf(stderr, "String parsing error at line %d\n", -X tok->lineno); -X } -X tok_free(tok); -X return ret; +X struct tok_state *tok = tok_setups(s); +X int ret; +X +X if (tok == NULL) { +X fprintf(stderr, "no mem for tok_setups\n"); +X return E_NOMEM; +X } +X ret = parsetok(tok, g, start, n_ret); +X if (ret == E_TOKEN || ret == E_SYNTAX) { +X fprintf(stderr, "String parsing error at line %d\n", +X tok->lineno); +X } +X tok_free(tok); +X return ret; X} X X -X/* Parse input coming from a file. Return error code, print some errors. */ +X/* Parse input coming from a file. Return error code, print some errors. */ X Xint Xparsefile(fp, filename, g, start, ps1, ps2, n_ret) -X FILE *fp; -X char *filename; -X grammar *g; -X int start; -X char *ps1, *ps2; -X node **n_ret; +X FILE *fp; +X char *filename; +X grammar *g; +X int start; +X char *ps1, *ps2; +X node **n_ret; X{ -X struct tok_state *tok = tok_setupf(fp, ps1, ps2); -X int ret; -X -X if (tok == NULL) { -X fprintf(stderr, "no mem for tok_setupf\n"); -X return E_NOMEM; -X } -X ret = parsetok(tok, g, start, n_ret); -X if (ret == E_TOKEN || ret == E_SYNTAX) { -X char *p; -X fprintf(stderr, "Parsing error: file %s, line %d:\n", -X filename, tok->lineno); -X *tok->inp = '\0'; -X if (tok->inp > tok->buf && tok->inp[-1] == '\n') -X tok->inp[-1] = '\0'; -X fprintf(stderr, "%s\n", tok->buf); -X for (p = tok->buf; p < tok->cur; p++) { -X if (*p == '\t') -X putc('\t', stderr); -X else -X putc(' ', stderr); -X } -X fprintf(stderr, "^\n"); -X } -X tok_free(tok); -X return ret; +X struct tok_state *tok = tok_setupf(fp, ps1, ps2); +X int ret; +X +X if (tok == NULL) { +X fprintf(stderr, "no mem for tok_setupf\n"); +X return E_NOMEM; +X } +X ret = parsetok(tok, g, start, n_ret); +X if (ret == E_TOKEN || ret == E_SYNTAX) { +X char *p; +X fprintf(stderr, "Parsing error: file %s, line %d:\n", +X filename, tok->lineno); +X *tok->inp = '\0'; +X if (tok->inp > tok->buf && tok->inp[-1] == '\n') +X tok->inp[-1] = '\0'; +X fprintf(stderr, "%s\n", tok->buf); +X for (p = tok->buf; p < tok->cur; p++) { +X if (*p == '\t') +X putc('\t', stderr); +X else +X putc(' ', stderr); +X } +X fprintf(stderr, "^\n"); +X } +X tok_free(tok); +X return ret; X} X X X/* Parse input coming from the given tokenizer structure. -X Return error code. */ +X Return error code. */ X Xstatic int Xparsetok(tok, g, start, n_ret) -X struct tok_state *tok; -X grammar *g; -X int start; -X node **n_ret; +X struct tok_state *tok; +X grammar *g; +X int start; +X node **n_ret; X{ -X parser_state *ps; -X int ret; -X -X if ((ps = newparser(g, start)) == NULL) { -X fprintf(stderr, "no mem for new parser\n"); -X return E_NOMEM; -X } -X -X for (;;) { -X char *a, *b; -X int type; -X int len; -X char *str; -X -X type = tok_get(tok, &a, &b); -X if (type == ERRORTOKEN) { -X ret = tok->done; -X break; -X } -X len = b - a; -X str = NEW(char, len + 1); -X if (str == NULL) { -X fprintf(stderr, "no mem for next token\n"); -X ret = E_NOMEM; -X break; -X } -X strncpy(str, a, len); -X str[len] = '\0'; -X ret = addtoken(ps, (int)type, str, tok->lineno); -X if (ret != E_OK) { -X if (ret == E_DONE) { -X *n_ret = ps->p_tree; -X ps->p_tree = NULL; -X } -X else if (tok->lineno <= 1 && tok->done == E_EOF) -X ret = E_EOF; -X break; -X } -X } -X -X delparser(ps); -X return ret; +X parser_state *ps; +X int ret; +X +X if ((ps = newparser(g, start)) == NULL) { +X fprintf(stderr, "no mem for new parser\n"); +X return E_NOMEM; +X } +X +X for (;;) { +X char *a, *b; +X int type; +X int len; +X char *str; +X +X type = tok_get(tok, &a, &b); +X if (type == ERRORTOKEN) { +X ret = tok->done; +X break; +X } +X len = b - a; +X str = NEW(char, len + 1); +X if (str == NULL) { +X fprintf(stderr, "no mem for next token\n"); +X ret = E_NOMEM; +X break; +X } +X strncpy(str, a, len); +X str[len] = '\0'; +X ret = addtoken(ps, (int)type, str, tok->lineno); +X if (ret != E_OK) { +X if (ret == E_DONE) { +X *n_ret = ps->p_tree; +X ps->p_tree = NULL; +X } +X else if (tok->lineno <= 1 && tok->done == E_EOF) +X ret = E_EOF; +X break; +X } +X } +X +X delparser(ps); +X return ret; X} EOF fi @@ -1309,12 +1309,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1332,12 +1332,12 @@ X X/* Parser generator main program */ X X/* This expects a filename containing the grammar as argv[1] (UNIX) -X or asks the console for such a file name (THINK C). -X It writes its output on two files in the current directory: -X - "graminit.c" gets the grammar as a bunch of initialized data -X - "graminit.h" gets the grammar's non-terminals as #defines. -X Error messages and status info during the generation process are -X written to stdout, or sometimes to stderr. */ +X or asks the console for such a file name (THINK C). +X It writes its output on two files in the current directory: +X - "graminit.c" gets the grammar as a bunch of initialized data +X - "graminit.h" gets the grammar's non-terminals as #defines. +X Error messages and status info during the generation process are +X written to stdout, or sometimes to stderr. */ X X#include "pgenheaders.h" X#include "grammar.h" @@ -1356,102 +1356,102 @@ X#endif X Xint Xmain(argc, argv) -X int argc; -X char **argv; +X int argc; +X char **argv; X{ -X grammar *g; -X node *n; -X FILE *fp; -X char *filename; -X +X grammar *g; +X node *n; +X FILE *fp; +X char *filename; +X X#ifdef THINK_C -X filename = askfile(); +X filename = askfile(); X#else -X if (argc != 2) { -X fprintf(stderr, "usage: %s grammar\n", argv[0]); -X exit(2); -X } -X filename = argv[1]; +X if (argc != 2) { +X fprintf(stderr, "usage: %s grammar\n", argv[0]); +X exit(2); +X } +X filename = argv[1]; X#endif -X g = getgrammar(filename); -X fp = fopen("graminit.c", "w"); -X if (fp == NULL) { -X perror("graminit.c"); -X exit(1); -X } -X printf("Writing graminit.c ...\n"); -X printgrammar(g, fp); -X fclose(fp); -X fp = fopen("graminit.h", "w"); -X if (fp == NULL) { -X perror("graminit.h"); -X exit(1); -X } -X printf("Writing graminit.h ...\n"); -X printnonterminals(g, fp); -X fclose(fp); -X exit(0); +X g = getgrammar(filename); +X fp = fopen("graminit.c", "w"); +X if (fp == NULL) { +X perror("graminit.c"); +X exit(1); +X } +X printf("Writing graminit.c ...\n"); +X printgrammar(g, fp); +X fclose(fp); +X fp = fopen("graminit.h", "w"); +X if (fp == NULL) { +X perror("graminit.h"); +X exit(1); +X } +X printf("Writing graminit.h ...\n"); +X printnonterminals(g, fp); +X fclose(fp); +X exit(0); X} X Xgrammar * Xgetgrammar(filename) -X char *filename; +X char *filename; X{ -X FILE *fp; -X node *n; -X grammar *g0, *g; -X -X fp = fopen(filename, "r"); -X if (fp == NULL) { -X perror(filename); -X exit(1); -X } -X g0 = meta_grammar(); -X n = NULL; -X parsefile(fp, filename, g0, g0->g_start, (char *)NULL, (char *)NULL, &n); -X fclose(fp); -X if (n == NULL) { -X fprintf(stderr, "Parsing error.\n"); -X exit(1); -X } -X g = pgen(n); -X if (g == NULL) { -X printf("Bad grammar.\n"); -X exit(1); -X } -X return g; +X FILE *fp; +X node *n; +X grammar *g0, *g; +X +X fp = fopen(filename, "r"); +X if (fp == NULL) { +X perror(filename); +X exit(1); +X } +X g0 = meta_grammar(); +X n = NULL; +X parsefile(fp, filename, g0, g0->g_start, (char *)NULL, (char *)NULL, &n); +X fclose(fp); +X if (n == NULL) { +X fprintf(stderr, "Parsing error.\n"); +X exit(1); +X } +X g = pgen(n); +X if (g == NULL) { +X printf("Bad grammar.\n"); +X exit(1); +X } +X return g; X} X X#ifdef THINK_C Xchar * Xaskfile() X{ -X char buf[256]; -X static char name[256]; -X printf("Input file name: "); -X if (fgets(buf, sizeof buf, stdin) == NULL) { -X printf("EOF\n"); -X exit(1); -X } -X /* XXX The (unsigned char *) case is needed by THINK C 3.0 */ -X if (sscanf(/*(unsigned char *)*/buf, " %s ", name) != 1) { -X printf("No file\n"); -X exit(1); -X } -X return name; +X char buf[256]; +X static char name[256]; +X printf("Input file name: "); +X if (fgets(buf, sizeof buf, stdin) == NULL) { +X printf("EOF\n"); +X exit(1); +X } +X /* XXX The (unsigned char *) case is needed by THINK C 3.0 */ +X if (sscanf(/*(unsigned char *)*/buf, " %s ", name) != 1) { +X printf("No file\n"); +X exit(1); +X } +X return name; X} X#endif X Xvoid Xfatal(msg) -X char *msg; +X char *msg; X{ -X fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); -X exit(1); +X fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); +X exit(1); X} X X/* XXX TO DO: -X - check for duplicate definitions of names (instead of fatal err) +X - check for duplicate definitions of names (instead of fatal err) X*/ EOF fi @@ -1464,12 +1464,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1497,117 +1497,117 @@ Xstatic void printlabels PROTO((grammar *, FILE *)); X Xvoid Xprintgrammar(g, fp) -X grammar *g; -X FILE *fp; +X grammar *g; +X FILE *fp; X{ -X fprintf(fp, "#include \"pgenheaders.h\"\n"); -X fprintf(fp, "#include \"grammar.h\"\n"); -X printdfas(g, fp); -X printlabels(g, fp); -X fprintf(fp, "grammar gram = {\n"); -X fprintf(fp, "\t%d,\n", g->g_ndfas); -X fprintf(fp, "\tdfas,\n"); -X fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); -X fprintf(fp, "\t%d\n", g->g_start); -X fprintf(fp, "};\n"); +X fprintf(fp, "#include \"pgenheaders.h\"\n"); +X fprintf(fp, "#include \"grammar.h\"\n"); +X printdfas(g, fp); +X printlabels(g, fp); +X fprintf(fp, "grammar gram = {\n"); +X fprintf(fp, "\t%d,\n", g->g_ndfas); +X fprintf(fp, "\tdfas,\n"); +X fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); +X fprintf(fp, "\t%d\n", g->g_start); +X fprintf(fp, "};\n"); X} X Xvoid Xprintnonterminals(g, fp) -X grammar *g; -X FILE *fp; +X grammar *g; +X FILE *fp; X{ -X dfa *d; -X int i; -X -X d = g->g_dfa; -X for (i = g->g_ndfas; --i >= 0; d++) -X fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); +X dfa *d; +X int i; +X +X d = g->g_dfa; +X for (i = g->g_ndfas; --i >= 0; d++) +X fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); X} X Xstatic void Xprintarcs(i, d, fp) -X int i; -X dfa *d; -X FILE *fp; +X int i; +X dfa *d; +X FILE *fp; X{ -X arc *a; -X state *s; -X int j, k; -X -X s = d->d_state; -X for (j = 0; j < d->d_nstates; j++, s++) { -X fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", -X i, j, s->s_narcs); -X a = s->s_arc; -X for (k = 0; k < s->s_narcs; k++, a++) -X fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); -X fprintf(fp, "};\n"); -X } +X arc *a; +X state *s; +X int j, k; +X +X s = d->d_state; +X for (j = 0; j < d->d_nstates; j++, s++) { +X fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", +X i, j, s->s_narcs); +X a = s->s_arc; +X for (k = 0; k < s->s_narcs; k++, a++) +X fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); +X fprintf(fp, "};\n"); +X } X} X Xstatic void Xprintstates(g, fp) -X grammar *g; -X FILE *fp; +X grammar *g; +X FILE *fp; X{ -X state *s; -X dfa *d; -X int i, j; -X -X d = g->g_dfa; -X for (i = 0; i < g->g_ndfas; i++, d++) { -X printarcs(i, d, fp); -X fprintf(fp, "static state states_%d[%d] = {\n", -X i, d->d_nstates); -X s = d->d_state; -X for (j = 0; j < d->d_nstates; j++, s++) -X fprintf(fp, "\t{%d, arcs_%d_%d},\n", -X s->s_narcs, i, j); -X fprintf(fp, "};\n"); -X } +X state *s; +X dfa *d; +X int i, j; +X +X d = g->g_dfa; +X for (i = 0; i < g->g_ndfas; i++, d++) { +X printarcs(i, d, fp); +X fprintf(fp, "static state states_%d[%d] = {\n", +X i, d->d_nstates); +X s = d->d_state; +X for (j = 0; j < d->d_nstates; j++, s++) +X fprintf(fp, "\t{%d, arcs_%d_%d},\n", +X s->s_narcs, i, j); +X fprintf(fp, "};\n"); +X } X} X Xstatic void Xprintdfas(g, fp) -X grammar *g; -X FILE *fp; +X grammar *g; +X FILE *fp; X{ -X dfa *d; -X int i, j; -X -X printstates(g, fp); -X fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); -X d = g->g_dfa; -X for (i = 0; i < g->g_ndfas; i++, d++) { -X fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", -X d->d_type, d->d_name, d->d_initial, d->d_nstates, i); -X fprintf(fp, "\t \""); -X for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) -X fprintf(fp, "\\%03o", d->d_first[j] & 0xff); -X fprintf(fp, "\"},\n"); -X } -X fprintf(fp, "};\n"); +X dfa *d; +X int i, j; +X +X printstates(g, fp); +X fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); +X d = g->g_dfa; +X for (i = 0; i < g->g_ndfas; i++, d++) { +X fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", +X d->d_type, d->d_name, d->d_initial, d->d_nstates, i); +X fprintf(fp, "\t \""); +X for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) +X fprintf(fp, "\\%03o", d->d_first[j] & 0xff); +X fprintf(fp, "\"},\n"); +X } +X fprintf(fp, "};\n"); X} X Xstatic void Xprintlabels(g, fp) -X grammar *g; -X FILE *fp; +X grammar *g; +X FILE *fp; X{ -X label *l; -X int i; -X -X fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); -X l = g->g_ll.ll_label; -X for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { -X if (l->lb_str == NULL) -X fprintf(fp, "\t{%d, 0},\n", l->lb_type); -X else -X fprintf(fp, "\t{%d, \"%s\"},\n", -X l->lb_type, l->lb_str); -X } -X fprintf(fp, "};\n"); +X label *l; +X int i; +X +X fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); +X l = g->g_ll.ll_label; +X for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { +X if (l->lb_str == NULL) +X fprintf(fp, "\t{%d, 0},\n", l->lb_type); +X else +X fprintf(fp, "\t{%d, \"%s\"},\n", +X l->lb_type, l->lb_str); +X } +X fprintf(fp, "};\n"); X} EOF fi @@ -1620,12 +1620,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1643,35 +1643,35 @@ X X/* X * regsub X * -X * Copyright (c) 1986 by University of Toronto. -X * Written by Henry Spencer. Not derived from licensed software. +X * Copyright (c) 1986 by University of Toronto. +X * Written by Henry Spencer. Not derived from licensed software. X#ifdef MULTILINE -X * Changed by Guido van Rossum, CWI, Amsterdam -X * for multi-line support. +X * Changed by Guido van Rossum, CWI, Amsterdam +X * for multi-line support. X#endif X * -X * Permission is granted to anyone to use this software for any -X * purpose on any computer system, and to redistribute it freely, -X * subject to the following restrictions: +X * Permission is granted to anyone to use this software for any +X * purpose on any computer system, and to redistribute it freely, +X * subject to the following restrictions: X * -X * 1. The author is not responsible for the consequences of use of -X * this software, no matter how awful, even if they arise -X * from defects in it. +X * 1. The author is not responsible for the consequences of use of +X * this software, no matter how awful, even if they arise +X * from defects in it. X * -X * 2. The origin of this software must not be misrepresented, either -X * by explicit claim or by omission. +X * 2. The origin of this software must not be misrepresented, either +X * by explicit claim or by omission. X * -X * 3. Altered versions must be plainly marked as such, and must not -X * be misrepresented as being the original software. +X * 3. Altered versions must be plainly marked as such, and must not +X * be misrepresented as being the original software. X */ X#include <stdio.h> X#include "regexp.h" X#include "regmagic.h" X X#ifndef CHARBITS -X#define UCHARAT(p) ((int)*(unsigned char *)(p)) +X#define UCHARAT(p) ((int)*(unsigned char *)(p)) X#else -X#define UCHARAT(p) ((int)*(p)&CHARBITS) +X#define UCHARAT(p) ((int)*(p)&CHARBITS) X#endif X X/* @@ -1683,53 +1683,53 @@ Xregexp *prog; Xchar *source; Xchar *dest; X{ -X register char *src; -X register char *dst; -X register char c; -X register int no; -X register int len; -X extern char *strncpy(); -X -X if (prog == NULL || source == NULL || dest == NULL) { -X regerror("NULL parm to regsub"); -X return; -X } -X if (UCHARAT(prog->program) != MAGIC) { -X regerror("damaged regexp fed to regsub"); -X return; -X } -X -X src = source; -X dst = dest; -X while ((c = *src++) != '\0') { -X if (c == '&') -X no = 0; -X else if (c == '\\' && '0' <= *src && *src <= '9') -X no = *src++ - '0'; -X else -X no = -1; -X -X if (no < 0) { /* Ordinary character. */ -X if (c == '\\' && (*src == '\\' || *src == '&')) -X c = *src++; +X register char *src; +X register char *dst; +X register char c; +X register int no; +X register int len; +X extern char *strncpy(); +X +X if (prog == NULL || source == NULL || dest == NULL) { +X regerror("NULL parm to regsub"); +X return; +X } +X if (UCHARAT(prog->program) != MAGIC) { +X regerror("damaged regexp fed to regsub"); +X return; +X } +X +X src = source; +X dst = dest; +X while ((c = *src++) != '\0') { +X if (c == '&') +X no = 0; +X else if (c == '\\' && '0' <= *src && *src <= '9') +X no = *src++ - '0'; +X else +X no = -1; +X +X if (no < 0) { /* Ordinary character. */ +X if (c == '\\' && (*src == '\\' || *src == '&')) +X c = *src++; X#ifdef MULTILINE -X else if (c == '\\' && *src == 'n') { -X c = '\n'; -X src++; -X } +X else if (c == '\\' && *src == 'n') { +X c = '\n'; +X src++; +X } X#endif -X *dst++ = c; -X } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) { -X len = prog->endp[no] - prog->startp[no]; -X (void) strncpy(dst, prog->startp[no], len); -X dst += len; -X if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */ -X regerror("damaged match string"); -X return; -X } -X } -X } -X *dst++ = '\0'; +X *dst++ = c; +X } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) { +X len = prog->endp[no] - prog->startp[no]; +X (void) strncpy(dst, prog->startp[no], len); +X dst += len; +X if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */ +X regerror("damaged match string"); +X return; +X } +X } +X } +X *dst++ = '\0'; X} EOF fi @@ -1742,12 +1742,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1774,114 +1774,114 @@ X#include "tupleobject.h" X Xobject * Xerr_scerr(sc_errno) -X int sc_errno; +X int sc_errno; X{ -X switch(sc_errno) { -X -X case NoBufSize: -X err_setstr(StubcodeError, "Stubcode didn't start with BufSize"); -X break; -X -X case TwoBufSize: -X err_setstr(StubcodeError, "Stubcode can't have more then one BufSize"); -X break; -X -X case ElementIsNull: -X err_setstr(StubcodeError, "Trying to access an NIL object"); -X break; -X -X case StackOverflow: -X err_setstr(StubcodeError, "Stack overflow"); -X return NULL; -X -X case StackUnderflow: -X err_setstr(StubcodeError, "Stack underflow"); -X return NULL; -X -X case NoEndLoop: -X err_setstr(StubcodeError, "LoopXXX with no EndLoop"); -X return NULL; -X -X case BufferOverflow: -X err_setstr(StubcodeError, "Buffer overflow"); -X return NULL; -X -X } -X return NULL; +X switch(sc_errno) { +X +X case NoBufSize: +X err_setstr(StubcodeError, "Stubcode didn't start with BufSize"); +X break; +X +X case TwoBufSize: +X err_setstr(StubcodeError, "Stubcode can't have more then one BufSize"); +X break; +X +X case ElementIsNull: +X err_setstr(StubcodeError, "Trying to access an NIL object"); +X break; +X +X case StackOverflow: +X err_setstr(StubcodeError, "Stack overflow"); +X return NULL; +X +X case StackUnderflow: +X err_setstr(StubcodeError, "Stack underflow"); +X return NULL; +X +X case NoEndLoop: +X err_setstr(StubcodeError, "LoopXXX with no EndLoop"); +X return NULL; +X +X case BufferOverflow: +X err_setstr(StubcodeError, "Buffer overflow"); +X return NULL; +X +X } +X return NULL; X} X Xerr_scerrset(sc_errno, value, instr) -X int sc_errno; -X object *value; -X char *instr; +X int sc_errno; +X object *value; +X char *instr; X{ -X object *str, *str1, *t; -X -X if ((t = newtupleobject(3)) == NULL) { -X return -1; -X } -X if ((str = newstringobject(instr)) == NULL) { -X return -1; -X } -X if (settupleitem(t, 2, str) != 0) { -X return -1; -X } -X INCREF(value); -X if (settupleitem(t, 1, value) != 0) { -X DECREF(t); -X return -1; -X } -X switch(sc_errno) { -X -X case TypeFailure: -X if ((str1 = newstringobject("Unexpected type")) == NULL) { -X DECREF(t); -X return -1; -X } -X break; -X -X case RangeError: -X if ((str1 = newstringobject("Value out of range")) == NULL) { -X DECREF(t); -X return -1; -X } -X break; -X -X case SizeError: -X if ((str1 = newstringobject("Value doesn't have the right size")) == NULL) { -X DECREF(t); -X return -1; -X } -X break; -X -X case FlagError: -X if ((str1 = newstringobject("Illegal flag value")) == NULL) { -X DECREF(t); -X return -1; -X } -X break; -X -X case TransError: -X if ((str1 = newstringobject("hdr.h_status != 0")) == NULL) { -X DECREF(t); -X return -1; -X } -X break; -X -X default: -X if ((str1 = newstringobject("sc_errno not found")) == NULL) { -X DECREF(t); -X return -1; -X } -X break; -X } -X if (settupleitem(t, 0, str1) != 0) { -X DECREF(t); -X return -1; -X } -X err_setval(StubcodeError, t); -X DECREF(t); -X return -1; +X object *str, *str1, *t; +X +X if ((t = newtupleobject(3)) == NULL) { +X return -1; +X } +X if ((str = newstringobject(instr)) == NULL) { +X return -1; +X } +X if (settupleitem(t, 2, str) != 0) { +X return -1; +X } +X INCREF(value); +X if (settupleitem(t, 1, value) != 0) { +X DECREF(t); +X return -1; +X } +X switch(sc_errno) { +X +X case TypeFailure: +X if ((str1 = newstringobject("Unexpected type")) == NULL) { +X DECREF(t); +X return -1; +X } +X break; +X +X case RangeError: +X if ((str1 = newstringobject("Value out of range")) == NULL) { +X DECREF(t); +X return -1; +X } +X break; +X +X case SizeError: +X if ((str1 = newstringobject("Value doesn't have the right size")) == NULL) { +X DECREF(t); +X return -1; +X } +X break; +X +X case FlagError: +X if ((str1 = newstringobject("Illegal flag value")) == NULL) { +X DECREF(t); +X return -1; +X } +X break; +X +X case TransError: +X if ((str1 = newstringobject("hdr.h_status != 0")) == NULL) { +X DECREF(t); +X return -1; +X } +X break; +X +X default: +X if ((str1 = newstringobject("sc_errno not found")) == NULL) { +X DECREF(t); +X return -1; +X } +X break; +X } +X if (settupleitem(t, 0, str1) != 0) { +X DECREF(t); +X return -1; +X } +X err_setval(StubcodeError, t); +X DECREF(t); +X return -1; X} EOF fi @@ -1894,12 +1894,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1916,116 +1916,116 @@ X******************************************************************/ X X X/* -X** This file contains the data used in Ail, Python and sc2txt. +X** This file contains the data used in Ail, Python and sc2txt. X** -X** If you want to add an instuction to the instructions just define -X** it here and add the instruction in the function sc_interpreter in -X** the file sc_interpreter.c in the switch. You also have to make a -X** new function with the name x{instruction_name} in the file -X** sc_interpreter. +X** If you want to add an instuction to the instructions just define +X** it here and add the instruction in the function sc_interpreter in +X** the file sc_interpreter.c in the switch. You also have to make a +X** new function with the name x{instruction_name} in the file +X** sc_interpreter. X*/ X X/* -X** When you want to change the types of the opcode or the operand -X** you maybe need to adjust the options to mypf. And the defines : -X** SwapOpcode, SwapOperand. +X** When you want to change the types of the opcode or the operand +X** you maybe need to adjust the options to mypf. And the defines : +X** SwapOpcode, SwapOperand. X*/ X Xtypedef unsigned char TscOpcode; Xtypedef long TscOperand; X -X#define SC_MAGIC 0x19901991 +X#define SC_MAGIC 0x19901991 X -X#define SwapOpcode(x) x = x -X#define SwapOperand(l) ((l))=(((((l))>>24)&0xFF)|((((l))>>8)&0xFF00)|((((l))<<8)&0xFF0000)|((((l))<<24)&0xFF000000)) +X#define SwapOpcode(x) x = x +X#define SwapOperand(l) ((l))=(((((l))>>24)&0xFF)|((((l))>>8)&0xFF00)|((((l))<<8)&0xFF0000)|((((l))<<24)&0xFF000000)) X -X#define STKSIZE 256 +X#define STKSIZE 256 X -X#define OPERAND 0x80 -X#define FLAGS 0x40 +X#define OPERAND 0x80 +X#define FLAGS 0x40 X X/* -X** The headerfields. The value of the flag is the index of the fields -X** array from the file mhdr.c plus one +X** The headerfields. The value of the flag is the index of the fields +X** array from the file mhdr.c plus one X*/ X -X#define H_EXTRA 0x00000001 -X#define H_SIZE 0x00000002 -X#define H_OFFSET 0x00000003 -X#define H_PORT 0x00000004 -X#define H_PRIV 0x00000005 -X#define PSEUDOFIELD 0x00000006 -X#define ALL_FIELDS 0x000000ff +X#define H_EXTRA 0x00000001 +X#define H_SIZE 0x00000002 +X#define H_OFFSET 0x00000003 +X#define H_PORT 0x00000004 +X#define H_PRIV 0x00000005 +X#define PSEUDOFIELD 0x00000006 +X#define ALL_FIELDS 0x000000ff X X/* -X** The specefiers for the integers +X** The specefiers for the integers X*/ X -X#define NOSIGN 0x00000100 -X#define INT32 0x00000200 -X#define ALLTYPES 0xffffff00 +X#define NOSIGN 0x00000100 +X#define INT32 0x00000200 +X#define ALLTYPES 0xffffff00 X X/* -X** The opcode with no operand +X** The opcode with no operand X*/ X -X#define ListS 0x00 -X#define PutVS 0x01 -X#define GetVS 0x02 -X#define StringS 0x03 -X#define Equal 0x04 -X#define NoArgs 0x05 +X#define ListS 0x00 +X#define PutVS 0x01 +X#define GetVS 0x02 +X#define StringS 0x03 +X#define Equal 0x04 +X#define NoArgs 0x05 X X/* -X * Between 0x10 and 0x3f there is space for predefined marshal -X * and unmarshal functions or macros that do not have an operand +X * Between 0x10 and 0x3f there is space for predefined marshal +X * and unmarshal functions or macros that do not have an operand X */ X -X#define MarshTC 0x10 -X#define UnMarshTC 0x11 +X#define MarshTC 0x10 +X#define UnMarshTC 0x11 X X/* -X** The opcode with a number as operand +X** The opcode with a number as operand X*/ X -X#define BufSize 0x80 -X#define Trans 0x81 -X#define TTupleS 0x82 -X#define Unpack 0x83 -X#define PutFS 0x84 -X#define TStringSeq 0x85 -X#define TStringSlt 0x86 -X#define TListSeq 0x87 -X#define TListSlt 0x88 -X#define LoopPut 0x89 -X#define EndLoop 0x8a -X#define Dup 0x8b -X#define Pop 0x8c -X#define Align 0x8d -X#define Pack 0x8e -X#define LoopGet 0x8f -X#define GetFS 0x90 -X#define PushI 0x91 +X#define BufSize 0x80 +X#define Trans 0x81 +X#define TTupleS 0x82 +X#define Unpack 0x83 +X#define PutFS 0x84 +X#define TStringSeq 0x85 +X#define TStringSlt 0x86 +X#define TListSeq 0x87 +X#define TListSlt 0x88 +X#define LoopPut 0x89 +X#define EndLoop 0x8a +X#define Dup 0x8b +X#define Pop 0x8c +X#define Align 0x8d +X#define Pack 0x8e +X#define LoopGet 0x8f +X#define GetFS 0x90 +X#define PushI 0x91 X X/* -X** Between 0xa0 and 0xbf there is space for predefined marshal -X** and unmarshal functions or macros with a numberas operand +X** Between 0xa0 and 0xbf there is space for predefined marshal +X** and unmarshal functions or macros with a numberas operand X*/ X X X/* -X** The opcodes with flags as operand +X** The opcodes with flags as operand X*/ X -X#define AilWord 0xc0 -X#define PutI 0xc1 -X#define PutC 0xc2 -X#define GetI 0xc3 -X#define GetC 0xc4 +X#define AilWord 0xc0 +X#define PutI 0xc1 +X#define PutC 0xc2 +X#define GetI 0xc3 +X#define GetC 0xc4 X X/* -X** Between 0xe0 and 0xff there is space for predefined marshal -X** and unmarshal functions or macros with flags as operand +X** Between 0xe0 and 0xff there is space for predefined marshal +X** and unmarshal functions or macros with flags as operand X*/ EOF fi @@ -2038,12 +2038,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2065,7 +2065,7 @@ Xvoid xPrintNum(Num) XTscOperand Num; X{ X -X printf(" %ld",(long)Num); +X printf(" %ld",(long)Num); X} X Xvoid xPrintFlags(Flags) @@ -2073,118 +2073,118 @@ XTscOperand Flags; X{ Xlong x; X -X x = (long)Flags; -X x = x & 0x0000000F; -X if (x == H_EXTRA) printf(" h_extra"); -X if (x == H_SIZE) printf(" h_size"); -X if (x == H_OFFSET) printf(" h_offset"); -X if (x == H_PORT) printf(" h_port"); -X if (x == H_PRIV) printf(" h_priv"); -X if (x == PSEUDOFIELD) printf(" h_port and h_priv"); -X x = (long)Flags; -X if (x & NOSIGN) printf(" unsigned"); -X if (x & INT32) printf(" int32"); +X x = (long)Flags; +X x = x & 0x0000000F; +X if (x == H_EXTRA) printf(" h_extra"); +X if (x == H_SIZE) printf(" h_size"); +X if (x == H_OFFSET) printf(" h_offset"); +X if (x == H_PORT) printf(" h_port"); +X if (x == H_PRIV) printf(" h_priv"); +X if (x == PSEUDOFIELD) printf(" h_port and h_priv"); +X x = (long)Flags; +X if (x & NOSIGN) printf(" unsigned"); +X if (x & INT32) printf(" int32"); X} X Xvoid xPrintCode(Opcode) XTscOpcode Opcode; X{ X -X switch (Opcode) { -X -X case BufSize: printf("BufSize"); -X break; -X -X case Trans: printf("Trans"); -X break; -X -X case TTupleS: printf("TTupleS"); -X break; -X -X case Unpack: printf("Unpack"); -X break; -X -X case AilWord: printf("AilWord"); -X break; -X -X case ListS: printf("ListS"); -X break; -X -X case StringS: printf("StringS"); -X break; -X -X case PutFS: printf("PutFS"); -X break; -X -X case TStringSeq: printf("TStringSeq"); -X break; -X -X case TStringSlt: printf("TStringSlt"); -X break; -X -X case PutVS: printf("PutVS"); -X break; -X -X case TListSeq: printf("TListSeq"); -X break; -X -X case TListSlt: printf("TListSlt"); -X break; -X -X case LoopPut: printf("LoopPut"); -X break; -X -X case EndLoop: printf("EndLoop"); -X break; -X -X case PutI: printf("PutI"); -X break; -X -X case PutC: printf("PutC"); -X break; -X -X case Dup: printf("Dup"); -X break; -X -X case Pop: printf("Pop"); -X break; -X -X case Align: printf("Align"); -X break; -X -X case Pack: printf("Pack"); -X break; -X -X case GetVS: printf("GetVS"); -X break; -X -X case LoopGet: printf("LoopGet"); -X break; -X -X case GetFS: printf("GetFS"); -X break; -X -X case GetI: printf("GetI"); -X break; -X -X case GetC: printf("GetC"); -X break; -X -X case PushI: printf("PushI"); -X break; -X -X case MarshTC: printf("MarshTC"); -X break; -X -X case UnMarshTC: printf("UnMarshTC"); -X break; -X -X case Equal: printf("Equal"); -X break; -X -X default: printf("Unknown opcode %04x",(int)Opcode); -X break; -X } +X switch (Opcode) { +X +X case BufSize: printf("BufSize"); +X break; +X +X case Trans: printf("Trans"); +X break; +X +X case TTupleS: printf("TTupleS"); +X break; +X +X case Unpack: printf("Unpack"); +X break; +X +X case AilWord: printf("AilWord"); +X break; +X +X case ListS: printf("ListS"); +X break; +X +X case StringS: printf("StringS"); +X break; +X +X case PutFS: printf("PutFS"); +X break; +X +X case TStringSeq: printf("TStringSeq"); +X break; +X +X case TStringSlt: printf("TStringSlt"); +X break; +X +X case PutVS: printf("PutVS"); +X break; +X +X case TListSeq: printf("TListSeq"); +X break; +X +X case TListSlt: printf("TListSlt"); +X break; +X +X case LoopPut: printf("LoopPut"); +X break; +X +X case EndLoop: printf("EndLoop"); +X break; +X +X case PutI: printf("PutI"); +X break; +X +X case PutC: printf("PutC"); +X break; +X +X case Dup: printf("Dup"); +X break; +X +X case Pop: printf("Pop"); +X break; +X +X case Align: printf("Align"); +X break; +X +X case Pack: printf("Pack"); +X break; +X +X case GetVS: printf("GetVS"); +X break; +X +X case LoopGet: printf("LoopGet"); +X break; +X +X case GetFS: printf("GetFS"); +X break; +X +X case GetI: printf("GetI"); +X break; +X +X case GetC: printf("GetC"); +X break; +X +X case PushI: printf("PushI"); +X break; +X +X case MarshTC: printf("MarshTC"); +X break; +X +X case UnMarshTC: printf("UnMarshTC"); +X break; +X +X case Equal: printf("Equal"); +X break; +X +X default: printf("Unknown opcode %04x",(int)Opcode); +X break; +X } X} EOF fi @@ -2197,12 +2197,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2225,131 +2225,131 @@ X#include "structmember.h" X Xobject * Xgetmember(addr, mlist, name) -X char *addr; -X struct memberlist *mlist; -X char *name; +X char *addr; +X struct memberlist *mlist; +X char *name; X{ -X struct memberlist *l; -X -X for (l = mlist; l->name != NULL; l++) { -X if (strcmp(l->name, name) == 0) { -X object *v; -X addr += l->offset; -X switch (l->type) { -X case T_SHORT: -X v = newintobject((long) *(short*)addr); -X break; -X case T_INT: -X v = newintobject((long) *(int*)addr); -X break; -X case T_LONG: -X v = newintobject(*(long*)addr); -X break; -X case T_FLOAT: -X v = newfloatobject((double)*(float*)addr); -X break; -X case T_DOUBLE: -X v = newfloatobject(*(double*)addr); -X break; -X case T_STRING: -X if (*(char**)addr == NULL) { -X INCREF(None); -X v = None; -X } -X else -X v = newstringobject(*(char**)addr); -X break; -X case T_OBJECT: -X v = *(object **)addr; -X if (v == NULL) -X v = None; -X INCREF(v); -X break; -X default: -X err_setstr(SystemError, "bad memberlist type"); -X v = NULL; -X } -X return v; -X } -X } -X -X err_setstr(NameError, name); -X return NULL; +X struct memberlist *l; +X +X for (l = mlist; l->name != NULL; l++) { +X if (strcmp(l->name, name) == 0) { +X object *v; +X addr += l->offset; +X switch (l->type) { +X case T_SHORT: +X v = newintobject((long) *(short*)addr); +X break; +X case T_INT: +X v = newintobject((long) *(int*)addr); +X break; +X case T_LONG: +X v = newintobject(*(long*)addr); +X break; +X case T_FLOAT: +X v = newfloatobject((double)*(float*)addr); +X break; +X case T_DOUBLE: +X v = newfloatobject(*(double*)addr); +X break; +X case T_STRING: +X if (*(char**)addr == NULL) { +X INCREF(None); +X v = None; +X } +X else +X v = newstringobject(*(char**)addr); +X break; +X case T_OBJECT: +X v = *(object **)addr; +X if (v == NULL) +X v = None; +X INCREF(v); +X break; +X default: +X err_setstr(SystemError, "bad memberlist type"); +X v = NULL; +X } +X return v; +X } +X } +X +X err_setstr(NameError, name); +X return NULL; X} X Xint Xsetmember(addr, mlist, name, v) -X char *addr; -X struct memberlist *mlist; -X char *name; -X object *v; +X char *addr; +X struct memberlist *mlist; +X char *name; +X object *v; X{ -X struct memberlist *l; -X -X for (l = mlist; l->name != NULL; l++) { -X if (strcmp(l->name, name) == 0) { -X if (l->readonly || l->type == T_STRING) { -X err_setstr(RuntimeError, "readonly attribute"); -X return -1; -X } -X addr += l->offset; -X switch (l->type) { -X case T_SHORT: -X if (!is_intobject(v)) { -X err_badarg(); -X return -1; -X } -X *(short*)addr = getintvalue(v); -X break; -X case T_INT: -X if (!is_intobject(v)) { -X err_badarg(); -X return -1; -X } -X *(int*)addr = getintvalue(v); -X break; -X case T_LONG: -X if (!is_intobject(v)) { -X err_badarg(); -X return -1; -X } -X *(long*)addr = getintvalue(v); -X break; -X case T_FLOAT: -X if (is_intobject(v)) -X *(float*)addr = getintvalue(v); -X else if (is_floatobject(v)) -X *(float*)addr = getfloatvalue(v); -X else { -X err_badarg(); -X return -1; -X } -X break; -X case T_DOUBLE: -X if (is_intobject(v)) -X *(double*)addr = getintvalue(v); -X else if (is_floatobject(v)) -X *(double*)addr = getfloatvalue(v); -X else { -X err_badarg(); -X return -1; -X } -X break; -X case T_OBJECT: -X XDECREF(*(object **)addr); -X XINCREF(v); -X *(object **)addr = v; -X break; -X default: -X err_setstr(SystemError, "bad memberlist type"); -X return -1; -X } -X return 0; -X } -X } -X -X err_setstr(NameError, name); -X return -1; +X struct memberlist *l; +X +X for (l = mlist; l->name != NULL; l++) { +X if (strcmp(l->name, name) == 0) { +X if (l->readonly || l->type == T_STRING) { +X err_setstr(RuntimeError, "readonly attribute"); +X return -1; +X } +X addr += l->offset; +X switch (l->type) { +X case T_SHORT: +X if (!is_intobject(v)) { +X err_badarg(); +X return -1; +X } +X *(short*)addr = getintvalue(v); +X break; +X case T_INT: +X if (!is_intobject(v)) { +X err_badarg(); +X return -1; +X } +X *(int*)addr = getintvalue(v); +X break; +X case T_LONG: +X if (!is_intobject(v)) { +X err_badarg(); +X return -1; +X } +X *(long*)addr = getintvalue(v); +X break; +X case T_FLOAT: +X if (is_intobject(v)) +X *(float*)addr = getintvalue(v); +X else if (is_floatobject(v)) +X *(float*)addr = getfloatvalue(v); +X else { +X err_badarg(); +X return -1; +X } +X break; +X case T_DOUBLE: +X if (is_intobject(v)) +X *(double*)addr = getintvalue(v); +X else if (is_floatobject(v)) +X *(double*)addr = getfloatvalue(v); +X else { +X err_badarg(); +X return -1; +X } +X break; +X case T_OBJECT: +X XDECREF(*(object **)addr); +X XINCREF(v); +X *(object **)addr = v; +X break; +X default: +X err_setstr(SystemError, "bad memberlist type"); +X return -1; +X } +X return 0; +X } +X } +X +X err_setstr(NameError, name); +X return -1; X} EOF fi @@ -2362,12 +2362,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2383,13 +2383,13 @@ X X******************************************************************/ X X/* Use this file as a template to start implementing a new object type. -X If your objects will be called foobar, start by copying this file to -X foobarobject.c, changing all occurrences of xx to foobar and all -X occurrences of Xx by Foobar. You will probably want to delete all -X references to 'x_attr' and add your own types of attributes -X instead. Maybe you want to name your local variables other than -X 'xp'. If your object type is needed in other files, you'll have to -X create a file "foobarobject.h"; see intobject.h for an example. */ +X If your objects will be called foobar, start by copying this file to +X foobarobject.c, changing all occurrences of xx to foobar and all +X occurrences of Xx by Foobar. You will probably want to delete all +X references to 'x_attr' and add your own types of attributes +X instead. Maybe you want to name your local variables other than +X 'xp'. If your object type is needed in other files, you'll have to +X create a file "foobarobject.h"; see intobject.h for an example. */ X X X/* Xx objects */ @@ -2397,99 +2397,99 @@ X X#include "allobjects.h" X Xtypedef struct { -X OB_HEAD -X object *x_attr; /* Attributes dictionary */ +X OB_HEAD +X object *x_attr; /* Attributes dictionary */ X} xxobject; X -Xextern typeobject Xxtype; /* Really static, forward */ +Xextern typeobject Xxtype; /* Really static, forward */ X -X#define is_xxobject(v) ((v)->ob_type == &Xxtype) +X#define is_xxobject(v) ((v)->ob_type == &Xxtype) X Xstatic xxobject * Xnewxxobject(arg) -X object *arg; +X object *arg; X{ -X xxobject *xp; -X xp = NEWOBJ(xxobject, &Xxtype); -X if (xp == NULL) -X return NULL; -X xp->x_attr = NULL; -X return xp; +X xxobject *xp; +X xp = NEWOBJ(xxobject, &Xxtype); +X if (xp == NULL) +X return NULL; +X xp->x_attr = NULL; +X return xp; X} X X/* Xx methods */ X Xstatic void Xxx_dealloc(xp) -X xxobject *xp; +X xxobject *xp; X{ -X XDECREF(xp->x_attr); -X DEL(xp); +X XDECREF(xp->x_attr); +X DEL(xp); X} X Xstatic object * Xxx_demo(self, args) -X xxobject *self; -X object *args; +X xxobject *self; +X object *args; X{ -X if (!getnoarg(args)) -X return NULL; -X INCREF(None); -X return None; +X if (!getnoarg(args)) +X return NULL; +X INCREF(None); +X return None; X} X Xstatic struct methodlist xx_methods[] = { -X "demo", xx_demo, -X {NULL, NULL} /* sentinel */ +X "demo", xx_demo, +X {NULL, NULL} /* sentinel */ X}; X Xstatic object * Xxx_getattr(xp, name) -X xxobject *xp; -X char *name; +X xxobject *xp; +X char *name; X{ -X if (xp->x_attr != NULL) { -X object *v = dictlookup(xp->x_attr, name); -X if (v != NULL) { -X INCREF(v); -X return v; -X } -X } -X return findmethod(xx_methods, (object *)xp, name); +X if (xp->x_attr != NULL) { +X object *v = dictlookup(xp->x_attr, name); +X if (v != NULL) { +X INCREF(v); +X return v; +X } +X } +X return findmethod(xx_methods, (object *)xp, name); X} X Xstatic int Xxx_setattr(xp, name, v) -X xxobject *xp; -X char *name; -X object *v; +X xxobject *xp; +X char *name; +X object *v; X{ -X if (xp->x_attr == NULL) { -X xp->x_attr = newdictobject(); -X if (xp->x_attr == NULL) -X return -1; -X } -X if (v == NULL) -X return dictremove(xp->x_attr, name); -X else -X return dictinsert(xp->x_attr, name, v); +X if (xp->x_attr == NULL) { +X xp->x_attr = newdictobject(); +X if (xp->x_attr == NULL) +X return -1; +X } +X if (v == NULL) +X return dictremove(xp->x_attr, name); +X else +X return dictinsert(xp->x_attr, name, v); X} X Xstatic typeobject Xxtype = { -X OB_HEAD_INIT(&Typetype) -X 0, /*ob_size*/ -X "xx", /*tp_name*/ -X sizeof(xxobject), /*tp_size*/ -X 0, /*tp_itemsize*/ -X /* methods */ -X xx_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X xx_getattr, /*tp_getattr*/ -X xx_setattr, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /*ob_size*/ +X "xx", /*tp_name*/ +X sizeof(xxobject), /*tp_size*/ +X 0, /*tp_itemsize*/ +X /* methods */ +X xx_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X xx_getattr, /*tp_getattr*/ +X xx_setattr, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; EOF fi echo 'Part 16 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-17-21.shar b/shar/python-0.9.1-17-21.shar index 1ab184e..7e27790 100644 --- a/shar/python-0.9.1-17-21.shar +++ b/shar/python-0.9.1-17-21.shar @@ -30,153 +30,153 @@ X Xsurfknots = [-1, -1, -1, -1, 1, 1, 1, 1] X Xdef make_ctlpoints(): -X c = [] -X # -X ci = [] -X ci.append(-2.5, -3.7, 1.0) -X ci.append(-1.5, -3.7, 3.0) -X ci.append(1.5, -3.7, -2.5) -X ci.append(2.5, -3.7, -0.75) -X c.append(ci) -X # -X ci = [] -X ci.append(-2.5, -2.0, 3.0) -X ci.append(-1.5, -2.0, 4.0) -X ci.append(1.5, -2.0, -3.0) -X ci.append(2.5, -2.0, 0.0) -X c.append(ci) -X # -X ci = [] -X ci.append(-2.5, 2.0, 1.0) -X ci.append(-1.5, 2.0, 0.0) -X ci.append(1.5, 2.0, -1.0) -X ci.append(2.5, 2.0, 2.0) -X c.append(ci) -X # -X ci = [] -X ci.append(-2.5, 2.7, 1.25) -X ci.append(-1.5, 2.7, 0.1) -X ci.append(1.5, 2.7, -0.6) -X ci.append(2.5, 2.7, 0.2) -X c.append(ci) -X # -X return c +X c = [] +X # +X ci = [] +X ci.append(-2.5, -3.7, 1.0) +X ci.append(-1.5, -3.7, 3.0) +X ci.append(1.5, -3.7, -2.5) +X ci.append(2.5, -3.7, -0.75) +X c.append(ci) +X # +X ci = [] +X ci.append(-2.5, -2.0, 3.0) +X ci.append(-1.5, -2.0, 4.0) +X ci.append(1.5, -2.0, -3.0) +X ci.append(2.5, -2.0, 0.0) +X c.append(ci) +X # +X ci = [] +X ci.append(-2.5, 2.0, 1.0) +X ci.append(-1.5, 2.0, 0.0) +X ci.append(1.5, 2.0, -1.0) +X ci.append(2.5, 2.0, 2.0) +X c.append(ci) +X # +X ci = [] +X ci.append(-2.5, 2.7, 1.25) +X ci.append(-1.5, 2.7, 0.1) +X ci.append(1.5, 2.7, -0.6) +X ci.append(2.5, 2.7, 0.2) +X c.append(ci) +X # +X return c X Xctlpoints = make_ctlpoints() X -Xtrimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] +Xtrimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] X Xdef make_trimpoints(): -X c = [] -X c.append(1.0, 0.0, 1.0) -X c.append(1.0, 1.0, 1.0) -X c.append(0.0, 2.0, 2.0) -X c.append(-1.0, 1.0, 1.0) -X c.append(-1.0, 0.0, 1.0) -X c.append(-1.0, -1.0, 1.0) -X c.append(0.0, -2.0, 2.0) -X c.append(1.0, -1.0, 1.0) -X c.append(1.0, 0.0, 1.0) -X return c +X c = [] +X c.append(1.0, 0.0, 1.0) +X c.append(1.0, 1.0, 1.0) +X c.append(0.0, 2.0, 2.0) +X c.append(-1.0, 1.0, 1.0) +X c.append(-1.0, 0.0, 1.0) +X c.append(-1.0, -1.0, 1.0) +X c.append(0.0, -2.0, 2.0) +X c.append(1.0, -1.0, 1.0) +X c.append(1.0, 0.0, 1.0) +X return c X Xtrimpoints = make_trimpoints() X Xdef main(): -X init_windows() -X setup_queue() -X make_lights() -X init_view() -X # -X set_scene() -X setnurbsproperty( N_ERRORCHECKING, 1.0 ) -X setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) -X trim_flag = 0 -X draw_trim_surface(trim_flag) -X # -X while 1: -X while qtest(): -X dev, val = qread() -X if dev = ESCKEY: -X return -X elif dev = WINQUIT: -X dglclose(-1) # this for DGL only -X return -X elif dev = REDRAW: -X reshapeviewport() -X set_scene() -X draw_trim_surface(trim_flag) -X elif dev = LEFTMOUSE: -X if val: -X trim_flag = (not trim_flag) -X set_scene() -X draw_trim_surface(trim_flag) +X init_windows() +X setup_queue() +X make_lights() +X init_view() +X # +X set_scene() +X setnurbsproperty( N_ERRORCHECKING, 1.0 ) +X setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) +X trim_flag = 0 +X draw_trim_surface(trim_flag) +X # +X while 1: +X while qtest(): +X dev, val = qread() +X if dev = ESCKEY: +X return +X elif dev = WINQUIT: +X dglclose(-1) # this for DGL only +X return +X elif dev = REDRAW: +X reshapeviewport() +X set_scene() +X draw_trim_surface(trim_flag) +X elif dev = LEFTMOUSE: +X if val: +X trim_flag = (not trim_flag) +X set_scene() +X draw_trim_surface(trim_flag) X Xdef init_windows(): -X foreground() -X #prefposition(0, 500, 0, 500) -X wid = winopen('nurbs') -X wintitle('NURBS Surface') -X doublebuffer() -X RGBmode() -X gconfig() -X lsetdepth(0x000, 0x7fffff) -X zbuffer( TRUE ) +X foreground() +X #prefposition(0, 500, 0, 500) +X wid = winopen('nurbs') +X wintitle('NURBS Surface') +X doublebuffer() +X RGBmode() +X gconfig() +X lsetdepth(0x000, 0x7fffff) +X zbuffer( TRUE ) X Xdef setup_queue(): -X qdevice(ESCKEY) -X qdevice(REDRAW) -X qdevice(RIGHTMOUSE) -X qdevice(WINQUIT) -X qdevice(LEFTMOUSE) #trimming +X qdevice(ESCKEY) +X qdevice(REDRAW) +X qdevice(RIGHTMOUSE) +X qdevice(WINQUIT) +X qdevice(LEFTMOUSE) #trimming X Xdef init_view(): -X mmode(MPROJECTION) -X ortho( -4., 4., -4., 4., -4., 4. ) -X # -X mmode(MVIEWING) -X loadmatrix(idmat) -X # -X lmbind(MATERIAL, 1) +X mmode(MPROJECTION) +X ortho( -4., 4., -4., 4., -4., 4. ) +X # +X mmode(MVIEWING) +X loadmatrix(idmat) +X # +X lmbind(MATERIAL, 1) X Xdef set_scene(): -X lmbind(MATERIAL, 0) -X RGBcolor(150,150,150) -X lmbind(MATERIAL, 1) -X clear() -X zclear() -X # -X rotate( 100, 'y' ) -X rotate( 100, 'z' ) +X lmbind(MATERIAL, 0) +X RGBcolor(150,150,150) +X lmbind(MATERIAL, 1) +X clear() +X zclear() +X # +X rotate( 100, 'y' ) +X rotate( 100, 'z' ) X Xdef draw_trim_surface(trim_flag): -X bgnsurface() -X nurbssurface(surfknots, surfknots, ctlpoints, ORDER, ORDER, N_XYZ) -X if trim_flag: -X bgntrim() -X nurbscurve(trimknots, trimpoints, ORDER-1, N_STW) -X endtrim() -X endsurface() -X swapbuffers() +X bgnsurface() +X nurbssurface(surfknots, surfknots, ctlpoints, ORDER, ORDER, N_XYZ) +X if trim_flag: +X bgntrim() +X nurbscurve(trimknots, trimpoints, ORDER-1, N_STW) +X endtrim() +X endsurface() +X swapbuffers() X Xdef make_lights(): -X lmdef(DEFLMODEL,1,[]) -X lmdef(DEFLIGHT,1,[]) -X # -X # define material #1 -X # -X a = [] -X a = a + [EMISSION, 0.0, 0.0, 0.0] -X a = a + [AMBIENT, 0.1, 0.1, 0.1] -X a = a + [DIFFUSE, 0.6, 0.3, 0.3] -X a = a + [SPECULAR, 0.0, 0.6, 0.0] -X a = a + [SHININESS, 2.0] -X a = a + [LMNULL] -X lmdef(DEFMATERIAL, 1, a) -X # -X # turn on lighting -X # -X lmbind(LIGHT0, 1) -X lmbind(LMODEL, 1) +X lmdef(DEFLMODEL,1,[]) +X lmdef(DEFLIGHT,1,[]) +X # +X # define material #1 +X # +X a = [] +X a = a + [EMISSION, 0.0, 0.0, 0.0] +X a = a + [AMBIENT, 0.1, 0.1, 0.1] +X a = a + [DIFFUSE, 0.6, 0.3, 0.3] +X a = a + [SPECULAR, 0.0, 0.6, 0.0] +X a = a + [SHININESS, 2.0] +X a = a + [LMNULL] +X lmdef(DEFMATERIAL, 1, a) +X # +X # turn on lighting +X # +X lmbind(LIGHT0, 1) +X lmbind(LMODEL, 1) X Xmain() EOF @@ -189,14 +189,14 @@ echo 'x - demo/sgi/gl/zrgb.py' sed 's/^X//' > 'demo/sgi/gl/zrgb.py' << 'EOF' X#! /ufs/guido/bin/sgi/python X -X# zrgb (Requires Z buffer.) +X# zrgb (Requires Z buffer.) X# X# This program demostrates zbuffering 3 intersecting RGB polygons while -X# in doublebuffer mode where, movement of the mouse with the LEFTMOUSE +X# in doublebuffer mode where, movement of the mouse with the LEFTMOUSE X# button depressed will, rotate the 3 polygons. This is done by compound -X# rotations allowing continuous screen-oriented rotations. +X# rotations allowing continuous screen-oriented rotations. X# -X# Press the "Esc" key to exit. +X# Press the "Esc" key to exit. X Xfrom gl import * Xfrom GL import * @@ -208,115 +208,115 @@ X Xidmat=[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] X Xdef main() : -X # -X # old and new mouse position -X # -X # -X mode = 0 -X omx = 0 -X mx = 0 -X omy = 0 -X my = 0 -X # -X initialize () -X # -X draw_scene (objmat) -X # -X while (1) : -X # -X dev, val = qread() -X # -X if dev = ESCKEY : -X if val : -X break -X # exit when key is going up, not down -X # this avoids the scenario where a window -X # underneath this program's window -X # would otherwise "eat up" the up- -X # event of the Esc key being released -X return -X # -X elif dev = REDRAW : -X reshapeviewport() -X draw_scene(objmat) -X # -X elif dev = LEFTMOUSE: -X omx = mx -X omy = my -X if val : -X mode = 1 -X else : -X mode = 0 -X elif dev = MOUSEX : -X omx = mx -X mx = val -X #print omx, mx -X objmat = update_scene(objmat,mx,my,omx,omy,mode) -X # -X elif dev = MOUSEY : -X omy = my -X my = val -X #print omy, my -X objmat = update_scene(objmat,mx,my,omx,omy,mode) -X # +X # +X # old and new mouse position +X # +X # +X mode = 0 +X omx = 0 +X mx = 0 +X omy = 0 +X my = 0 +X # +X initialize () +X # +X draw_scene (objmat) +X # +X while (1) : +X # +X dev, val = qread() +X # +X if dev = ESCKEY : +X if val : +X break +X # exit when key is going up, not down +X # this avoids the scenario where a window +X # underneath this program's window +X # would otherwise "eat up" the up- +X # event of the Esc key being released +X return +X # +X elif dev = REDRAW : +X reshapeviewport() +X draw_scene(objmat) +X # +X elif dev = LEFTMOUSE: +X omx = mx +X omy = my +X if val : +X mode = 1 +X else : +X mode = 0 +X elif dev = MOUSEX : +X omx = mx +X mx = val +X #print omx, mx +X objmat = update_scene(objmat,mx,my,omx,omy,mode) +X # +X elif dev = MOUSEY : +X omy = my +X my = val +X #print omy, my +X objmat = update_scene(objmat,mx,my,omx,omy,mode) +X # X X Xdef initialize () : -X # -X foreground () -X keepaspect(5, 4) -X w = winopen('Zbuffered RGB') -X # -X doublebuffer() -X RGBmode() -X gconfig() -X zbuffer(1) -X lsetdepth(0x0, 0x7FFFFF) -X # -X qdevice(ESCKEY) -X qdevice(LEFTMOUSE) -X qdevice(MOUSEX) -X qdevice(MOUSEY) +X # +X foreground () +X keepaspect(5, 4) +X w = winopen('Zbuffered RGB') +X # +X doublebuffer() +X RGBmode() +X gconfig() +X zbuffer(1) +X lsetdepth(0x0, 0x7FFFFF) +X # +X qdevice(ESCKEY) +X qdevice(LEFTMOUSE) +X qdevice(MOUSEX) +X qdevice(MOUSEY) X Xdef update_scene (mat, mx, my, omx, omy, mode) : -X # -X if mode = 1 : -X mat = orient(mat, mx, my, omx, omy) -X draw_scene(mat) -X return mat +X # +X if mode = 1 : +X mat = orient(mat, mx, my, omx, omy) +X draw_scene(mat) +X return mat X Xdef orient (mat, mx, my, omx, omy) : -X # -X # -X pushmatrix() -X loadmatrix(idmat) -X # -X if mx - omx : rot (float (mx - omx), 'y') -X if omy - my : rot (float (omy - my), 'x') -X # -X multmatrix(mat) -X mat = getmatrix() -X # -X # -X popmatrix() -X # -X return mat +X # +X # +X pushmatrix() +X loadmatrix(idmat) +X # +X if mx - omx : rot (float (mx - omx), 'y') +X if omy - my : rot (float (omy - my), 'x') +X # +X multmatrix(mat) +X mat = getmatrix() +X # +X # +X popmatrix() +X # +X return mat X Xdef draw_scene (mat) : -X RGBcolor(40, 100, 200) -X clear() -X zclear() -X # -X perspective(400, 1.25, 30.0, 60.0) -X translate(0.0, 0.0, -40.0) -X multmatrix(mat) -X # -X # skews original view to show all polygons -X # -X rotate(-580, 'y') -X draw_polys() -X # -X swapbuffers() +X RGBcolor(40, 100, 200) +X clear() +X zclear() +X # +X perspective(400, 1.25, 30.0, 60.0) +X translate(0.0, 0.0, -40.0) +X multmatrix(mat) +X # +X # skews original view to show all polygons +X # +X rotate(-580, 'y') +X draw_polys() +X # +X swapbuffers() X Xpolygon1 = [(-10.0,-10.0,0.0),(10.0,-10.0,0.0),(-10.0,10.0,0.0)] X @@ -325,34 +325,34 @@ X Xpolygon3 = [(-10.0,6.0,4.0),(-10.0,3.0,4.0),(4.0,-9.0,-10.0),(4.0,-6.0,-10.0)] X Xdef draw_polys(): -X bgnpolygon() -X cpack(0x0) -X v3f(polygon1[0]) -X cpack(0x007F7F7F) -X v3f(polygon1[1]) -X cpack(0x00FFFFFF) -X v3f(polygon1[2]) -X endpolygon() -X # -X bgnpolygon() -X cpack(0x0000FFFF) -X v3f(polygon2[0]) -X cpack(0x007FFF00) -X v3f(polygon2[1]) -X cpack(0x00FF0000) -X v3f(polygon2[2]) -X endpolygon() -X # -X bgnpolygon() -X cpack(0x0000FFFF) -X v3f(polygon3[0]) -X cpack(0x00FF00FF) -X v3f(polygon3[1]) -X cpack(0x00FF0000) -X v3f(polygon3[2]) -X cpack(0x00FF00FF) -X v3f(polygon3[3]) -X endpolygon() +X bgnpolygon() +X cpack(0x0) +X v3f(polygon1[0]) +X cpack(0x007F7F7F) +X v3f(polygon1[1]) +X cpack(0x00FFFFFF) +X v3f(polygon1[2]) +X endpolygon() +X # +X bgnpolygon() +X cpack(0x0000FFFF) +X v3f(polygon2[0]) +X cpack(0x007FFF00) +X v3f(polygon2[1]) +X cpack(0x00FF0000) +X v3f(polygon2[2]) +X endpolygon() +X # +X bgnpolygon() +X cpack(0x0000FFFF) +X v3f(polygon3[0]) +X cpack(0x00FF00FF) +X v3f(polygon3[1]) +X cpack(0x00FF0000) +X v3f(polygon3[2]) +X cpack(0x00FF00FF) +X v3f(polygon3[3]) +X endpolygon() X X Xmain () @@ -520,143 +520,143 @@ X X# first try - brute force method (ala M.Overmars...) X Xdef makespinobject (smooth,rot,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2) : -X object = [] -X dth = 2.0 * pi / float (rot) -X for i in range (0, n) : -X for j in range (0, rot) : -X th = dth * float (j) -X # -X if smooth = 1: -X a1 = th -X a2 =th+dth -X else : -X a1 = th + dth / 2.0 -X a2 = th + dth / 2.0 -X # -X v0 = (x1[i]*sin(th),x1[i]*cos(th),z1[i]) -X n0 = (nx1[i]*sin(a1),nx1[i]*cos(a1),nz1[i]) -X # -X v1 = (x1[i]*sin(th+dth),x1[i]*cos(th+dth),z1[i]) -X n1 = (nx1[i]*sin(a2), nx1[i]*cos(a2), nz1[i]) -X # -X v2 = (x2[i]*sin(th+dth),x2[i]*cos(th+dth),z2[i]) -X n2 = (nx2[i]*sin(a2), nx2[i]*cos(a2), nz2[i]) -X # -X v3 = (x2[i]*sin(th), x2[i]*cos(th), z2[i]) -X n3 = (nx2[i]*sin(a1), nx2[i]*cos(a1), nz2[i]) -X # -X patch = ((v0,n0), (v1,n1), (v2,n2), (v3,n3)) -X #patch = ((n0,v0), (n1,v1), (n2,v2), (n3,v3)) -X # -X if x1[i] < FUZZY : -X patch = patch[1:] -X # -X object.append (patch) -X # -X return object +X object = [] +X dth = 2.0 * pi / float (rot) +X for i in range (0, n) : +X for j in range (0, rot) : +X th = dth * float (j) +X # +X if smooth = 1: +X a1 = th +X a2 =th+dth +X else : +X a1 = th + dth / 2.0 +X a2 = th + dth / 2.0 +X # +X v0 = (x1[i]*sin(th),x1[i]*cos(th),z1[i]) +X n0 = (nx1[i]*sin(a1),nx1[i]*cos(a1),nz1[i]) +X # +X v1 = (x1[i]*sin(th+dth),x1[i]*cos(th+dth),z1[i]) +X n1 = (nx1[i]*sin(a2), nx1[i]*cos(a2), nz1[i]) +X # +X v2 = (x2[i]*sin(th+dth),x2[i]*cos(th+dth),z2[i]) +X n2 = (nx2[i]*sin(a2), nx2[i]*cos(a2), nz2[i]) +X # +X v3 = (x2[i]*sin(th), x2[i]*cos(th), z2[i]) +X n3 = (nx2[i]*sin(a1), nx2[i]*cos(a1), nz2[i]) +X # +X patch = ((v0,n0), (v1,n1), (v2,n2), (v3,n3)) +X #patch = ((n0,v0), (n1,v1), (n2,v2), (n3,v3)) +X # +X if x1[i] < FUZZY : +X patch = patch[1:] +X # +X object.append (patch) +X # +X return object X Xdef makesphere (n): -X asin = [] -X acos = [] -X for i in range (0, n-1): -X asin.append (sin((pi/float (n))*(1.0+float (i)))) -X acos.append(cos((pi/float (n))*(1.0+float (i)))) -X # -X x1 = [0.0] + asin -X z1 = [1.0] + acos -X nx1 = [0.0] + asin -X nz1 = [1.0] + acos -X # -X x2 = asin + [0.0] -X z2 = acos + [-1.0] -X nx2 = asin + [0.0] -X nz2 = acos + [-1.0] -X # -X return makespinobject (1,2*n,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2) +X asin = [] +X acos = [] +X for i in range (0, n-1): +X asin.append (sin((pi/float (n))*(1.0+float (i)))) +X acos.append(cos((pi/float (n))*(1.0+float (i)))) +X # +X x1 = [0.0] + asin +X z1 = [1.0] + acos +X nx1 = [0.0] + asin +X nz1 = [1.0] + acos +X # +X x2 = asin + [0.0] +X z2 = acos + [-1.0] +X nx2 = asin + [0.0] +X nz2 = acos + [-1.0] +X # +X return makespinobject (1,2*n,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2) X Xdef makecylinder(n) : -X x1 = [0.0, 1.0, 1.0] -X nx1 = [0.0, 1.0, 0.0] -X z1 = [1.0, 1.0, -1.0] -X nz1 = [1.0, 0.0, -1.0] -X # -X z2 = [1.0, -1.0, -1.0] -X nz2 = [1.0, 0.0, -1.0] -X x2 = [1.0, 1.0, 0.0] -X nx2 = [0.0, 1.0, 0.0] -X # -X return makespinobject(1,2*n,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) +X x1 = [0.0, 1.0, 1.0] +X nx1 = [0.0, 1.0, 0.0] +X z1 = [1.0, 1.0, -1.0] +X nz1 = [1.0, 0.0, -1.0] +X # +X z2 = [1.0, -1.0, -1.0] +X nz2 = [1.0, 0.0, -1.0] +X x2 = [1.0, 1.0, 0.0] +X nx2 = [0.0, 1.0, 0.0] +X # +X return makespinobject(1,2*n,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) X Xdef makecone(n) : -X x1 = [0.0, 1.0, 1.0] -X nx1 = [2.0/sqrt(5.0), 0.0, 0.0] -X z1 = [1.0, -1.0, -1.0] -X nz1 = [1.0/sqrt(5.0), -1.0, -1.0] -X # -X x2 = [1.0, 0.0, 0.0] -X nx2 = [2.0/sqrt(5.0), 0.0, 0.0] -X nz2 = [1.0/sqrt(5.0), -1.0, -1.0] -X z2 = [-1.0, -1.0, -1.0] -X # -X return makespinobject(1,2*n,2,x1,z1,nx1,nz1,x2,z2,nx2,nz2) +X x1 = [0.0, 1.0, 1.0] +X nx1 = [2.0/sqrt(5.0), 0.0, 0.0] +X z1 = [1.0, -1.0, -1.0] +X nz1 = [1.0/sqrt(5.0), -1.0, -1.0] +X # +X x2 = [1.0, 0.0, 0.0] +X nx2 = [2.0/sqrt(5.0), 0.0, 0.0] +X nz2 = [1.0/sqrt(5.0), -1.0, -1.0] +X z2 = [-1.0, -1.0, -1.0] +X # +X return makespinobject(1,2*n,2,x1,z1,nx1,nz1,x2,z2,nx2,nz2) X Xdef makecube() : -X x1 = [0.0, sqrt(2.0), sqrt (2.0)] -X nx1 = [0.0, 1.0, 0.0] -X z1 = [1.0, 1.0, -1.0] -X nz1 = [1.0, 0.0, -1.0] -X # -X x2 = [sqrt(2.0), sqrt(2.0), 0.0] -X nx2 = [0.0, 1.0, 0.0] -X z2 = [1.0, -1.0, -1.0] -X nz2 = [1.0, 0.0, -1.0] -X # -X return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) +X x1 = [0.0, sqrt(2.0), sqrt (2.0)] +X nx1 = [0.0, 1.0, 0.0] +X z1 = [1.0, 1.0, -1.0] +X nz1 = [1.0, 0.0, -1.0] +X # +X x2 = [sqrt(2.0), sqrt(2.0), 0.0] +X nx2 = [0.0, 1.0, 0.0] +X z2 = [1.0, -1.0, -1.0] +X nz2 = [1.0, 0.0, -1.0] +X # +X return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) X X Xdef makepyramid() : -X x1 = [0.0, sqrt(2.0), 0.0] -X nx1 = [2.0 / sqrt(5.0), 0.0, 0.0] -X z1 = [1.0, -1.0, 0.0] -X nz1 = [1.0 / sqrt(5.0), -1.0, 0.0] -X # -X x2 = [sqrt(2.0), 0.0, 0.0] -X nx2 = [2.0 / sqrt(5.0), 0.0, 0.0] -X z2 = [-1.0, -1.0, -1.0] -X nz2 = [1.0/sqrt(5.0), -1.0, 0.0] -X # -X return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) +X x1 = [0.0, sqrt(2.0), 0.0] +X nx1 = [2.0 / sqrt(5.0), 0.0, 0.0] +X z1 = [1.0, -1.0, 0.0] +X nz1 = [1.0 / sqrt(5.0), -1.0, 0.0] +X # +X x2 = [sqrt(2.0), 0.0, 0.0] +X nx2 = [2.0 / sqrt(5.0), 0.0, 0.0] +X z2 = [-1.0, -1.0, -1.0] +X nz2 = [1.0/sqrt(5.0), -1.0, 0.0] +X # +X return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2) X Xdef makeobjects () : -X cube = makecube() -X sphere = makesphere (6) -X cylinder = makecylinder (6) -X cone = makecone (6) -X pyramid = makepyramid () -X # -X odict = {} -X odict ['cube'] = cube -X odict ['pyramid'] = pyramid -X odict ['sphere'] = sphere -X odict ['cylinder'] = cylinder -X odict ['cone'] = cone -X odict ['diamond'] = cube -X odict ['disk'] = sphere -X # -X return odict +X cube = makecube() +X sphere = makesphere (6) +X cylinder = makecylinder (6) +X cone = makecone (6) +X pyramid = makepyramid () +X # +X odict = {} +X odict ['cube'] = cube +X odict ['pyramid'] = pyramid +X odict ['sphere'] = sphere +X odict ['cylinder'] = cylinder +X odict ['cone'] = cone +X odict ['diamond'] = cube +X odict ['disk'] = sphere +X # +X return odict X X Xrenderfuncs = [bgnpolygon, endpolygon] X Xdef putFunc (funcs) : -X renderfuncs [:] = funcs +X renderfuncs [:] = funcs X Xdef drawobject (obj) : -X # -X for patch in obj : -X renderfuncs[0] () -X vnarray (patch) -X renderfuncs[1] () +X # +X for patch in obj : +X renderfuncs[0] () +X vnarray (patch) +X renderfuncs[1] () X EOF fi @@ -670,117 +670,117 @@ X# Use as a base class for other splits. X# Derived classes should at least implement the methods that call X# unimpl() below: minsize(), getbounds() and setbounds(). X -XError = 'Split.Error' # Exception +XError = 'Split.Error' # Exception X Ximport rect Xfrom util import remove X Xclass Split(): -X # -X # Calls from creator -X # NB derived classes may add parameters to create() -X # -X def create(self, parent): -X parent.addchild(self) -X self.parent = parent -X self.children = [] -X self.mouse_interest = [] -X self.timer_interest = [] -X self.mouse_focus = 0 -X return self -X # -X # Downcalls from parent to child -X # -X def destroy(self): -X self.parent = None -X for child in self.children: -X child.destroy() -X del self.children[:] -X del self.mouse_interest[:] -X del self.timer_interest[:] -X self.mouse_focus = None -X # -X def minsize(self, m): return unimpl() -X def getbounds(self): return unimpl() -X def setbounds(self, bounds): unimpl() -X # -X def draw(self, d_detail): -X # (Could avoid calls to children outside the area) -X for child in self.children: -X child.draw(d_detail) -X # -X # Downcalls only made after certain upcalls -X # -X def mouse_down(self, detail): -X if self.mouse_focus: -X self.mouse_focus.mouse_down(detail) -X p = detail[0] -X for child in self.mouse_interest: -X if rect.pointinrect(p, child.getbounds()): -X self.mouse_focus = child -X child.mouse_down(detail) -X def mouse_move(self, detail): -X if self.mouse_focus: -X self.mouse_focus.mouse_move(detail) -X def mouse_up(self, detail): -X if self.mouse_focus: -X self.mouse_focus.mouse_up(detail) -X self.mouse_focus = 0 -X # -X def timer(self): -X for child in self.timer_interest: -X child.timer() -X # -X # Upcalls from child to parent -X # -X def addchild(self, child): -X if child in self.children: -X raise Error, 'addchild: child already inlist' -X self.children.append(child) -X def delchild(self, child): -X if child not in self.children: -X raise Error, 'delchild: child not in list' -X remove(child, self.children) -X if child in self.mouse_interest: -X remove(child, self.mouse_interest) -X if child in self.timer_interest: -X remove(child, self.timer_interest) -X if child = self.mouse_focus: -X self.mouse_focus = 0 -X # -X def need_mouse(self, child): -X if child not in self.mouse_interest: -X self.mouse_interest.append(child) -X self.parent.need_mouse(self) -X def no_mouse(self, child): -X if child in self.mouse_interest: -X remove(child, self.mouse_interest) -X if not self.mouse_interest: -X self.parent.no_mouse(self) -X # -X def need_timer(self, child): -X if child not in self.timer_interest: -X self.timer_interest.append(child) -X self.parent.need_timer(self) -X def no_timer(self, child): -X if child in self.timer_interest: -X remove(child, self.timer_interest) -X if not self.timer_interest: -X self.parent.no_timer(self) -X # -X # The rest are transparent: -X # -X def begindrawing(self): -X return self.parent.begindrawing() -X def beginmeasuring(self): -X return self.parent.beginmeasuring() -X # -X def change(self, area): -X self.parent.change(area) -X def scroll(self, area_vector): -X self.parent.scroll(area_vector) -X def settimer(self, itimer): -X self.parent.settimer(itimer) +X # +X # Calls from creator +X # NB derived classes may add parameters to create() +X # +X def create(self, parent): +X parent.addchild(self) +X self.parent = parent +X self.children = [] +X self.mouse_interest = [] +X self.timer_interest = [] +X self.mouse_focus = 0 +X return self +X # +X # Downcalls from parent to child +X # +X def destroy(self): +X self.parent = None +X for child in self.children: +X child.destroy() +X del self.children[:] +X del self.mouse_interest[:] +X del self.timer_interest[:] +X self.mouse_focus = None +X # +X def minsize(self, m): return unimpl() +X def getbounds(self): return unimpl() +X def setbounds(self, bounds): unimpl() +X # +X def draw(self, d_detail): +X # (Could avoid calls to children outside the area) +X for child in self.children: +X child.draw(d_detail) +X # +X # Downcalls only made after certain upcalls +X # +X def mouse_down(self, detail): +X if self.mouse_focus: +X self.mouse_focus.mouse_down(detail) +X p = detail[0] +X for child in self.mouse_interest: +X if rect.pointinrect(p, child.getbounds()): +X self.mouse_focus = child +X child.mouse_down(detail) +X def mouse_move(self, detail): +X if self.mouse_focus: +X self.mouse_focus.mouse_move(detail) +X def mouse_up(self, detail): +X if self.mouse_focus: +X self.mouse_focus.mouse_up(detail) +X self.mouse_focus = 0 +X # +X def timer(self): +X for child in self.timer_interest: +X child.timer() +X # +X # Upcalls from child to parent +X # +X def addchild(self, child): +X if child in self.children: +X raise Error, 'addchild: child already inlist' +X self.children.append(child) +X def delchild(self, child): +X if child not in self.children: +X raise Error, 'delchild: child not in list' +X remove(child, self.children) +X if child in self.mouse_interest: +X remove(child, self.mouse_interest) +X if child in self.timer_interest: +X remove(child, self.timer_interest) +X if child = self.mouse_focus: +X self.mouse_focus = 0 +X # +X def need_mouse(self, child): +X if child not in self.mouse_interest: +X self.mouse_interest.append(child) +X self.parent.need_mouse(self) +X def no_mouse(self, child): +X if child in self.mouse_interest: +X remove(child, self.mouse_interest) +X if not self.mouse_interest: +X self.parent.no_mouse(self) +X # +X def need_timer(self, child): +X if child not in self.timer_interest: +X self.timer_interest.append(child) +X self.parent.need_timer(self) +X def no_timer(self, child): +X if child in self.timer_interest: +X remove(child, self.timer_interest) +X if not self.timer_interest: +X self.parent.no_timer(self) +X # +X # The rest are transparent: +X # +X def begindrawing(self): +X return self.parent.begindrawing() +X def beginmeasuring(self): +X return self.parent.beginmeasuring() +X # +X def change(self, area): +X self.parent.change(area) +X def scroll(self, area_vector): +X self.parent.scroll(area_vector) +X def settimer(self, itimer): +X self.parent.settimer(itimer) EOF fi if test -s 'lib/WindowParent.py' @@ -797,98 +797,98 @@ Xfrom stdwinevents import * X Xfrom TransParent import ManageOneChild X -XError = 'WindowParent.Error' # Exception +XError = 'WindowParent.Error' # Exception X Xclass WindowParent() = ManageOneChild(): -X # -X def create(self, (title, size)): -X self.title = title -X self.size = size # (width, height) -X self._reset() -X return self -X # -X def _reset(self): -X self.child = 0 -X self.win = 0 -X self.itimer = 0 -X self.do_mouse = 0 -X self.do_timer = 0 -X # -X def destroy(self): -X if self.child: self.child.destroy() -X self._reset() -X # -X def need_mouse(self, child): self.do_mouse = 1 -X def no_mouse(self, child): self.do_mouse = 0 -X # -X def need_timer(self, child): self.do_timer = 1 -X def no_timer(self, child): self.do_timer = 0 -X # -X def realize(self): -X if self.win: -X raise Error, 'realize(): called twice' -X if not self.child: -X raise Error, 'realize(): no child' -X size = self.child.minsize(self.beginmeasuring()) -X self.size = max(self.size[0], size[0]), \ -X max(self.size[1], size[1]) -X #stdwin.setdefwinsize(self.size) -X # XXX Compensate stdwin bug: -X stdwin.setdefwinsize(self.size[0]+4, self.size[1]+2) -X self.win = stdwin.open(self.title) -X if self.itimer: -X self.win.settimer(self.itimer) -X bounds = (0, 0), self.win.getwinsize() -X self.child.setbounds(bounds) -X # -X def beginmeasuring(self): -X # Return something with which a child can measure text -X if self.win: -X return self.win.begindrawing() -X else: -X return stdwin -X # -X def begindrawing(self): -X if self.win: -X return self.win.begindrawing() -X else: -X raise Error, 'begindrawing(): not realized yet' -X # -X def change(self, area): -X if self.win: -X self.win.change(area) -X # -X def scroll(self, args): -X if self.win: -X self.win.scroll(args) -X # -X def settimer(self, itimer): -X if self.win: -X self.win.settimer(itimer) -X else: -X self.itimer = itimer -X # -X # Only call dispatch if we have a child -X # -X def dispatch(self, (type, win, detail)): -X if win <> self.win: -X return -X elif type = WE_DRAW: -X d = self.win.begindrawing() -X self.child.draw(d, detail) -X elif type = WE_MOUSE_DOWN: -X if self.do_mouse: self.child.mouse_down(detail) -X elif type = WE_MOUSE_MOVE: -X if self.do_mouse: self.child.mouse_move(detail) -X elif type = WE_MOUSE_UP: -X if self.do_mouse: self.child.mouse_up(detail) -X elif type = WE_TIMER: -X if self.do_timer: self.child.timer() -X elif type = WE_SIZE: -X self.win.change((0, 0), (10000, 10000)) # XXX -X bounds = (0, 0), self.win.getwinsize() -X self.child.setbounds(bounds) -X # +X # +X def create(self, (title, size)): +X self.title = title +X self.size = size # (width, height) +X self._reset() +X return self +X # +X def _reset(self): +X self.child = 0 +X self.win = 0 +X self.itimer = 0 +X self.do_mouse = 0 +X self.do_timer = 0 +X # +X def destroy(self): +X if self.child: self.child.destroy() +X self._reset() +X # +X def need_mouse(self, child): self.do_mouse = 1 +X def no_mouse(self, child): self.do_mouse = 0 +X # +X def need_timer(self, child): self.do_timer = 1 +X def no_timer(self, child): self.do_timer = 0 +X # +X def realize(self): +X if self.win: +X raise Error, 'realize(): called twice' +X if not self.child: +X raise Error, 'realize(): no child' +X size = self.child.minsize(self.beginmeasuring()) +X self.size = max(self.size[0], size[0]), \ +X max(self.size[1], size[1]) +X #stdwin.setdefwinsize(self.size) +X # XXX Compensate stdwin bug: +X stdwin.setdefwinsize(self.size[0]+4, self.size[1]+2) +X self.win = stdwin.open(self.title) +X if self.itimer: +X self.win.settimer(self.itimer) +X bounds = (0, 0), self.win.getwinsize() +X self.child.setbounds(bounds) +X # +X def beginmeasuring(self): +X # Return something with which a child can measure text +X if self.win: +X return self.win.begindrawing() +X else: +X return stdwin +X # +X def begindrawing(self): +X if self.win: +X return self.win.begindrawing() +X else: +X raise Error, 'begindrawing(): not realized yet' +X # +X def change(self, area): +X if self.win: +X self.win.change(area) +X # +X def scroll(self, args): +X if self.win: +X self.win.scroll(args) +X # +X def settimer(self, itimer): +X if self.win: +X self.win.settimer(itimer) +X else: +X self.itimer = itimer +X # +X # Only call dispatch if we have a child +X # +X def dispatch(self, (type, win, detail)): +X if win <> self.win: +X return +X elif type = WE_DRAW: +X d = self.win.begindrawing() +X self.child.draw(d, detail) +X elif type = WE_MOUSE_DOWN: +X if self.do_mouse: self.child.mouse_down(detail) +X elif type = WE_MOUSE_MOVE: +X if self.do_mouse: self.child.mouse_move(detail) +X elif type = WE_MOUSE_UP: +X if self.do_mouse: self.child.mouse_up(detail) +X elif type = WE_TIMER: +X if self.do_timer: self.child.timer() +X elif type = WE_SIZE: +X self.win.change((0, 0), (10000, 10000)) # XXX +X bounds = (0, 0), self.win.getwinsize() +X self.child.setbounds(bounds) +X # EOF fi if test -s 'lib/gwin.py' @@ -907,113 +907,113 @@ Xfrom stdwinevents import * X X# XXX Old version of stdwinevents, should go Ximport stdwinsupport -XS = stdwinsupport # Shorthand +XS = stdwinsupport # Shorthand X -Xwindows = [] # List of open windows +Xwindows = [] # List of open windows X X X# Open a window X -Xdef open(title): # Open a generic window -X w = stdwin.open(title) -X stdwin.setdefwinsize(0, 0) -X # Set default event handlers -X w.draw = nop -X w.char = nop -X w.mdown = nop -X w.mmove = nop -X w.mup = nop -X w.m2down = m2down -X w.m2up = m2up -X w.size = nop -X w.move = nop -X w.activate = w.deactivate = nop -X w.timer = nop -X # default command handlers -X w.close = close -X w.tab = tab -X w.enter = enter -X w.backspace = backspace -X w.arrow = arrow -X w.kleft = w.kup = w.kright = w.kdown = nop -X windows.append(w) -X return w +Xdef open(title): # Open a generic window +X w = stdwin.open(title) +X stdwin.setdefwinsize(0, 0) +X # Set default event handlers +X w.draw = nop +X w.char = nop +X w.mdown = nop +X w.mmove = nop +X w.mup = nop +X w.m2down = m2down +X w.m2up = m2up +X w.size = nop +X w.move = nop +X w.activate = w.deactivate = nop +X w.timer = nop +X # default command handlers +X w.close = close +X w.tab = tab +X w.enter = enter +X w.backspace = backspace +X w.arrow = arrow +X w.kleft = w.kup = w.kright = w.kdown = nop +X windows.append(w) +X return w X X X# Generic event dispatching X -Xdef mainloop(): # Handle events until no windows left -X while windows: -X treatevent(stdwin.getevent()) -X -Xdef treatevent(e): # Handle a stdwin event -X type, w, detail = e -X if type = S.we_draw: -X w.draw(w, detail) -X elif type = S.we_menu: -X m, item = detail -X m.action[item](w, m, item) -X elif type = S.we_command: -X treatcommand(w, detail) -X elif type = S.we_char: -X w.char(w, detail) -X elif type = S.we_mouse_down: -X if detail[1] > 1: w.m2down(w, detail) -X else: w.mdown(w, detail) -X elif type = S.we_mouse_move: -X w.mmove(w, detail) -X elif type = S.we_mouse_up: -X if detail[1] > 1: w.m2up(w, detail) -X else: w.mup(w, detail) -X elif type = S.we_size: -X w.size(w, w.getwinsize()) -X elif type = S.we_activate: -X w.activate(w) -X elif type = S.we_deactivate: -X w.deactivate(w) -X elif type = S.we_move: -X w.move(w) -X elif type = S.we_timer: -X w.timer(w) -X elif type = WE_CLOSE: -X w.close(w) -X -Xdef treatcommand(w, type): # Handle a we_command event -X if type = S.wc_close: -X w.close(w) -X elif type = S.wc_return: -X w.enter(w) -X elif type = S.wc_tab: -X w.tab(w) -X elif type = S.wc_backspace: -X w.backspace(w) -X elif type in (S.wc_left, S.wc_up, S.wc_right, S.wc_down): -X w.arrow(w, type) +Xdef mainloop(): # Handle events until no windows left +X while windows: +X treatevent(stdwin.getevent()) +X +Xdef treatevent(e): # Handle a stdwin event +X type, w, detail = e +X if type = S.we_draw: +X w.draw(w, detail) +X elif type = S.we_menu: +X m, item = detail +X m.action[item](w, m, item) +X elif type = S.we_command: +X treatcommand(w, detail) +X elif type = S.we_char: +X w.char(w, detail) +X elif type = S.we_mouse_down: +X if detail[1] > 1: w.m2down(w, detail) +X else: w.mdown(w, detail) +X elif type = S.we_mouse_move: +X w.mmove(w, detail) +X elif type = S.we_mouse_up: +X if detail[1] > 1: w.m2up(w, detail) +X else: w.mup(w, detail) +X elif type = S.we_size: +X w.size(w, w.getwinsize()) +X elif type = S.we_activate: +X w.activate(w) +X elif type = S.we_deactivate: +X w.deactivate(w) +X elif type = S.we_move: +X w.move(w) +X elif type = S.we_timer: +X w.timer(w) +X elif type = WE_CLOSE: +X w.close(w) +X +Xdef treatcommand(w, type): # Handle a we_command event +X if type = S.wc_close: +X w.close(w) +X elif type = S.wc_return: +X w.enter(w) +X elif type = S.wc_tab: +X w.tab(w) +X elif type = S.wc_backspace: +X w.backspace(w) +X elif type in (S.wc_left, S.wc_up, S.wc_right, S.wc_down): +X w.arrow(w, type) X X X# Methods X -Xdef close(w): # Close method -X for i in range(len(windows)): -X if windows[i] is w: -X del windows[i] -X break +Xdef close(w): # Close method +X for i in range(len(windows)): +X if windows[i] is w: +X del windows[i] +X break X -Xdef arrow(w, detail): # Arrow key method -X if detail = S.wc_left: -X w.kleft(w) -X elif detail = S.wc_up: -X w.kup(w) -X elif detail = S.wc_right: -X w.kright(w) -X elif detail = S.wc_down: -X w.kdown(w) +Xdef arrow(w, detail): # Arrow key method +X if detail = S.wc_left: +X w.kleft(w) +X elif detail = S.wc_up: +X w.kup(w) +X elif detail = S.wc_right: +X w.kright(w) +X elif detail = S.wc_down: +X w.kdown(w) X X X# Trivial methods X Xdef tab(w): w.char(w, '\t') -Xdef enter(w): w.char(w, '\n') # 'return' is a Python reserved word +Xdef enter(w): w.char(w, '\n') # 'return' is a Python reserved word Xdef backspace(w): w.char(w, '\b') Xdef m2down(w, detail): w.mdown(w, detail) Xdef m2up(w, detail): w.mup(w, detail) @@ -1042,47 +1042,47 @@ X# Tokenize a string. X# Return a list of tokens (strings). X# Xdef tokenize_string(s): -X tokens = [] -X while s: -X c = s[:1] -X if c in whitespace: -X s = s[1:] -X elif c = ';': -X s = '' -X elif c = '"': -X n = len(s) -X i = 1 -X while i < n: -X c = s[i] -X i = i+1 -X if c = '"': break -X if c = '\\': i = i+1 -X tokens.append(s[:i]) -X s = s[i:] -X elif c in operators: -X tokens.append(c) -X s = s[1:] -X else: -X n = len(s) -X i = 1 -X while i < n: -X if s[i] in separators: break -X i = i+1 -X tokens.append(s[:i]) -X s = s[i:] -X return tokens +X tokens = [] +X while s: +X c = s[:1] +X if c in whitespace: +X s = s[1:] +X elif c = ';': +X s = '' +X elif c = '"': +X n = len(s) +X i = 1 +X while i < n: +X c = s[i] +X i = i+1 +X if c = '"': break +X if c = '\\': i = i+1 +X tokens.append(s[:i]) +X s = s[i:] +X elif c in operators: +X tokens.append(c) +X s = s[1:] +X else: +X n = len(s) +X i = 1 +X while i < n: +X if s[i] in separators: break +X i = i+1 +X tokens.append(s[:i]) +X s = s[i:] +X return tokens X X X# Tokenize a whole file (given as file object, not as file name). X# Return a list of tokens (strings). X# Xdef tokenize_file(fp): -X tokens = [] -X while 1: -X line = fp.readline() -X if not line: break -X tokens = tokens + tokenize_string(line) -X return tokens +X tokens = [] +X while 1: +X line = fp.readline() +X if not line: break +X tokens = tokens + tokenize_string(line) +X return tokens X X X# Exception raised by parse_exr. @@ -1098,50 +1098,50 @@ X# and tokens contains the remaining tokens. X# May raise syntax_error. X# Xdef parse_expr(tokens): -X if (not tokens) or tokens[0] <> '(': -X raise syntax_error, 'expected "("' -X tokens = tokens[1:] -X expr = [] -X while 1: -X if not tokens: -X raise syntax_error, 'missing ")"' -X if tokens[0] = ')': -X return expr, tokens[1:] -X elif tokens[0] = '(': -X subexpr, tokens = parse_expr(tokens) -X expr.append(subexpr) -X else: -X expr.append(tokens[0]) -X tokens = tokens[1:] +X if (not tokens) or tokens[0] <> '(': +X raise syntax_error, 'expected "("' +X tokens = tokens[1:] +X expr = [] +X while 1: +X if not tokens: +X raise syntax_error, 'missing ")"' +X if tokens[0] = ')': +X return expr, tokens[1:] +X elif tokens[0] = '(': +X subexpr, tokens = parse_expr(tokens) +X expr.append(subexpr) +X else: +X expr.append(tokens[0]) +X tokens = tokens[1:] X X X# Parse a file (given as file object, not as file name). X# Return a list of parsed S-expressions found at the top level. X# Xdef parse_file(fp): -X tokens = tokenize_file(fp) -X exprlist = [] -X while tokens: -X expr, tokens = parse_expr(tokens) -X exprlist.append(expr) -X return exprlist +X tokens = tokenize_file(fp) +X exprlist = [] +X while tokens: +X expr, tokens = parse_expr(tokens) +X exprlist.append(expr) +X return exprlist X X X# EXAMPLE: X# X# The input -X# '(hip (hop hur-ray))' +X# '(hip (hop hur-ray))' X# X# passed to tokenize_string() returns the token list -X# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')'] +X# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')'] X# X# When this is passed to parse_expr() it returns the expression -X# ['hip', ['hop', 'hur-ray']] +X# ['hip', ['hop', 'hur-ray']] X# plus an empty token list (because there are no tokens left. X# X# When a file containing the example is passed to parse_file() it returns X# a list whose only element is the output of parse_expr() above: -X# [['hip', ['hop', 'hur-ray']]] +X# [['hip', ['hop', 'hur-ray']]] X X X# TOKENIZING: @@ -1150,7 +1150,7 @@ X# Comments start with semicolon (;) and continue till the end of the line. X# X# Tokens are separated by whitespace, except the following characters X# always form a separate token (outside strings): -X# ( ) ' +X# ( ) ' X# Strings are enclosed in double quotes (") and backslash (\) is used X# as escape character in strings. EOF @@ -1172,86 +1172,86 @@ X# Ignores the first part altogether if the second part is absolute X# (begins with '/'). X# Xdef cat(a, b): -X if b[:1] = '/': return b -X if a = '' or a[-1:] = '/': return a + b -X return a + '/' + b +X if b[:1] = '/': return b +X if a = '' or a[-1:] = '/': return a + b +X return a + '/' + b X X X# Split a path in head (empty or ending in '/') and tail (no '/'). X# The tail will be empty if the path ends in '/'. X# Xdef split(p): -X head, tail = '', '' -X for c in p: -X tail = tail + c -X if c = '/': -X head, tail = head + tail, '' -X return head, tail +X head, tail = '', '' +X for c in p: +X tail = tail + c +X if c = '/': +X head, tail = head + tail, '' +X return head, tail X X X# Return the tail (basename) part of a path. X# Xdef basename(p): -X return split(p)[1] +X return split(p)[1] X X X# Return the longest prefix of all list elements. X# Xdef commonprefix(m): -X if not m: return '' -X prefix = m[0] -X for item in m: -X for i in range(len(prefix)): -X if prefix[:i+1] <> item[:i+1]: -X prefix = prefix[:i] -X if i = 0: return '' -X break -X return prefix +X if not m: return '' +X prefix = m[0] +X for item in m: +X for i in range(len(prefix)): +X if prefix[:i+1] <> item[:i+1]: +X prefix = prefix[:i] +X if i = 0: return '' +X break +X return prefix X X X# Does a file/directory exist? X# Xdef exists(path): -X try: -X st = posix.stat(path) -X except posix.error: -X return 0 -X return 1 +X try: +X st = posix.stat(path) +X except posix.error: +X return 0 +X return 1 X X X# Is a path a posix directory? X# Xdef isdir(path): -X try: -X st = posix.stat(path) -X except posix.error: -X return 0 -X return stat.S_ISDIR(st[stat.ST_MODE]) +X try: +X st = posix.stat(path) +X except posix.error: +X return 0 +X return stat.S_ISDIR(st[stat.ST_MODE]) X X X# Is a path a symbolic link? X# This will always return false on systems where posix.lstat doesn't exist. X# Xdef islink(path): -X try: -X st = posix.lstat(path) -X except (posix.error, NameError): -X return 0 -X return stat.S_ISLNK(st[stat.ST_MODE]) +X try: +X st = posix.lstat(path) +X except (posix.error, NameError): +X return 0 +X return stat.S_ISLNK(st[stat.ST_MODE]) X X X_mounts = [] X Xdef _getmounts(): -X import commands, string -X mounts = [] -X data = commands.getoutput('/etc/mount') -X lines = string.splitfields(data, '\n') -X for line in lines: -X words = string.split(line) -X if len(words) >= 3 and words[1] = 'on': -X mounts.append(words[2]) -X return mounts +X import commands, string +X mounts = [] +X data = commands.getoutput('/etc/mount') +X lines = string.splitfields(data, '\n') +X for line in lines: +X words = string.split(line) +X if len(words) >= 3 and words[1] = 'on': +X mounts.append(words[2]) +X return mounts X X X# Is a path a mount point? @@ -1260,9 +1260,9 @@ X# and only if the mount table as printed by /etc/mount is correct. X# Sorry. X# Xdef ismount(path): -X if not _mounts: -X _mounts[:] = _getmounts() -X return path in _mounts +X if not _mounts: +X _mounts[:] = _getmounts() +X return path in _mounts X X X# Directory tree walk. @@ -1274,17 +1274,17 @@ X# func may modify the filenames list, to implement a filter, X# or to impose a different order of visiting. X# Xdef walk(top, func, arg): -X try: -X names = posix.listdir(top) -X except posix.error: -X return -X func(arg, top, names) -X exceptions = ('.', '..') -X for name in names: -X if name not in exceptions: -X name = cat(top, name) -X if isdir(name): -X walk(name, func, arg) +X try: +X names = posix.listdir(top) +X except posix.error: +X return +X func(arg, top, names) +X exceptions = ('.', '..') +X for name in names: +X if name not in exceptions: +X name = cat(top, name) +X if isdir(name): +X walk(name, func, arg) EOF fi if test -s 'lib/string.py' @@ -1308,119 +1308,119 @@ X X# Case conversion helpers X_caseswap = {} Xfor i in range(26): -X _caseswap[lowercase[i]] = uppercase[i] -X _caseswap[uppercase[i]] = lowercase[i] +X _caseswap[lowercase[i]] = uppercase[i] +X _caseswap[uppercase[i]] = lowercase[i] Xdel i X X# convert UPPER CASE letters to lower case Xdef lower(s): -X res = '' -X for c in s: -X if 'A' <= c <= 'Z': c = _caseswap[c] -X res = res + c -X return res +X res = '' +X for c in s: +X if 'A' <= c <= 'Z': c = _caseswap[c] +X res = res + c +X return res X X# Convert lower case letters to UPPER CASE Xdef upper(s): -X res = '' -X for c in s: -X if 'a' <= c <= 'z': c = _caseswap[c] -X res = res + c -X return res +X res = '' +X for c in s: +X if 'a' <= c <= 'z': c = _caseswap[c] +X res = res + c +X return res X X# Swap lower case letters and UPPER CASE Xdef swapcase(s): -X res = '' -X for c in s: -X if 'a' <= c <= 'z' or 'A' <= c <= 'Z': c = _caseswap[c] -X res = res + c -X return res +X res = '' +X for c in s: +X if 'a' <= c <= 'z' or 'A' <= c <= 'Z': c = _caseswap[c] +X res = res + c +X return res X X# Strip leading and trailing tabs and spaces Xdef strip(s): -X i, j = 0, len(s) -X while i < j and s[i] in whitespace: i = i+1 -X while i < j and s[j-1] in whitespace: j = j-1 -X return s[i:j] +X i, j = 0, len(s) +X while i < j and s[i] in whitespace: i = i+1 +X while i < j and s[j-1] in whitespace: j = j-1 +X return s[i:j] X X# Split a string into a list of space/tab-separated words X# NB: split(s) is NOT the same as splitfields(s, ' ')! Xdef split(s): -X res = [] -X i, n = 0, len(s) -X while i < n: -X while i < n and s[i] in whitespace: i = i+1 -X if i = n: break -X j = i -X while j < n and s[j] not in whitespace: j = j+1 -X res.append(s[i:j]) -X i = j -X return res +X res = [] +X i, n = 0, len(s) +X while i < n: +X while i < n and s[i] in whitespace: i = i+1 +X if i = n: break +X j = i +X while j < n and s[j] not in whitespace: j = j+1 +X res.append(s[i:j]) +X i = j +X return res X X# Split a list into fields separated by a given string X# NB: splitfields(s, ' ') is NOT the same as split(s)! Xdef splitfields(s, sep): -X res = [] -X ns = len(s) -X nsep = len(sep) -X i = j = 0 -X while j+nsep <= ns: -X if s[j:j+nsep] = sep: -X res.append(s[i:j]) -X i = j = j + nsep -X else: -X j = j + 1 -X res.append(s[i:]) -X return res +X res = [] +X ns = len(s) +X nsep = len(sep) +X i = j = 0 +X while j+nsep <= ns: +X if s[j:j+nsep] = sep: +X res.append(s[i:j]) +X i = j = j + nsep +X else: +X j = j + 1 +X res.append(s[i:]) +X return res X X# Find substring Xindex_error = 'substring not found in string.index' Xdef index(s, sub): -X n = len(sub) -X for i in range(len(s) + 1 - n): -X if sub = s[i:i+n]: return i -X raise index_error, (s, sub) +X n = len(sub) +X for i in range(len(s) + 1 - n): +X if sub = s[i:i+n]: return i +X raise index_error, (s, sub) X X# Convert string to integer Xatoi_error = 'non-numeric argument to string.atoi' Xdef atoi(str): -X s = str -X if s[:1] in '+-': s = s[1:] -X if not s: raise atoi_error, str -X for c in s: -X if c not in digits: raise atoi_error, str -X return eval(str) +X s = str +X if s[:1] in '+-': s = s[1:] +X if not s: raise atoi_error, str +X for c in s: +X if c not in digits: raise atoi_error, str +X return eval(str) X X# Left-justify a string Xdef ljust(s, width): -X n = len(s) -X if n >= width: return s -X return s + ' '*(width-n) +X n = len(s) +X if n >= width: return s +X return s + ' '*(width-n) X X# Right-justify a string Xdef rjust(s, width): -X n = len(s) -X if n >= width: return s -X return ' '*(width-n) + s +X n = len(s) +X if n >= width: return s +X return ' '*(width-n) + s X X# Center a string Xdef center(s, width): -X n = len(s) -X if n >= width: return s -X return ' '*((width-n)/2) + s + ' '*(width -(width-n)/2) +X n = len(s) +X if n >= width: return s +X return ' '*((width-n)/2) + s + ' '*(width -(width-n)/2) X X# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03' X# Decadent feature: the argument may be a string or a number X# (Use of this is deprecated; it should be a string as with ljust c.s.) Xdef zfill(x, width): -X if type(x) = type(''): s = x -X else: s = `x` -X n = len(s) -X if n >= width: return s -X sign = '' -X if s[0] = '-': -X sign, s = '-', s[1:] -X return sign + '0'*(width-n) + s +X if type(x) = type(''): s = x +X else: s = `x` +X n = len(s) +X if n >= width: return s +X sign = '' +X if s[0] = '-': +X sign, s = '-', s[1:] +X return sign + '0'*(width-n) + s EOF fi if test -s 'src/Grammar' @@ -1431,26 +1431,26 @@ sed 's/^X//' > 'src/Grammar' << 'EOF' X# Grammar for Python, version 4 X X# Changes compared to version 3: -X# Removed 'dir' statement. -X# Function call argument is a testlist instead of exprlist. +X# Removed 'dir' statement. +X# Function call argument is a testlist instead of exprlist. X X# Changes compared to version 2: -X# The syntax of Boolean operations is changed to use more -X# conventional priorities: or < and < not. +X# The syntax of Boolean operations is changed to use more +X# conventional priorities: or < and < not. X X# Changes compared to version 1: -X# modules and scripts are unified; -X# 'quit' is gone (use ^D); -X# empty_stmt is gone, replaced by explicit NEWLINE where appropriate; -X# 'import' and 'def' aren't special any more; -X# added 'from' NAME option on import clause, and '*' to import all; -X# added class definition. +X# modules and scripts are unified; +X# 'quit' is gone (use ^D); +X# empty_stmt is gone, replaced by explicit NEWLINE where appropriate; +X# 'import' and 'def' aren't special any more; +X# added 'from' NAME option on import clause, and '*' to import all; +X# added class definition. X X# Start symbols for the grammar: -X# single_input is a single interactive statement; -X# file_input is a module or sequence of commands read from an input file; -X# expr_input is the input for the input() function; -X# eval_input is the input for the eval() function. +X# single_input is a single interactive statement; +X# file_input is a module or sequence of commands read from an input file; +X# expr_input is the input for the input() function; +X# eval_input is the input for the eval() function. X X# NB: compound_stmt in single_input is followed by extra NEWLINE! Xsingle_input: NEWLINE | simple_stmt | compound_stmt NEWLINE @@ -1464,7 +1464,7 @@ Xfplist: fpdef (',' fpdef)* Xfpdef: NAME | '(' fplist ')' X Xstmt: simple_stmt | compound_stmt -Xsimple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt +Xsimple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt Xexpr_stmt: (exprlist '=')* exprlist NEWLINE X# For assignments, additional restrictions enforced by the interpreter Xprint_stmt: 'print' (test ',')* [test] NEWLINE @@ -1511,12 +1511,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1544,101 +1544,101 @@ Xstatic void calcfirstset PROTO((grammar *, dfa *)); X Xvoid Xaddfirstsets(g) -X grammar *g; +X grammar *g; X{ -X int i; -X dfa *d; -X -X printf("Adding FIRST sets ...\n"); -X for (i = 0; i < g->g_ndfas; i++) { -X d = &g->g_dfa[i]; -X if (d->d_first == NULL) -X calcfirstset(g, d); -X } +X int i; +X dfa *d; +X +X printf("Adding FIRST sets ...\n"); +X for (i = 0; i < g->g_ndfas; i++) { +X d = &g->g_dfa[i]; +X if (d->d_first == NULL) +X calcfirstset(g, d); +X } X} X Xstatic void Xcalcfirstset(g, d) -X grammar *g; -X dfa *d; +X grammar *g; +X dfa *d; X{ -X int i, j; -X state *s; -X arc *a; -X int nsyms; -X int *sym; -X int nbits; -X static bitset dummy; -X bitset result; -X int type; -X dfa *d1; -X label *l0; -X -X if (debugging) -X printf("Calculate FIRST set for '%s'\n", d->d_name); -X -X if (dummy == NULL) -X dummy = newbitset(1); -X if (d->d_first == dummy) { -X fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); -X return; -X } -X if (d->d_first != NULL) { -X fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", -X d->d_name); -X } -X d->d_first = dummy; -X -X l0 = g->g_ll.ll_label; -X nbits = g->g_ll.ll_nlabels; -X result = newbitset(nbits); -X -X sym = NEW(int, 1); -X if (sym == NULL) -X fatal("no mem for new sym in calcfirstset"); -X nsyms = 1; -X sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); -X -X s = &d->d_state[d->d_initial]; -X for (i = 0; i < s->s_narcs; i++) { -X a = &s->s_arc[i]; -X for (j = 0; j < nsyms; j++) { -X if (sym[j] == a->a_lbl) -X break; -X } -X if (j >= nsyms) { /* New label */ -X RESIZE(sym, int, nsyms + 1); -X if (sym == NULL) -X fatal("no mem to resize sym in calcfirstset"); -X sym[nsyms++] = a->a_lbl; -X type = l0[a->a_lbl].lb_type; -X if (ISNONTERMINAL(type)) { -X d1 = finddfa(g, type); -X if (d1->d_first == dummy) { -X fprintf(stderr, -X "Left-recursion below '%s'\n", -X d->d_name); -X } -X else { -X if (d1->d_first == NULL) -X calcfirstset(g, d1); -X mergebitset(result, d1->d_first, nbits); -X } -X } -X else if (ISTERMINAL(type)) { -X addbit(result, a->a_lbl); -X } -X } -X } -X d->d_first = result; -X if (debugging) { -X printf("FIRST set for '%s': {", d->d_name); -X for (i = 0; i < nbits; i++) { -X if (testbit(result, i)) -X printf(" %s", labelrepr(&l0[i])); -X } -X printf(" }\n"); -X } +X int i, j; +X state *s; +X arc *a; +X int nsyms; +X int *sym; +X int nbits; +X static bitset dummy; +X bitset result; +X int type; +X dfa *d1; +X label *l0; +X +X if (debugging) +X printf("Calculate FIRST set for '%s'\n", d->d_name); +X +X if (dummy == NULL) +X dummy = newbitset(1); +X if (d->d_first == dummy) { +X fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); +X return; +X } +X if (d->d_first != NULL) { +X fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", +X d->d_name); +X } +X d->d_first = dummy; +X +X l0 = g->g_ll.ll_label; +X nbits = g->g_ll.ll_nlabels; +X result = newbitset(nbits); +X +X sym = NEW(int, 1); +X if (sym == NULL) +X fatal("no mem for new sym in calcfirstset"); +X nsyms = 1; +X sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); +X +X s = &d->d_state[d->d_initial]; +X for (i = 0; i < s->s_narcs; i++) { +X a = &s->s_arc[i]; +X for (j = 0; j < nsyms; j++) { +X if (sym[j] == a->a_lbl) +X break; +X } +X if (j >= nsyms) { /* New label */ +X RESIZE(sym, int, nsyms + 1); +X if (sym == NULL) +X fatal("no mem to resize sym in calcfirstset"); +X sym[nsyms++] = a->a_lbl; +X type = l0[a->a_lbl].lb_type; +X if (ISNONTERMINAL(type)) { +X d1 = finddfa(g, type); +X if (d1->d_first == dummy) { +X fprintf(stderr, +X "Left-recursion below '%s'\n", +X d->d_name); +X } +X else { +X if (d1->d_first == NULL) +X calcfirstset(g, d1); +X mergebitset(result, d1->d_first, nbits); +X } +X } +X else if (ISTERMINAL(type)) { +X addbit(result, a->a_lbl); +X } +X } +X } +X d->d_first = result; +X if (debugging) { +X printf("FIRST set for '%s': {", d->d_name); +X for (i = 0; i < nbits; i++) { +X if (testbit(result, i)) +X printf(" %s", labelrepr(&l0[i])); +X } +X printf(" }\n"); +X } X} EOF fi @@ -1651,12 +1651,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1674,22 +1674,22 @@ X X/* Frame object interface */ X Xtypedef struct { -X int b_type; /* what kind of block this is */ -X int b_handler; /* where to jump to find handler */ -X int b_level; /* value stack level to pop to */ +X int b_type; /* what kind of block this is */ +X int b_handler; /* where to jump to find handler */ +X int b_level; /* value stack level to pop to */ X} block; X Xtypedef struct _frame { -X OB_HEAD -X struct _frame *f_back; /* previous frame, or NULL */ -X codeobject *f_code; /* code segment */ -X object *f_globals; /* global symbol table (dictobject) */ -X object *f_locals; /* local symbol table (dictobject) */ -X object **f_valuestack; /* malloc'ed array */ -X block *f_blockstack; /* malloc'ed array */ -X int f_nvalues; /* size of f_valuestack */ -X int f_nblocks; /* size of f_blockstack */ -X int f_iblock; /* index in f_blockstack */ +X OB_HEAD +X struct _frame *f_back; /* previous frame, or NULL */ +X codeobject *f_code; /* code segment */ +X object *f_globals; /* global symbol table (dictobject) */ +X object *f_locals; /* local symbol table (dictobject) */ +X object **f_valuestack; /* malloc'ed array */ +X block *f_blockstack; /* malloc'ed array */ +X int f_nvalues; /* size of f_valuestack */ +X int f_nblocks; /* size of f_blockstack */ +X int f_iblock; /* index in f_blockstack */ X} frameobject; X X @@ -1700,7 +1700,7 @@ X X#define is_frameobject(op) ((op)->ob_type == &Frametype) X Xframeobject * newframeobject PROTO( -X (frameobject *, codeobject *, object *, object *, int, int)); +X (frameobject *, codeobject *, object *, object *, int, int)); X X X/* The rest of the interface is specific for frame objects */ @@ -1719,8 +1719,8 @@ X#define GETUSTRINGVALUE(s) ((unsigned char *)GETSTRINGVALUE(s)) X X/* Code access macros */ X -X#define Getconst(f, i) (GETITEM((f)->f_code->co_consts, (i))) -X#define Getname(f, i) (GETITEMNAME((f)->f_code->co_names, (i))) +X#define Getconst(f, i) (GETITEM((f)->f_code->co_consts, (i))) +X#define Getname(f, i) (GETITEMNAME((f)->f_code->co_names, (i))) X X X/* Block management functions */ @@ -1738,12 +1738,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1765,46 +1765,46 @@ X X#include "structmember.h" X Xtypedef struct { -X OB_HEAD -X object *func_code; -X object *func_globals; +X OB_HEAD +X object *func_code; +X object *func_globals; X} funcobject; X Xobject * Xnewfuncobject(code, globals) -X object *code; -X object *globals; +X object *code; +X object *globals; X{ -X funcobject *op = NEWOBJ(funcobject, &Functype); -X if (op != NULL) { -X INCREF(code); -X op->func_code = code; -X INCREF(globals); -X op->func_globals = globals; -X } -X return (object *)op; +X funcobject *op = NEWOBJ(funcobject, &Functype); +X if (op != NULL) { +X INCREF(code); +X op->func_code = code; +X INCREF(globals); +X op->func_globals = globals; +X } +X return (object *)op; X} X Xobject * Xgetfunccode(op) -X object *op; +X object *op; X{ -X if (!is_funcobject(op)) { -X err_badcall(); -X return NULL; -X } -X return ((funcobject *) op) -> func_code; +X if (!is_funcobject(op)) { +X err_badcall(); +X return NULL; +X } +X return ((funcobject *) op) -> func_code; X} X Xobject * Xgetfuncglobals(op) -X object *op; +X object *op; X{ -X if (!is_funcobject(op)) { -X err_badcall(); -X return NULL; -X } -X return ((funcobject *) op) -> func_globals; +X if (!is_funcobject(op)) { +X err_badcall(); +X return NULL; +X } +X return ((funcobject *) op) -> func_globals; X} X X/* Methods */ @@ -1812,40 +1812,40 @@ X X#define OFF(x) offsetof(funcobject, x) X Xstatic struct memberlist func_memberlist[] = { -X {"func_code", T_OBJECT, OFF(func_code)}, -X {"func_globals",T_OBJECT, OFF(func_globals)}, -X {NULL} /* Sentinel */ +X {"func_code", T_OBJECT, OFF(func_code)}, +X {"func_globals",T_OBJECT, OFF(func_globals)}, +X {NULL} /* Sentinel */ X}; X Xstatic object * Xfunc_getattr(op, name) -X funcobject *op; -X char *name; +X funcobject *op; +X char *name; X{ -X return getmember((char *)op, func_memberlist, name); +X return getmember((char *)op, func_memberlist, name); X} X Xstatic void Xfunc_dealloc(op) -X funcobject *op; +X funcobject *op; X{ -X DECREF(op->func_code); -X DECREF(op->func_globals); -X DEL(op); +X DECREF(op->func_code); +X DECREF(op->func_globals); +X DEL(op); X} X Xtypeobject Functype = { -X OB_HEAD_INIT(&Typetype) -X 0, -X "function", -X sizeof(funcobject), -X 0, -X func_dealloc, /*tp_dealloc*/ -X 0, /*tp_print*/ -X func_getattr, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X 0, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, +X "function", +X sizeof(funcobject), +X 0, +X func_dealloc, /*tp_dealloc*/ +X 0, /*tp_print*/ +X func_getattr, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X 0, /*tp_repr*/ X}; EOF fi @@ -1858,12 +1858,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1885,58 +1885,58 @@ X X/* A label of an arc */ X Xtypedef struct _label { -X int lb_type; -X char *lb_str; +X int lb_type; +X char *lb_str; X} label; X -X#define EMPTY 0 /* Label number 0 is by definition the empty label */ +X#define EMPTY 0 /* Label number 0 is by definition the empty label */ X X/* A list of labels */ X Xtypedef struct _labellist { -X int ll_nlabels; -X label *ll_label; +X int ll_nlabels; +X label *ll_label; X} labellist; X X/* An arc from one state to another */ X Xtypedef struct _arc { -X short a_lbl; /* Label of this arc */ -X short a_arrow; /* State where this arc goes to */ +X short a_lbl; /* Label of this arc */ +X short a_arrow; /* State where this arc goes to */ X} arc; X X/* A state in a DFA */ X Xtypedef struct _state { -X int s_narcs; -X arc *s_arc; /* Array of arcs */ -X -X /* Optional accelerators */ -X int s_lower; /* Lowest label index */ -X int s_upper; /* Highest label index */ -X int *s_accel; /* Accelerator */ -X int s_accept; /* Nonzero for accepting state */ +X int s_narcs; +X arc *s_arc; /* Array of arcs */ +X +X /* Optional accelerators */ +X int s_lower; /* Lowest label index */ +X int s_upper; /* Highest label index */ +X int *s_accel; /* Accelerator */ +X int s_accept; /* Nonzero for accepting state */ X} state; X X/* A DFA */ X Xtypedef struct _dfa { -X int d_type; /* Non-terminal this represents */ -X char *d_name; /* For printing */ -X int d_initial; /* Initial state */ -X int d_nstates; -X state *d_state; /* Array of states */ -X bitset d_first; +X int d_type; /* Non-terminal this represents */ +X char *d_name; /* For printing */ +X int d_initial; /* Initial state */ +X int d_nstates; +X state *d_state; /* Array of states */ +X bitset d_first; X} dfa; X X/* A grammar */ X Xtypedef struct _grammar { -X int g_ndfas; -X dfa *g_dfa; /* Array of DFAs */ -X labellist g_ll; -X int g_start; /* Start symbol of the grammar */ -X int g_accel; /* Set if accelerators present */ +X int g_ndfas; +X dfa *g_dfa; /* Array of DFAs */ +X labellist g_ll; +X int g_start; /* Start symbol of the grammar */ +X int g_accel; /* Set if accelerators present */ X} grammar; X X/* FUNCTIONS */ @@ -1970,12 +1970,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1995,11 +1995,11 @@ X X/* X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 X -Xintobject represents a (long) integer. This is an immutable object; +Xintobject represents a (long) integer. This is an immutable object; Xan integer cannot change its value after creation. X XThere are functions to create new integer objects, to test an object -Xfor integer-ness, and to get the integer value. The latter functions +Xfor integer-ness, and to get the integer value. The latter functions Xreturns -1 and sets errno to EBADF if the object is not an intobject. XNone of the functions should be applied to nil objects. X @@ -2008,8 +2008,8 @@ XTrueObject and FalseObject below; don't use this. X*/ X Xtypedef struct { -X OB_HEAD -X long ob_ival; +X OB_HEAD +X long ob_ival; X} intobject; X Xextern typeobject Inttype; @@ -2049,12 +2049,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2083,12 +2083,12 @@ X Xint Xintrcheck() X{ -X int interrupted = 0; -X while (kbhit()) { -X if (getch() == '\003') -X interrupted = 1; -X } -X return interrupted; +X int interrupted = 0; +X while (kbhit()) { +X if (getch() == '\003') +X interrupted = 1; +X } +X return interrupted; X} X X#define OK @@ -2099,7 +2099,7 @@ X X#ifdef THINK_C X X/* This is for THINK C 4.0. -X For 3.0, you may have to remove the signal stuff. */ +X For 3.0, you may have to remove the signal stuff. */ X X#include <MacHeaders> X#include <signal.h> @@ -2109,44 +2109,44 @@ Xstatic int interrupted; X Xstatic SIGTYPE Xintcatcher(sig) -X int sig; +X int sig; X{ -X interrupted = 1; -X signal(SIGINT, intcatcher); +X interrupted = 1; +X signal(SIGINT, intcatcher); X} X Xvoid Xinitintr() X{ -X if (signal(SIGINT, SIG_IGN) != SIG_IGN) -X signal(SIGINT, intcatcher); +X if (signal(SIGINT, SIG_IGN) != SIG_IGN) +X signal(SIGINT, intcatcher); X} X Xint Xintrcheck() X{ -X register EvQElPtr q; -X -X /* This is like THINK C 4.0's <console.h>. -X I'm not sure why FlushEvents must be called from asm{}. */ -X for (q = (EvQElPtr)EventQueue.qHead; q; q = (EvQElPtr)q->qLink) { -X if (q->evtQWhat == keyDown && -X (char)q->evtQMessage == '.' && -X (q->evtQModifiers & cmdKey) != 0) { -X -X asm { -X moveq #keyDownMask,d0 -X _FlushEvents -X } -X interrupted = 1; -X break; -X } -X } -X if (interrupted) { -X interrupted = 0; -X return 1; -X } -X return 0; +X register EvQElPtr q; +X +X /* This is like THINK C 4.0's <console.h>. +X I'm not sure why FlushEvents must be called from asm{}. */ +X for (q = (EvQElPtr)EventQueue.qHead; q; q = (EvQElPtr)q->qLink) { +X if (q->evtQWhat == keyDown && +X (char)q->evtQMessage == '.' && +X (q->evtQModifiers & cmdKey) != 0) { +X +X asm { +X moveq #keyDownMask,d0 +X _FlushEvents +X } +X interrupted = 1; +X break; +X } +X } +X if (interrupted) { +X interrupted = 0; +X return 1; +X } +X return 0; X} X X#define OK @@ -2166,26 +2166,26 @@ Xstatic int interrupted; X Xstatic SIGTYPE Xintcatcher(sig) -X int sig; +X int sig; X{ -X interrupted = 1; -X signal(SIGINT, intcatcher); +X interrupted = 1; +X signal(SIGINT, intcatcher); X} X Xvoid Xinitintr() X{ -X if (signal(SIGINT, SIG_IGN) != SIG_IGN) -X signal(SIGINT, intcatcher); +X if (signal(SIGINT, SIG_IGN) != SIG_IGN) +X signal(SIGINT, intcatcher); X} X Xint Xintrcheck() X{ -X if (!interrupted) -X return 0; -X interrupted = 0; -X return 1; +X if (!interrupted) +X return 0; +X interrupted = 0; +X return 1; X} X X#endif /* !OK */ @@ -2200,12 +2200,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2240,94 +2240,94 @@ Xint debugging = 1; X XFILE *getopenfile() X{ -X char buf[256]; -X char *p; -X FILE *fp; -X for (;;) { -X fprintf(stderr, "File name: "); -X if (fgets(buf, sizeof buf, stdin) == NULL) { -X fprintf(stderr, "EOF\n"); -X exit(1); -X } -X p = strchr(buf, '\n'); -X if (p != NULL) -X *p = '\0'; -X if ((fp = fopen(buf, "r")) != NULL) -X break; -X fprintf(stderr, "Sorry, try again.\n"); -X } -X return fp; +X char buf[256]; +X char *p; +X FILE *fp; +X for (;;) { +X fprintf(stderr, "File name: "); +X if (fgets(buf, sizeof buf, stdin) == NULL) { +X fprintf(stderr, "EOF\n"); +X exit(1); +X } +X p = strchr(buf, '\n'); +X if (p != NULL) +X *p = '\0'; +X if ((fp = fopen(buf, "r")) != NULL) +X break; +X fprintf(stderr, "Sorry, try again.\n"); +X } +X return fp; X} X Xmain() X{ -X FILE *fp; -X _profile = 0; -X fp = getopenfile(); +X FILE *fp; +X _profile = 0; +X fp = getopenfile(); X#if 0 -X askgo("Start tokenizing"); -X runtokenizer(fp); -X fseek(fp, 0L, 0); +X askgo("Start tokenizing"); +X runtokenizer(fp); +X fseek(fp, 0L, 0); X#endif -X if (!gram.g_accel) -X addaccelerators(&gram); -X askgo("Start parsing"); -X _profile = 1; -X runparser(fp); -X _profile = 0; -X freopen("prof.out", "w", stdout); -X DumpProfile(); -X fflush(stdout); -X exit(0); +X if (!gram.g_accel) +X addaccelerators(&gram); +X askgo("Start parsing"); +X _profile = 1; +X runparser(fp); +X _profile = 0; +X freopen("prof.out", "w", stdout); +X DumpProfile(); +X fflush(stdout); +X exit(0); X} X Xstatic int Xruntokenizer(fp) -X FILE *fp; +X FILE *fp; X{ -X struct tok_state *tok; -X tok = tok_setupf(fp, "Tokenizing", "."); -X for (;;) { -X char *a, *b; -X register char *str; -X register int len; -X (void) tok_get(tok, &a, &b); -X if (tok->done != E_OK) -X break; -X len = b - a; -X str = NEW(char, len + 1); -X if (str == NULL) { -X fprintf(stderr, "no mem for next token"); -X break; -X } -X strncpy(str, a, len); -X str[len] = '\0'; -X } -X fprintf(stderr, "done (%d)\n", tok->done); +X struct tok_state *tok; +X tok = tok_setupf(fp, "Tokenizing", "."); +X for (;;) { +X char *a, *b; +X register char *str; +X register int len; +X (void) tok_get(tok, &a, &b); +X if (tok->done != E_OK) +X break; +X len = b - a; +X str = NEW(char, len + 1); +X if (str == NULL) { +X fprintf(stderr, "no mem for next token"); +X break; +X } +X strncpy(str, a, len); +X str[len] = '\0'; +X } +X fprintf(stderr, "done (%d)\n", tok->done); X} X Xstatic Xrunparser(fp, start) -X FILE *fp; +X FILE *fp; X{ -X node *n; -X int ret; -X ret = parsefile(fp, &gram, module_input, "Parsing", ".", &n); -X fprintf(stderr, "done (%d)\n", ret); +X node *n; +X int ret; +X ret = parsefile(fp, &gram, module_input, "Parsing", ".", &n); +X fprintf(stderr, "done (%d)\n", ret); X#if 0 -X _profile = 0; -X if (ret == E_DONE) -X listtree(n); +X _profile = 0; +X if (ret == E_DONE) +X listtree(n); X#endif X} X Xstatic int Xaskgo(prompt) -X char *prompt; +X char *prompt; X{ -X char buf[256]; -X fprintf(stderr, "%s: hit return when ready: ", prompt); -X fgets(buf, sizeof buf, stdin); +X char buf[256]; +X fprintf(stderr, "%s: hit return when ready: ", prompt); +X fgets(buf, sizeof buf, stdin); X} EOF fi @@ -2340,12 +2340,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2361,104 +2361,104 @@ X X******************************************************************/ X X/* -X** strtol -X** This is a general purpose routine for converting -X** an ascii string to an integer in an arbitrary base. -X** Leading white space is ignored, if 'base' is zero -X** it looks for a leading 0, 0x or 0X to tell which -X** base. If these are absent it defaults to 10. -X** Base must be between 0 and 36. -X** If 'ptr' is non-NULL it will contain a pointer to -X** the end of the scan. -X** Errors due to bad pointers will probably result in -X** exceptions - we don't check for them. +X** strtol +X** This is a general purpose routine for converting +X** an ascii string to an integer in an arbitrary base. +X** Leading white space is ignored, if 'base' is zero +X** it looks for a leading 0, 0x or 0X to tell which +X** base. If these are absent it defaults to 10. +X** Base must be between 0 and 36. +X** If 'ptr' is non-NULL it will contain a pointer to +X** the end of the scan. +X** Errors due to bad pointers will probably result in +X** exceptions - we don't check for them. X*/ X X#include "ctype.h" X Xlong Xstrtol(str, ptr, base) -Xregister char * str; -Xchar ** ptr; -Xint base; +Xregister char * str; +Xchar ** ptr; +Xint base; X{ -X register long result; /* return value of the function */ -X register int c; /* current input character */ -X int minus; /* true if a leading minus was found */ +X register long result; /* return value of the function */ +X register int c; /* current input character */ +X int minus; /* true if a leading minus was found */ X -X result = 0; -X minus = 0; +X result = 0; +X minus = 0; X X/* catch silly bases */ -X if (base < 0 || base > 36) -X { -X if (ptr) -X *ptr = str; -X return result; -X } +X if (base < 0 || base > 36) +X { +X if (ptr) +X *ptr = str; +X return result; +X } X X/* skip leading white space */ -X while (*str && isspace(*str)) -X str++; +X while (*str && isspace(*str)) +X str++; X X/* check for optional leading minus sign */ -X if (*str == '-') -X { -X minus = 1; -X str++; -X } +X if (*str == '-') +X { +X minus = 1; +X str++; +X } X X/* check for leading 0 or 0x for auto-base or base 16 */ -X switch (base) -X { -X case 0: /* look for leading 0, 0x or 0X */ -X if (*str == '0') -X { -X str++; -X if (*str == 'x' || *str == 'X') -X { -X str++; -X base = 16; -X } -X else -X base = 8; -X } -X else -X base = 10; -X break; -X -X case 16: /* skip leading 0x or 0X */ -X if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X')) -X str += 2; -X break; -X } +X switch (base) +X { +X case 0: /* look for leading 0, 0x or 0X */ +X if (*str == '0') +X { +X str++; +X if (*str == 'x' || *str == 'X') +X { +X str++; +X base = 16; +X } +X else +X base = 8; +X } +X else +X base = 10; +X break; +X +X case 16: /* skip leading 0x or 0X */ +X if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X')) +X str += 2; +X break; +X } X X/* do the conversion */ -X while (c = *str) -X { -X if (isdigit(c) && c - '0' < base) -X c -= '0'; -X else -X { -X if (isupper(c)) -X c = tolower(c); -X if (c >= 'a' && c <= 'z') -X c -= 'a' - 10; -X else /* non-"digit" character */ -X break; -X if (c >= base) /* non-"digit" character */ -X break; -X } -X result = result * base + c; -X str++; -X } +X while (c = *str) +X { +X if (isdigit(c) && c - '0' < base) +X c -= '0'; +X else +X { +X if (isupper(c)) +X c = tolower(c); +X if (c >= 'a' && c <= 'z') +X c -= 'a' - 10; +X else /* non-"digit" character */ +X break; +X if (c >= base) /* non-"digit" character */ +X break; +X } +X result = result * base + c; +X str++; +X } X X/* set pointer to point to the last character scanned */ -X if (ptr) -X *ptr = str; -X return minus ? -result : result; +X if (ptr) +X *ptr = str; +X return minus ? -result : result; X} EOF fi echo 'Part 17 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-18-21.shar b/shar/python-0.9.1-18-21.shar index 6b566e7..e78b041 100644 --- a/shar/python-0.9.1-18-21.shar +++ b/shar/python-0.9.1-18-21.shar @@ -10,10 +10,10 @@ echo 'x - demo/sgi/gl/backface.py' sed 's/^X//' > 'demo/sgi/gl/backface.py' << 'EOF' X#! /ufs/guido/bin/sgi/python X -X# backface +X# backface X# -X# draw a cube that can run with backface() turned on or off. -X# cube is moved when LEFTMOUSE is pressed and mouse itself is moved. +X# draw a cube that can run with backface() turned on or off. +X# cube is moved when LEFTMOUSE is pressed and mouse itself is moved. X Xfrom gl import * Xfrom DEVICE import * @@ -23,128 +23,128 @@ XCUBE_SIZE = 200.0 XCUBE_OBJ = 1 X Xdef main () : -X # -X x = 0 -X y = 0 -X moveit = 0 -X # -X initialize() -X # -X while (1) : -X # -X while (qtest()) : -X dev, val = qread() -X # -X if dev = ESCKEY : -X backface(0) -X return -X # -X elif dev = REDRAW : -X reshapeviewport() -X drawcube(x,y) -X # -X elif dev = LEFTMOUSE : -X # -X # LEFTMOUSE down -X moveit = val -X # -X elif dev = BKEY : -X backface(1) -X drawcube(x,y) -X # -X elif dev = FKEY : -X backface(0) -X drawcube(x,y) -X # -X if moveit : -X x = getvaluator(MOUSEX) -X y = getvaluator(MOUSEY) -X drawcube(x,y) +X # +X x = 0 +X y = 0 +X moveit = 0 +X # +X initialize() +X # +X while (1) : +X # +X while (qtest()) : +X dev, val = qread() +X # +X if dev = ESCKEY : +X backface(0) +X return +X # +X elif dev = REDRAW : +X reshapeviewport() +X drawcube(x,y) +X # +X elif dev = LEFTMOUSE : +X # +X # LEFTMOUSE down +X moveit = val +X # +X elif dev = BKEY : +X backface(1) +X drawcube(x,y) +X # +X elif dev = FKEY : +X backface(0) +X drawcube(x,y) +X # +X if moveit : +X x = getvaluator(MOUSEX) +X y = getvaluator(MOUSEY) +X drawcube(x,y) X X Xdef initialize () : -X foreground () -X keepaspect (1, 1) -X gid = winopen('backface') -X winset(gid) -X winconstraints() -X # -X doublebuffer() -X gconfig() -X shademodel(FLAT) -X # -X ortho(-1024.0, 1024.0, -1024.0, 1024.0, -1024.0, 1024.0) -X # -X qdevice(ESCKEY) -X qdevice(REDRAW) -X qdevice(LEFTMOUSE) -X qdevice(BKEY) -X qdevice(FKEY) -X qenter(REDRAW,gid) -X # -X backface(1) +X foreground () +X keepaspect (1, 1) +X gid = winopen('backface') +X winset(gid) +X winconstraints() +X # +X doublebuffer() +X gconfig() +X shademodel(FLAT) +X # +X ortho(-1024.0, 1024.0, -1024.0, 1024.0, -1024.0, 1024.0) +X # +X qdevice(ESCKEY) +X qdevice(REDRAW) +X qdevice(LEFTMOUSE) +X qdevice(BKEY) +X qdevice(FKEY) +X qenter(REDRAW,gid) +X # +X backface(1) X X# X# define a cube Xdef cube () : -X # -X # front face -X pushmatrix() -X translate(0.0,0.0,CUBE_SIZE) -X color(RED) -X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) -X popmatrix() -X # -X # right face -X pushmatrix() -X translate(CUBE_SIZE, 0.0, 0.0) -X rotate(900, 'y') -X color(GREEN) -X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) -X popmatrix() -X # -X # back face -X pushmatrix() -X translate(0.0, 0.0, -CUBE_SIZE) -X rotate(1800, 'y') -X color(BLUE) -X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) -X popmatrix() -X # -X # left face -X pushmatrix() -X translate(-CUBE_SIZE, 0.0, 0.0) -X rotate(-900, 'y') -X color(CYAN) -X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) -X popmatrix() -X # -X # top face -X pushmatrix() -X translate(0.0, CUBE_SIZE, 0.0) -X rotate(-900, 'x') -X color(MAGENTA) -X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) -X popmatrix() -X # -X # bottom face -X pushmatrix() -X translate(0.0, -CUBE_SIZE, 0.0) -X rotate(900, 'x') -X color(YELLOW) -X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) -X popmatrix() +X # +X # front face +X pushmatrix() +X translate(0.0,0.0,CUBE_SIZE) +X color(RED) +X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) +X popmatrix() +X # +X # right face +X pushmatrix() +X translate(CUBE_SIZE, 0.0, 0.0) +X rotate(900, 'y') +X color(GREEN) +X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) +X popmatrix() +X # +X # back face +X pushmatrix() +X translate(0.0, 0.0, -CUBE_SIZE) +X rotate(1800, 'y') +X color(BLUE) +X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) +X popmatrix() +X # +X # left face +X pushmatrix() +X translate(-CUBE_SIZE, 0.0, 0.0) +X rotate(-900, 'y') +X color(CYAN) +X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) +X popmatrix() +X # +X # top face +X pushmatrix() +X translate(0.0, CUBE_SIZE, 0.0) +X rotate(-900, 'x') +X color(MAGENTA) +X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) +X popmatrix() +X # +X # bottom face +X pushmatrix() +X translate(0.0, -CUBE_SIZE, 0.0) +X rotate(900, 'x') +X color(YELLOW) +X rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) +X popmatrix() X Xdef drawcube(x,y) : -X # -X pushmatrix() -X rotate(2*x, 'x') -X rotate(2*y, 'y') -X color(BLACK) -X clear() -X cube() -X popmatrix() -X swapbuffers() +X # +X pushmatrix() +X rotate(2*x, 'x') +X rotate(2*y, 'y') +X color(BLACK) +X clear() +X cube() +X popmatrix() +X swapbuffers() X X Xmain () @@ -166,7 +166,7 @@ X X>For your enjoyment I have implemented a colorful clock. X XThe clock has now been extended with some new facilities: a menu, an -Xalarm and a gong. These may require some explanation beyond what's in +Xalarm and a gong. These may require some explanation beyond what's in Xthe usage message. X XMenu @@ -177,37 +177,37 @@ X XAlarm X----- X -XThe left and middle buttons set the alarm. When it is on, the alarm +XThe left and middle buttons set the alarm. When it is on, the alarm Xtime is displayed as a time on a 24 hour clock in the bottom left -Xcorner. It is also indicated by two red triangles, corresponding to the -Xlittle (hours) and big (minutes) hand. These hands can be moved around: +Xcorner. It is also indicated by two red triangles, corresponding to the +Xlittle (hours) and big (minutes) hand. These hands can be moved around: Xthe left mouse button moves the minutes hand, the middle button moves -Xthe hourds hand. Watch out for differences of twelve hours (always +Xthe hourds hand. Watch out for differences of twelve hours (always Xcheck the digital display); these can be corrected by dragging the hours Xhand once around the dial. X XWhen the alarm goes off, two things happen: a shell command specified on Xthe command line with the -a option is executed (in the background), and -Xthe clock's colors change every two seconds, for five minutes. You can +Xthe clock's colors change every two seconds, for five minutes. You can Xalso turn the alarm off by using the menu accessible through the right Xmouse button. X XThere is no default command for the -a option; if it is not specified, -Xonly the changing of the colors happens. If you have an 8 ohm speaker +Xonly the changing of the colors happens. If you have an 8 ohm speaker Xconnected to the audio output of your Personal Iris, a suitable command Xwould be: X -X mclock -a '/ufs/guido/bin/sgi/play /ufs/guido/lib/sounds/alarm' +X mclock -a '/ufs/guido/bin/sgi/play /ufs/guido/lib/sounds/alarm' X XGong X---- X XSome people like a clock that makes noises every hour, or even more -Xoften. This is supported by the -g and -G options. With -g you specify +Xoften. This is supported by the -g and -G options. With -g you specify Xa shell command to be executed to sound the gong; with -G you can Xspecify the interval between gong calls, in seconds (default is one hour). -XThe shell command is executed in the background. It is given two -Xarguments: the hours (on a 24 hour clock!) and the minutes. The +XThe shell command is executed in the background. It is given two +Xarguments: the hours (on a 24 hour clock!) and the minutes. The Xexecutable Python script /ufs/guido/bin/sgi/chime is a suitable example. XAgain, this only works if you have installed a speaker (I bet 8 ohm Xspeakers are going to be in demand!) @@ -225,9 +225,9 @@ echo 'x - demo/sgi/gl/mixing.py' sed 's/^X//' > 'demo/sgi/gl/mixing.py' << 'EOF' X#! /ufs/guido/bin/sgi/python X -X# Use Gouraud shading to mix colors. Requires Z-buffer. +X# Use Gouraud shading to mix colors. Requires Z-buffer. X# It changes the color assignments so fast that you see white. -X# Left button pauses, middle rotates the square. ESC to quit. +X# Left button pauses, middle rotates the square. ESC to quit. X# Experiment with a larger window (too slow) or smaller window (really white). X Xfrom GL import * @@ -236,57 +236,57 @@ Ximport DEVICE Xfrom math import * X X# -X# tekenvlak : draw a square. with bgnpolygon +X# tekenvlak : draw a square. with bgnpolygon X# Xdef tekenvlak (vc) : -X bgnpolygon() -X #vcarray (vc) -X for i in vc : -X c3f (i[1]) -X v3f (i[0]) -X endpolygon() +X bgnpolygon() +X #vcarray (vc) +X for i in vc : +X c3f (i[1]) +X v3f (i[0]) +X endpolygon() X X# X# tekendoos : draw a box X# Xdef tekendoos (col) : -X 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)] -X vc = [(v[0],col[0]),(v[1],col[1]),(v[2],col[2]),(v[3],col[1])] -X tekenvlak (vc) +X 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)] +X vc = [(v[0],col[0]),(v[1],col[1]),(v[2],col[2]),(v[3],col[1])] +X tekenvlak (vc) X X# X# initialize gl X# Xdef initgl () : -X # -X # open window -X # -X foreground () -X keepaspect (1, 1) -X prefposition (100, 500, 100, 500) -X w = winopen ('PYTHON RGB') -X keepaspect (1, 1) -X winconstraints() -X # -X # configure pipeline (2buf, GOURAUD and RGBmode) -X # -X doublebuffer () -X zbuffer (1) -X shademodel (GOURAUD) -X RGBmode () -X gconfig () -X # -X # set viewing -X # -X perspective (900, 1, 1.0, 10.0) -X polarview (10.0, 0, 0, 0) -X # -X # ask for the REDRAW and ESCKEY events -X # -X qdevice(DEVICE.MOUSE2) -X qdevice(DEVICE.MOUSE3) -X qdevice(DEVICE.REDRAW) -X qdevice(DEVICE.ESCKEY) +X # +X # open window +X # +X foreground () +X keepaspect (1, 1) +X prefposition (100, 500, 100, 500) +X w = winopen ('PYTHON RGB') +X keepaspect (1, 1) +X winconstraints() +X # +X # configure pipeline (2buf, GOURAUD and RGBmode) +X # +X doublebuffer () +X zbuffer (1) +X shademodel (GOURAUD) +X RGBmode () +X gconfig () +X # +X # set viewing +X # +X perspective (900, 1, 1.0, 10.0) +X polarview (10.0, 0, 0, 0) +X # +X # ask for the REDRAW and ESCKEY events +X # +X qdevice(DEVICE.MOUSE2) +X qdevice(DEVICE.MOUSE3) +X qdevice(DEVICE.REDRAW) +X qdevice(DEVICE.ESCKEY) X X X# @@ -294,51 +294,51 @@ X# the color black X# Xblack = 0 X# -X# GoForIT : use 2buf to redraw the object 2n times. index i is used as +X# GoForIT : use 2buf to redraw the object 2n times. index i is used as X# the (smoothly changing) rotation angle X# Xdef GoForIt(i) : -X col = [(255.0,0.0,0.0), (0.0,255.0,0.0), (0.0,0.0,255.0)] -X twist = 0 -X freeze = 1 -X while 1 : -X if freeze <> 0 : -X col[0],col[1],col[2] = col[1],col[2],col[0] -X # -X # clear z-buffer and clear background to light-blue -X # -X zclear() -X cpack (black) -X clear() -X # -X tekendoos (col) -X # -X swapbuffers() -X # -X if qtest() <> 0 : -X dev, val = qread() -X if dev = DEVICE.ESCKEY : -X break -X elif dev = DEVICE.REDRAW : -X reshapeviewport () -X elif dev = DEVICE.MOUSE2 and val <> 0 : -X twist = twist + 30 -X perspective (900, 1, 1.0, 10.0) -X polarview (10.0, 0, 0, twist) -X elif dev = DEVICE.MOUSE3 and val <> 0 : -X freeze = 1 - freeze +X col = [(255.0,0.0,0.0), (0.0,255.0,0.0), (0.0,0.0,255.0)] +X twist = 0 +X freeze = 1 +X while 1 : +X if freeze <> 0 : +X col[0],col[1],col[2] = col[1],col[2],col[0] +X # +X # clear z-buffer and clear background to light-blue +X # +X zclear() +X cpack (black) +X clear() +X # +X tekendoos (col) +X # +X swapbuffers() +X # +X if qtest() <> 0 : +X dev, val = qread() +X if dev = DEVICE.ESCKEY : +X break +X elif dev = DEVICE.REDRAW : +X reshapeviewport () +X elif dev = DEVICE.MOUSE2 and val <> 0 : +X twist = twist + 30 +X perspective (900, 1, 1.0, 10.0) +X polarview (10.0, 0, 0, twist) +X elif dev = DEVICE.MOUSE3 and val <> 0 : +X freeze = 1 - freeze X X X# the main program X# Xdef main () : -X initgl () -X GoForIt (0) +X initgl () +X GoForIt (0) X X# X# exec main X# -Xmain () +Xmain () EOF chmod +x 'demo/sgi/gl/mixing.py' fi @@ -454,74 +454,74 @@ echo 'x - lib/CSplit.py' sed 's/^X//' > 'lib/CSplit.py' << 'EOF' X# A CSplit is a Clock-shaped split: the children are grouped in a circle. X# The numbering is a little different from a real clock: the 12 o'clock -X# position is called 0, not 12. This is a little easier since Python -X# usually counts from zero. (BTW, there needn't be exactly 12 children.) +X# position is called 0, not 12. This is a little easier since Python +X# usually counts from zero. (BTW, there needn't be exactly 12 children.) X X Xfrom math import pi, sin, cos Xfrom Split import Split X Xclass CSplit() = Split(): -X # -X def minsize(self, m): -X # Since things look best if the children are spaced evenly -X # along the circle (and often all children have the same -X # size anyway) we compute the max child size and assume -X # this is each child's size. -X width, height = 0, 0 -X for child in self.children: -X wi, he = child.minsize(m) -X width = max(width, wi) -X height = max(height, he) -X # In approximation, the diameter of the circle we need is -X # (diameter of box) * (#children) / pi. -X # We approximate pi by 3 (so we slightly overestimate -X # our minimal size requirements -- not so bad). -X # Because the boxes stick out of the circle we add the -X # box size to each dimension. -X # Because we really deal with ellipses, do everything -X # separate in each dimension. -X n = len(self.children) -X return width + (width*n + 2)/3, height + (height*n + 2)/3 -X # -X def getbounds(self): -X return self.bounds -X # -X def setbounds(self, bounds): -X self.bounds = bounds -X # Place the children. This involves some math. -X # Compute center positions for children as if they were -X # ellipses with a diameter about 1/N times the -X # circumference of the big ellipse. -X # (There is some rounding involved to make it look -X # reasonable for small and large N alike.) -X # XXX One day Python will have automatic conversions... -X n = len(self.children) -X fn = float(n) -X if n = 0: return -X (left, top), (right, bottom) = bounds -X width, height = right-left, bottom-top -X child_width, child_height = width*3/(n+4), height*3/(n+4) -X half_width, half_height = \ -X float(width-child_width)/2.0, \ -X float(height-child_height)/2.0 -X center_h, center_v = center = (left+right)/2, (top+bottom)/2 -X fch, fcv = float(center_h), float(center_v) -X alpha = 2.0 * pi / fn -X for i in range(n): -X child = self.children[i] -X fi = float(i) -X fh, fv = \ -X fch + half_width*sin(fi*alpha), \ -X fcv - half_height*cos(fi*alpha) -X left, top = \ -X int(fh) - child_width/2, \ -X int(fv) - child_height/2 -X right, bottom = \ -X left + child_width, \ -X top + child_height -X child.setbounds((left, top), (right, bottom)) -X # +X # +X def minsize(self, m): +X # Since things look best if the children are spaced evenly +X # along the circle (and often all children have the same +X # size anyway) we compute the max child size and assume +X # this is each child's size. +X width, height = 0, 0 +X for child in self.children: +X wi, he = child.minsize(m) +X width = max(width, wi) +X height = max(height, he) +X # In approximation, the diameter of the circle we need is +X # (diameter of box) * (#children) / pi. +X # We approximate pi by 3 (so we slightly overestimate +X # our minimal size requirements -- not so bad). +X # Because the boxes stick out of the circle we add the +X # box size to each dimension. +X # Because we really deal with ellipses, do everything +X # separate in each dimension. +X n = len(self.children) +X return width + (width*n + 2)/3, height + (height*n + 2)/3 +X # +X def getbounds(self): +X return self.bounds +X # +X def setbounds(self, bounds): +X self.bounds = bounds +X # Place the children. This involves some math. +X # Compute center positions for children as if they were +X # ellipses with a diameter about 1/N times the +X # circumference of the big ellipse. +X # (There is some rounding involved to make it look +X # reasonable for small and large N alike.) +X # XXX One day Python will have automatic conversions... +X n = len(self.children) +X fn = float(n) +X if n = 0: return +X (left, top), (right, bottom) = bounds +X width, height = right-left, bottom-top +X child_width, child_height = width*3/(n+4), height*3/(n+4) +X half_width, half_height = \ +X float(width-child_width)/2.0, \ +X float(height-child_height)/2.0 +X center_h, center_v = center = (left+right)/2, (top+bottom)/2 +X fch, fcv = float(center_h), float(center_v) +X alpha = 2.0 * pi / fn +X for i in range(n): +X child = self.children[i] +X fi = float(i) +X fh, fv = \ +X fch + half_width*sin(fi*alpha), \ +X fcv - half_height*cos(fi*alpha) +X left, top = \ +X int(fh) - child_width/2, \ +X int(fv) - child_height/2 +X right, bottom = \ +X left + child_width, \ +X top + child_height +X child.setbounds((left, top), (right, bottom)) +X # EOF fi if test -s 'lib/TransParent.py' @@ -534,97 +534,97 @@ X# First create the parent, then this thing, then the child. X# Use this as a base class for objects that are almost transparent. X# Don't use as a base class for parents with multiple children. X -XError = 'TransParent.Error' # Exception +XError = 'TransParent.Error' # Exception X Xclass ManageOneChild(): -X # -X # Upcalls shared with other single-child parents -X # -X def addchild(self, child): -X if self.child: -X raise Error, 'addchild: one child only' -X if not child: -X raise Error, 'addchild: bad child' -X self.child = child -X # -X def delchild(self, child): -X if not self.child: -X raise Error, 'delchild: no child' -X if child <> self.child: -X raise Error, 'delchild: not my child' -X self.child = 0 +X # +X # Upcalls shared with other single-child parents +X # +X def addchild(self, child): +X if self.child: +X raise Error, 'addchild: one child only' +X if not child: +X raise Error, 'addchild: bad child' +X self.child = child +X # +X def delchild(self, child): +X if not self.child: +X raise Error, 'delchild: no child' +X if child <> self.child: +X raise Error, 'delchild: not my child' +X self.child = 0 X Xclass TransParent() = ManageOneChild(): -X # -X # Calls from creator -X # NB derived classes may add parameters to create() -X # -X def create(self, parent): -X parent.addchild(self) -X self.parent = parent -X self.child = 0 # No child yet -X # -X # Downcalls from parent to child -X # -X def destroy(self): -X del self.parent -X if self.child: self.child.destroy() -X del self.child -X # -X def minsize(self, m): -X if not self.child: -X return 0, 0 -X else: -X return self.child.minsize(m) -X def getbounds(self, bounds): -X if not self.child: -X raise Error, 'getbounds w/o child' -X else: -X return self.child.getbounds() -X def setbounds(self, bounds): -X if not self.child: -X raise Error, 'setbounds w/o child' -X else: -X self.child.setbounds(bounds) -X def draw(self, args): -X if self.child: -X self.child.draw(args) -X # -X # Downcalls only made after certain upcalls -X # -X def mouse_down(self, detail): -X if self.child: self.child.mouse_down(detail) -X def mouse_move(self, detail): -X if self.child: self.child.mouse_move(detail) -X def mouse_up(self, detail): -X if self.child: self.child.mouse_up(detail) -X # -X def timer(self): -X if self.child: self.child.timer() -X # -X # Upcalls from child to parent -X # -X def need_mouse(self, child): -X self.parent.need_mouse(self) -X def no_mouse(self, child): -X self.parent.no_mouse(self) -X # -X def need_timer(self, child): -X self.parent.need_timer(self) -X def no_timer(self, child): -X self.parent.no_timer(self) -X # -X def begindrawing(self): -X return self.parent.begindrawing() -X def beginmeasuring(self): -X return self.parent.beginmeasuring() -X # -X def change(self, area): -X self.parent.change(area) -X def scroll(self, args): -X self.parent.scroll(args) -X def settimer(self, itimer): -X self.parent.settimer(itimer) +X # +X # Calls from creator +X # NB derived classes may add parameters to create() +X # +X def create(self, parent): +X parent.addchild(self) +X self.parent = parent +X self.child = 0 # No child yet +X # +X # Downcalls from parent to child +X # +X def destroy(self): +X del self.parent +X if self.child: self.child.destroy() +X del self.child +X # +X def minsize(self, m): +X if not self.child: +X return 0, 0 +X else: +X return self.child.minsize(m) +X def getbounds(self, bounds): +X if not self.child: +X raise Error, 'getbounds w/o child' +X else: +X return self.child.getbounds() +X def setbounds(self, bounds): +X if not self.child: +X raise Error, 'setbounds w/o child' +X else: +X self.child.setbounds(bounds) +X def draw(self, args): +X if self.child: +X self.child.draw(args) +X # +X # Downcalls only made after certain upcalls +X # +X def mouse_down(self, detail): +X if self.child: self.child.mouse_down(detail) +X def mouse_move(self, detail): +X if self.child: self.child.mouse_move(detail) +X def mouse_up(self, detail): +X if self.child: self.child.mouse_up(detail) +X # +X def timer(self): +X if self.child: self.child.timer() +X # +X # Upcalls from child to parent +X # +X def need_mouse(self, child): +X self.parent.need_mouse(self) +X def no_mouse(self, child): +X self.parent.no_mouse(self) +X # +X def need_timer(self, child): +X self.parent.need_timer(self) +X def no_timer(self, child): +X self.parent.no_timer(self) +X # +X def begindrawing(self): +X return self.parent.begindrawing() +X def beginmeasuring(self): +X return self.parent.beginmeasuring() +X # +X def change(self, area): +X self.parent.change(area) +X def scroll(self, args): +X self.parent.scroll(args) +X def settimer(self, itimer): +X self.parent.settimer(itimer) EOF fi if test -s 'lib/auds.py' @@ -638,106 +638,106 @@ XRATE = 8192 X X# Initialize the audio stuff Xaudio.setrate(3) -Xaudio.setoutgain(100) # for speaker +Xaudio.setoutgain(100) # for speaker X Xplay = audio.write X Xdef samp(n): -X savegain = audio.getoutgain() -X try: -X audio.setoutgain(0) -X x = raw_input('Hit Enter to sample ' + `n` + ' seconds: ') -X return audio.read(n*RATE) -X finally: -X audio.setoutgain(savegain) +X savegain = audio.getoutgain() +X try: +X audio.setoutgain(0) +X x = raw_input('Hit Enter to sample ' + `n` + ' seconds: ') +X return audio.read(n*RATE) +X finally: +X audio.setoutgain(savegain) X Xdef echo(s, delay, gain): -X return s[:delay] + audio.add(s[delay:], audio.amplify(s, gain, gain)) +X return s[:delay] + audio.add(s[delay:], audio.amplify(s, gain, gain)) X Xdef save(s, file): -X f = open(file, 'w') -X f.write(s) +X f = open(file, 'w') +X f.write(s) X Xdef load(file): -X return loadfp(open(file, 'r')) +X return loadfp(open(file, 'r')) X Xdef loadfp(fp): -X s = '' -X while 1: -X buf = fp.read(16*1024) -X if not buf: break -X s = s + buf -X return s +X s = '' +X while 1: +X buf = fp.read(16*1024) +X if not buf: break +X s = s + buf +X return s X Xdef unbias(s): -X if not s: return s -X a = audio.chr2num(s) -X sum = 0 -X for i in a: sum = sum + i -X bias = (sum + len(a)/2) / len(a) -X print 'Bias value:', bias -X if bias: -X for i in range(len(a)): -X a[i] = a[i] - bias -X s = audio.num2chr(a) -X return s +X if not s: return s +X a = audio.chr2num(s) +X sum = 0 +X for i in a: sum = sum + i +X bias = (sum + len(a)/2) / len(a) +X print 'Bias value:', bias +X if bias: +X for i in range(len(a)): +X a[i] = a[i] - bias +X s = audio.num2chr(a) +X return s X X# Stretch by a/b. X# Think of this as converting the sampling rate from a samples/sec -X# to b samples/sec. Or, if the input is a bytes long, the output +X# to b samples/sec. Or, if the input is a bytes long, the output X# will be b bytes long. X# Xdef stretch(s, a, b): -X y = audio.chr2num(s) -X m = len(y) -X out = [] -X n = m * b / a -X # i, j will walk through y and out (step 1) -X # ib, ja are i*b, j*a and are kept as close together as possible -X i, ib = 0, 0 -X j, ja = 0, 0 -X for j in range(n): -X ja = ja+a -X while ib < ja: -X i = i+1 -X ib = ib+b -X if i >= m: -X break -X if ib = ja: -X out.append(y[i]) -X else: -X out.append((y[i]*(ja-(ib-b)) + y[i-1]*(ib-ja)) / b) -X return audio.num2chr(out) +X y = audio.chr2num(s) +X m = len(y) +X out = [] +X n = m * b / a +X # i, j will walk through y and out (step 1) +X # ib, ja are i*b, j*a and are kept as close together as possible +X i, ib = 0, 0 +X j, ja = 0, 0 +X for j in range(n): +X ja = ja+a +X while ib < ja: +X i = i+1 +X ib = ib+b +X if i >= m: +X break +X if ib = ja: +X out.append(y[i]) +X else: +X out.append((y[i]*(ja-(ib-b)) + y[i-1]*(ib-ja)) / b) +X return audio.num2chr(out) X Xdef sinus(freq): # return a 1-second sine wave -X from math import sin, pi -X factor = 2.0*pi*float(freq)/float(RATE) -X list = range(RATE) -X for i in list: -X list[i] = int(sin(float(i) * factor) * 127.0) -X return audio.num2chr(list) +X from math import sin, pi +X factor = 2.0*pi*float(freq)/float(RATE) +X list = range(RATE) +X for i in list: +X list[i] = int(sin(float(i) * factor) * 127.0) +X return audio.num2chr(list) X Xdef softclip(s): -X if '\177' not in s and '\200' not in s: -X return s -X num = audio.chr2num(s) -X extremes = (-128, 127) -X for i in range(1, len(num)-1): -X if num[i] in extremes: -X num[i] = (num[i-1] + num[i+1]) / 2 -X return audio.num2chr(num) +X if '\177' not in s and '\200' not in s: +X return s +X num = audio.chr2num(s) +X extremes = (-128, 127) +X for i in range(1, len(num)-1): +X if num[i] in extremes: +X num[i] = (num[i-1] + num[i+1]) / 2 +X return audio.num2chr(num) X Xdef demo(): -X gday = load('gday')[1000:6000] -X save(gday, 'gday0') -X gg = [gday] -X for i in range(1, 10): -X for g in gg: play(g) -X g = stretch(gday, 10, 10-i) -X save(g, 'gday' + `i`) -X gg.append(g) -X while 1: -X for g in gg: play(g) +X gday = load('gday')[1000:6000] +X save(gday, 'gday0') +X gg = [gday] +X for i in range(1, 10): +X for g in gg: play(g) +X g = stretch(gday, 10, 10-i) +X save(g, 'gday' + `i`) +X gg.append(g) +X while 1: +X for g in gg: play(g) EOF fi if test -s 'lib/listwin.py' @@ -752,46 +752,46 @@ Ximport gwin Ximport stdwin X Xdef maxlinewidth(a): # Compute maximum textwidth of lines in a sequence -X max = 0 -X for line in a: -X width = stdwin.textwidth(line) -X if width > max: max = width -X return max +X max = 0 +X for line in a: +X width = stdwin.textwidth(line) +X if width > max: max = width +X return max X Xdef action(w, string, i, detail): # Default item selection method -X pass +X pass X Xdef mup(w, detail): # Mouse up method -X (h, v), clicks, button, mask = detail -X i = divmod(v, w.lineheight)[0] -X if 0 <= i < len(w.data): -X w.action(w, w.data[i], i, detail) +X (h, v), clicks, button, mask = detail +X i = divmod(v, w.lineheight)[0] +X if 0 <= i < len(w.data): +X w.action(w, w.data[i], i, detail) X Xdef draw(w, ((left, top), (right, bottom))): # Text window draw method -X data = w.data -X d = w.begindrawing() -X lh = w.lineheight -X itop = top/lh -X ibot = (bottom-1)/lh + 1 -X if itop < 0: itop = 0 -X if ibot > len(data): ibot = len(data) -X for i in range(itop, ibot): d.text((0, i*lh), data[i]) +X data = w.data +X d = w.begindrawing() +X lh = w.lineheight +X itop = top/lh +X ibot = (bottom-1)/lh + 1 +X if itop < 0: itop = 0 +X if ibot > len(data): ibot = len(data) +X for i in range(itop, ibot): d.text((0, i*lh), data[i]) X Xdef open(title, data): # Display a list of texts in a window -X lineheight = stdwin.lineheight() -X h, v = maxlinewidth(data), len(data)*lineheight -X h0, v0 = h + stdwin.textwidth(' '), v + lineheight -X if h0 > stdwin.textwidth(' ')*80: h0 = 0 -X if v0 > stdwin.lineheight()*24: v0 = 0 -X stdwin.setdefwinsize(h0, v0) -X w = gwin.open(title) -X w.setdocsize(h, v) -X w.lineheight = lineheight -X w.data = data -X w.draw = draw -X w.action = action -X w.mup = mup -X return w +X lineheight = stdwin.lineheight() +X h, v = maxlinewidth(data), len(data)*lineheight +X h0, v0 = h + stdwin.textwidth(' '), v + lineheight +X if h0 > stdwin.textwidth(' ')*80: h0 = 0 +X if v0 > stdwin.lineheight()*24: v0 = 0 +X stdwin.setdefwinsize(h0, v0) +X w = gwin.open(title) +X w.setdocsize(h, v) +X w.lineheight = lineheight +X w.data = data +X w.draw = draw +X w.action = action +X w.mup = mup +X return w EOF fi if test -s 'lib/macpath.py' @@ -813,7 +813,7 @@ X# Anything else is absolute (the string up to the first colon is the X# volume name). X Xdef isabs(s): -X return ':' in s and s[0] <> ':' +X return ':' in s and s[0] <> ':' X X X# Concatenate two pathnames. @@ -821,13 +821,13 @@ X# The result is equivalent to what the second pathname would refer to X# if the first pathname were the current directory. X Xdef cat(s, t): -X if (not s) or isabs(t): return t -X if t[:1] = ':': t = t[1:] -X if ':' not in s: -X s = ':' + s -X if s[-1:] <> ':': -X s = s + ':' -X return s + t +X if (not s) or isabs(t): return t +X if t[:1] = ':': t = t[1:] +X if ':' not in s: +X s = ':' + s +X if s[-1:] <> ':': +X s = s + ':' +X return s + t X X X# Split a pathname in two parts: the directory leading up to the final bit, @@ -835,11 +835,11 @@ X# and the basename (the filename, without colons, in that directory). X# The result (s, t) is such that cat(s, t) yields the original argument. X Xdef split(s): -X if ':' not in s: return '', s -X colon = 0 -X for i in range(len(s)): -X if s[i] = ':': colon = i+1 -X return s[:colon], s[colon:] +X if ':' not in s: return '', s +X colon = 0 +X for i in range(len(s)): +X if s[i] = ':': colon = i+1 +X return s[:colon], s[colon:] X X X# Normalize a pathname: get rid of '::' sequences by backing up, @@ -850,63 +850,63 @@ X Xnorm_error = 'macpath.norm_error: path cannot be normalized' X Xdef norm(s): -X import string -X if ':' not in s: -X return ':' + s -X f = string.splitfields(s, ':') -X pre = [] -X post = [] -X if not f[0]: -X pre = f[:1] -X f = f[1:] -X if not f[len(f)-1]: -X post = f[-1:] -X f = f[:-1] -X res = [] -X for seg in f: -X if seg: -X res.append(seg) -X else: -X if not res: raise norm_error, 'path starts with ::' -X del res[len(res)-1] -X if not (pre or res): -X raise norm_error, 'path starts with volume::' -X if pre: res = pre + res -X if post: res = res + post -X s = res[0] -X for seg in res[1:]: -X s = s + ':' + seg -X return s +X import string +X if ':' not in s: +X return ':' + s +X f = string.splitfields(s, ':') +X pre = [] +X post = [] +X if not f[0]: +X pre = f[:1] +X f = f[1:] +X if not f[len(f)-1]: +X post = f[-1:] +X f = f[:-1] +X res = [] +X for seg in f: +X if seg: +X res.append(seg) +X else: +X if not res: raise norm_error, 'path starts with ::' +X del res[len(res)-1] +X if not (pre or res): +X raise norm_error, 'path starts with volume::' +X if pre: res = pre + res +X if post: res = res + post +X s = res[0] +X for seg in res[1:]: +X s = s + ':' + seg +X return s X X X# Return true if the pathname refers to an existing directory. X Xdef isdir(s): -X try: -X st = mac.stat(s) -X except mac.error: -X return 0 -X return S_ISDIR(st[ST_MODE]) +X try: +X st = mac.stat(s) +X except mac.error: +X return 0 +X return S_ISDIR(st[ST_MODE]) X X X# Return true if the pathname refers to an existing regular file. X Xdef isfile(s): -X try: -X st = mac.stat(s) -X except mac.error: -X return 0 -X return S_ISREG(st[ST_MODE]) +X try: +X st = mac.stat(s) +X except mac.error: +X return 0 +X return S_ISREG(st[ST_MODE]) X X X# Return true if the pathname refers to an existing file or directory. X Xdef exists(s): -X try: -X st = mac.stat(s) -X except mac.error: -X return 0 -X return 1 +X try: +X st = mac.stat(s) +X except mac.error: +X return 0 +X return 1 EOF fi if test -s 'lib/textwin.py' @@ -922,117 +922,117 @@ Ximport stdwin Ximport stdwinsupport Ximport gwin X -XS = stdwinsupport # Shorthand +XS = stdwinsupport # Shorthand X X Xdef fixsize(w): -X docwidth, docheight = w.text.getrect()[1] -X winheight = w.getwinsize()[1] -X if winheight > docheight: docheight = winheight -X w.setdocsize(0, docheight) -X fixeditmenu(w) +X docwidth, docheight = w.text.getrect()[1] +X winheight = w.getwinsize()[1] +X if winheight > docheight: docheight = winheight +X w.setdocsize(0, docheight) +X fixeditmenu(w) X Xdef cut(w, m, id): -X s = w.text.getfocustext() -X if s: -X stdwin.setcutbuffer(0, s) -X w.text.replace('') -X fixsize(w) +X s = w.text.getfocustext() +X if s: +X stdwin.setcutbuffer(0, s) +X w.text.replace('') +X fixsize(w) X Xdef copy(w, m, id): -X s = w.text.getfocustext() -X if s: -X stdwin.setcutbuffer(0, s) -X fixeditmenu(w) +X s = w.text.getfocustext() +X if s: +X stdwin.setcutbuffer(0, s) +X fixeditmenu(w) X Xdef paste(w, m, id): -X w.text.replace(stdwin.getcutbuffer(0)) -X fixsize(w) +X w.text.replace(stdwin.getcutbuffer(0)) +X fixsize(w) X Xdef addeditmenu(w): -X m = w.editmenu = w.menucreate('Edit') -X m.action = [] -X m.additem('Cut', 'X') -X m.action.append(cut) -X m.additem('Copy', 'C') -X m.action.append(copy) -X m.additem('Paste', 'V') -X m.action.append(paste) +X m = w.editmenu = w.menucreate('Edit') +X m.action = [] +X m.additem('Cut', 'X') +X m.action.append(cut) +X m.additem('Copy', 'C') +X m.action.append(copy) +X m.additem('Paste', 'V') +X m.action.append(paste) X Xdef fixeditmenu(w): -X m = w.editmenu -X f = w.text.getfocus() -X can_copy = (f[0] < f[1]) -X m.enable(1, can_copy) -X if not w.readonly: -X m.enable(0, can_copy) -X m.enable(2, (stdwin.getcutbuffer(0) <> '')) -X -Xdef draw(w, area): # Draw method -X w.text.draw(area) -X -Xdef size(w, newsize): # Size method -X w.text.move((0, 0), newsize) -X fixsize(w) -X -Xdef close(w): # Close method -X del w.text # Break circular ref -X gwin.close(w) -X -Xdef char(w, c): # Char method -X w.text.replace(c) -X fixsize(w) -X -Xdef backspace(w): # Backspace method -X void = w.text.event(S.we_command, w, S.wc_backspace) -X fixsize(w) -X -Xdef arrow(w, detail): # Arrow method -X w.text.arrow(detail) -X fixeditmenu(w) -X -Xdef mdown(w, detail): # Mouse down method -X void = w.text.event(S.we_mouse_down, w, detail) -X fixeditmenu(w) -X -Xdef mmove(w, detail): # Mouse move method -X void = w.text.event(S.we_mouse_move, w, detail) -X -Xdef mup(w, detail): # Mouse up method -X void = w.text.event(S.we_mouse_up, w, detail) -X fixeditmenu(w) -X -Xdef activate(w): # Activate method -X fixeditmenu(w) -X -Xdef open(title, str): # Display a string in a window -X w = gwin.open(title) -X w.readonly = 0 -X w.text = w.textcreate((0, 0), w.getwinsize()) -X w.text.replace(str) -X w.text.setfocus(0, 0) -X addeditmenu(w) -X fixsize(w) -X w.draw = draw -X w.size = size -X w.close = close -X w.mdown = mdown -X w.mmove = mmove -X w.mup = mup -X w.char = char -X w.backspace = backspace -X w.arrow = arrow -X w.activate = activate -X return w -X -Xdef open_readonly(title, str): # Same with char input disabled -X w = open(title, str) -X w.readonly = 1 -X w.char = w.backspace = gwin.nop -X # Disable Cut and Paste menu item; leave Copy alone -X w.editmenu.enable(0, 0) -X w.editmenu.enable(2, 0) -X return w +X m = w.editmenu +X f = w.text.getfocus() +X can_copy = (f[0] < f[1]) +X m.enable(1, can_copy) +X if not w.readonly: +X m.enable(0, can_copy) +X m.enable(2, (stdwin.getcutbuffer(0) <> '')) +X +Xdef draw(w, area): # Draw method +X w.text.draw(area) +X +Xdef size(w, newsize): # Size method +X w.text.move((0, 0), newsize) +X fixsize(w) +X +Xdef close(w): # Close method +X del w.text # Break circular ref +X gwin.close(w) +X +Xdef char(w, c): # Char method +X w.text.replace(c) +X fixsize(w) +X +Xdef backspace(w): # Backspace method +X void = w.text.event(S.we_command, w, S.wc_backspace) +X fixsize(w) +X +Xdef arrow(w, detail): # Arrow method +X w.text.arrow(detail) +X fixeditmenu(w) +X +Xdef mdown(w, detail): # Mouse down method +X void = w.text.event(S.we_mouse_down, w, detail) +X fixeditmenu(w) +X +Xdef mmove(w, detail): # Mouse move method +X void = w.text.event(S.we_mouse_move, w, detail) +X +Xdef mup(w, detail): # Mouse up method +X void = w.text.event(S.we_mouse_up, w, detail) +X fixeditmenu(w) +X +Xdef activate(w): # Activate method +X fixeditmenu(w) +X +Xdef open(title, str): # Display a string in a window +X w = gwin.open(title) +X w.readonly = 0 +X w.text = w.textcreate((0, 0), w.getwinsize()) +X w.text.replace(str) +X w.text.setfocus(0, 0) +X addeditmenu(w) +X fixsize(w) +X w.draw = draw +X w.size = size +X w.close = close +X w.mdown = mdown +X w.mmove = mmove +X w.mup = mup +X w.char = char +X w.backspace = backspace +X w.arrow = arrow +X w.activate = activate +X return w +X +Xdef open_readonly(title, str): # Same with char input disabled +X w = open(title, str) +X w.readonly = 1 +X w.char = w.backspace = gwin.nop +X # Disable Cut and Paste menu item; leave Copy alone +X w.editmenu.enable(0, 0) +X w.editmenu.enable(2, 0) +X return w EOF fi if test -s 'lib/zmod.py' @@ -1043,7 +1043,7 @@ sed 's/^X//' > 'lib/zmod.py' << 'EOF' X# module 'zmod' X X# Compute properties of mathematical "fields" formed by taking -X# Z/n (the whole numbers modulo some whole number n) and an +X# Z/n (the whole numbers modulo some whole number n) and an X# irreducible polynomial (i.e., a polynomial with only complex zeros), X# e.g., Z/5 and X**2 + 2. X# @@ -1052,11 +1052,11 @@ X# a set of d base vectors (where d is the degree of the polynomial). X# X# Note that this procedure doesn't yield a field for all combinations X# of n and p: it may well be that some numbers have more than one -X# inverse and others have none. This is what we check. +X# inverse and others have none. This is what we check. X# X# Remember that a field is a ring where each element has an inverse. X# A ring has commutative addition and multiplication, a zero and a one: -X# 0*x = x*0 = 0, 0+x = x+0 = x, 1*x = x*1 = x. Also, the distributive +X# 0*x = x*0 = 0, 0+x = x+0 = x, 1*x = x*1 = x. Also, the distributive X# property holds: a*(b+c) = a*b + b*c. X# (XXX I forget if this is an axiom or follows from the rules.) X @@ -1069,71 +1069,71 @@ XN = 5 XP = poly.plus(poly.one(0, 2), poly.one(2, 1)) # 2 + x**2 X X -X# Return x modulo y. Returns >= 0 even if x < 0. +X# Return x modulo y. Returns >= 0 even if x < 0. X Xdef mod(x, y): -X return divmod(x, y)[1] +X return divmod(x, y)[1] X X X# Normalize a polynomial modulo n and modulo p. X Xdef norm(a, n, p): -X a = poly.modulo(a, p) -X a = a[:] -X for i in range(len(a)): a[i] = mod(a[i], n) -X a = poly.normalize(a) -X return a +X a = poly.modulo(a, p) +X a = a[:] +X for i in range(len(a)): a[i] = mod(a[i], n) +X a = poly.normalize(a) +X return a X X X# Make a list of all n^d elements of the proposed field. X Xdef make_all(mat): -X all = [] -X for row in mat: -X for a in row: -X all.append(a) -X return all +X all = [] +X for row in mat: +X for a in row: +X all.append(a) +X return all X Xdef make_elements(n, d): -X if d = 0: return [poly.one(0, 0)] -X sub = make_elements(n, d-1) -X all = [] -X for a in sub: -X for i in range(n): -X all.append(poly.plus(a, poly.one(d-1, i))) -X return all +X if d = 0: return [poly.one(0, 0)] +X sub = make_elements(n, d-1) +X all = [] +X for a in sub: +X for i in range(n): +X all.append(poly.plus(a, poly.one(d-1, i))) +X return all X Xdef make_inv(all, n, p): -X x = poly.one(1, 1) -X inv = [] -X for a in all: -X inv.append(norm(poly.times(a, x), n, p)) -X return inv +X x = poly.one(1, 1) +X inv = [] +X for a in all: +X inv.append(norm(poly.times(a, x), n, p)) +X return inv X Xdef checkfield(n, p): -X all = make_elements(n, len(p)-1) -X inv = make_inv(all, n, p) -X all1 = all[:] -X inv1 = inv[:] -X all1.sort() -X inv1.sort() -X if all1 = inv1: print 'BINGO!' -X else: -X print 'Sorry:', n, p -X print all -X print inv +X all = make_elements(n, len(p)-1) +X inv = make_inv(all, n, p) +X all1 = all[:] +X inv1 = inv[:] +X all1.sort() +X inv1.sort() +X if all1 = inv1: print 'BINGO!' +X else: +X print 'Sorry:', n, p +X print all +X print inv X Xdef rj(s, width): -X if type(s) <> type(''): s = `s` -X n = len(s) -X if n >= width: return s -X return ' '*(width - n) + s +X if type(s) <> type(''): s = `s` +X n = len(s) +X if n >= width: return s +X return ' '*(width - n) + s X Xdef lj(s, width): -X if type(s) <> type(''): s = `s` -X n = len(s) -X if n >= width: return s -X return s + ' '*(width - n) +X if type(s) <> type(''): s = `s` +X n = len(s) +X if n >= width: return s +X return s + ' '*(width - n) EOF fi if test -s 'src/PROTO.h' @@ -1145,12 +1145,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1168,13 +1168,13 @@ X X/* XThe macro PROTO(x) is used to put function prototypes in the source. XThis is defined differently for compilers that support prototypes than -Xfor compilers that don't. It should be used as follows: -X int some_function PROTO((int arg1, char *arg2)); +Xfor compilers that don't. It should be used as follows: +X int some_function PROTO((int arg1, char *arg2)); XA variant FPROTO(x) is used for cases where Standard C allows prototypes Xbut Think C doesn't (mostly function pointers). X XThis file also defines the macro HAVE_PROTOTYPES if and only if -Xthe PROTO() macro expands the prototype. It is also allowed to predefine +Xthe PROTO() macro expands the prototype. It is also allowed to predefine XHAVE_PROTOTYPES to force prototypes on. X*/ X @@ -1231,12 +1231,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1258,73 +1258,73 @@ X#include "bitset.h" X Xbitset Xnewbitset(nbits) -X int nbits; +X int nbits; X{ -X int nbytes = NBYTES(nbits); -X bitset ss = NEW(BYTE, nbytes); -X -X if (ss == NULL) -X fatal("no mem for bitset"); -X -X ss += nbytes; -X while (--nbytes >= 0) -X *--ss = 0; -X return ss; +X int nbytes = NBYTES(nbits); +X bitset ss = NEW(BYTE, nbytes); +X +X if (ss == NULL) +X fatal("no mem for bitset"); +X +X ss += nbytes; +X while (--nbytes >= 0) +X *--ss = 0; +X return ss; X} X Xvoid Xdelbitset(ss) -X bitset ss; +X bitset ss; X{ -X DEL(ss); +X DEL(ss); X} X Xint Xaddbit(ss, ibit) -X bitset ss; -X int ibit; +X bitset ss; +X int ibit; X{ -X int ibyte = BIT2BYTE(ibit); -X BYTE mask = BIT2MASK(ibit); -X -X if (ss[ibyte] & mask) -X return 0; /* Bit already set */ -X ss[ibyte] |= mask; -X return 1; +X int ibyte = BIT2BYTE(ibit); +X BYTE mask = BIT2MASK(ibit); +X +X if (ss[ibyte] & mask) +X return 0; /* Bit already set */ +X ss[ibyte] |= mask; +X return 1; X} X X#if 0 /* Now a macro */ Xint Xtestbit(ss, ibit) -X bitset ss; -X int ibit; +X bitset ss; +X int ibit; X{ -X return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; +X return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; X} X#endif X Xint Xsamebitset(ss1, ss2, nbits) -X bitset ss1, ss2; -X int nbits; +X bitset ss1, ss2; +X int nbits; X{ -X int i; -X -X for (i = NBYTES(nbits); --i >= 0; ) -X if (*ss1++ != *ss2++) -X return 0; -X return 1; +X int i; +X +X for (i = NBYTES(nbits); --i >= 0; ) +X if (*ss1++ != *ss2++) +X return 0; +X return 1; X} X Xvoid Xmergebitset(ss1, ss2, nbits) -X bitset ss1, ss2; -X int nbits; +X bitset ss1, ss2; +X int nbits; X{ -X int i; -X -X for (i = NBYTES(nbits); --i >= 0; ) -X *ss1++ |= *ss2++; +X int i; +X +X for (i = NBYTES(nbits); --i >= 0; ) +X *ss1++ |= *ss2++; X} EOF fi @@ -1337,12 +1337,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1369,21 +1369,21 @@ X#endif X Xvoid Xinitargs(p_argc, p_argv) -X int *p_argc; -X char ***p_argv; +X int *p_argc; +X char ***p_argv; X{ X#ifdef USE_STDWIN X X#ifdef THINK_C_3_0 -X wsetstdio(1); +X wsetstdio(1); X#else -X /* This printf() statement is really needed only -X to initialize THINK C 4.0's stdio: */ -X printf( +X /* This printf() statement is really needed only +X to initialize THINK C 4.0's stdio: */ +X printf( X"Python 4.0, Copyright 1990 Stichting Mathematisch Centrum, Amsterdam\n"); X#endif X -X wargs(p_argc, p_argv); +X wargs(p_argc, p_argv); X#endif X} X @@ -1396,7 +1396,7 @@ Xvoid Xdonecalls() X{ X#ifdef USE_STDWIN -X wdone(); +X wdone(); X#endif X} X @@ -1408,18 +1408,18 @@ X Xchar * Xgetpythonpath() X{ -X return PYTHONPATH; +X return PYTHONPATH; X} X X X/* Table of built-in modules. -X These are initialized when first imported. */ +X These are initialized when first imported. */ X X/* Standard modules */ Xextern void inittime(); Xextern void initmath(); Xextern void initregexp(); -X +X X/* Mac-specific modules */ Xextern void initmac(); X#ifdef USE_STDWIN @@ -1427,20 +1427,20 @@ Xextern void initstdwin(); X#endif X Xstruct { -X char *name; -X void (*initfunc)(); +X char *name; +X void (*initfunc)(); X} inittab[] = { -X /* Standard modules */ -X {"time", inittime}, -X {"math", initmath}, -X {"regexp", initregexp}, -X -X /* Mac-specific modules */ -X {"mac", initmac}, +X /* Standard modules */ +X {"time", inittime}, +X {"math", initmath}, +X {"regexp", initregexp}, +X +X /* Mac-specific modules */ +X {"mac", initmac}, X#ifdef USE_STDWIN -X {"stdwin", initstdwin}, +X {"stdwin", initstdwin}, X#endif -X {0, 0} /* Sentinel */ +X {0, 0} /* Sentinel */ X}; EOF fi @@ -1453,12 +1453,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1474,10 +1474,10 @@ X X******************************************************************/ X X/* Interruptable version of fgets(). -X Return < 0 for interrupted, 1 for EOF, 0 for valid input. */ +X Return < 0 for interrupted, 1 for EOF, 0 for valid input. */ X X/* XXX This uses longjmp() from a signal out of fgets(). -X Should use read() instead?! */ +X Should use read() instead?! */ X X#include "pgenheaders.h" X @@ -1489,8 +1489,8 @@ X#include "sigtype.h" X#include "fgetsintr.h" X X#ifndef AMOEBA -X#define sig_block() /*empty*/ -X#define sig_unblock() /*empty*/ +X#define sig_block() /*empty*/ +X#define sig_unblock() /*empty*/ X#endif X Xstatic jmp_buf jback; @@ -1499,49 +1499,49 @@ Xstatic void catcher PROTO((int)); X Xstatic void Xcatcher(sig) -X int sig; +X int sig; X{ -X longjmp(jback, 1); +X longjmp(jback, 1); X} X Xint Xfgets_intr(buf, size, fp) -X char *buf; -X int size; -X FILE *fp; +X char *buf; +X int size; +X FILE *fp; X{ -X int ret; -X SIGTYPE (*sigsave)(); -X -X if (setjmp(jback)) { -X clearerr(fp); -X signal(SIGINT, sigsave); +X int ret; +X SIGTYPE (*sigsave)(); +X +X if (setjmp(jback)) { +X clearerr(fp); +X signal(SIGINT, sigsave); X#ifdef THINK_C_3_0 -X Set_Echo(1); +X Set_Echo(1); X#endif -X return E_INTR; -X } -X -X /* The casts to (SIGTYPE(*)()) are needed by THINK_C only */ -X -X sigsave = signal(SIGINT, (SIGTYPE(*)()) SIG_IGN); -X if (sigsave != (SIGTYPE(*)()) SIG_IGN) -X signal(SIGINT, (SIGTYPE(*)()) catcher); -X +X return E_INTR; +X } +X +X /* The casts to (SIGTYPE(*)()) are needed by THINK_C only */ +X +X sigsave = signal(SIGINT, (SIGTYPE(*)()) SIG_IGN); +X if (sigsave != (SIGTYPE(*)()) SIG_IGN) +X signal(SIGINT, (SIGTYPE(*)()) catcher); +X X#ifndef THINK_C -X if (intrcheck()) -X ret = E_INTR; -X else +X if (intrcheck()) +X ret = E_INTR; +X else X#endif -X { -X sig_block(); -X ret = (fgets(buf, size, fp) == NULL) ? E_EOF : E_OK; -X sig_unblock(); -X } -X -X if (sigsave != (SIGTYPE(*)()) SIG_IGN) -X signal(SIGINT, (SIGTYPE(*)()) sigsave); -X return ret; +X { +X sig_block(); +X ret = (fgets(buf, size, fp) == NULL) ? E_EOF : E_OK; +X sig_unblock(); +X } +X +X if (sigsave != (SIGTYPE(*)()) SIG_IGN) +X signal(SIGINT, (SIGTYPE(*)()) sigsave); +X return ret; X} EOF fi @@ -1554,12 +1554,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1575,7 +1575,7 @@ X X******************************************************************/ X X/* Two PD getcwd() implementations. -X Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <[email protected]>. */ +X Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <[email protected]>. */ X X/* #define NO_GETWD /* Turn this on to popen pwd instead of calling getwd() */ X @@ -1594,27 +1594,27 @@ Xextern char *getwd(); X Xchar * Xgetcwd(buf, size) -X char *buf; -X int size; +X char *buf; +X int size; X{ -X char localbuf[MAXPATHLEN+1]; -X char *ret; -X -X if (size <= 0) { -X errno = EINVAL; -X return NULL; -X } -X ret = getwd(localbuf); -X if (ret != NULL && strlen(localbuf) >= size) { -X errno = ERANGE; -X return NULL; -X } -X if (ret == NULL) { -X errno = EACCES; /* Most likely error */ -X return NULL; -X } -X strncpy(buf, localbuf, size); -X return buf; +X char localbuf[MAXPATHLEN+1]; +X char *ret; +X +X if (size <= 0) { +X errno = EINVAL; +X return NULL; +X } +X ret = getwd(localbuf); +X if (ret != NULL && strlen(localbuf) >= size) { +X errno = ERANGE; +X return NULL; +X } +X if (ret == NULL) { +X errno = EACCES; /* Most likely error */ +X return NULL; +X } +X strncpy(buf, localbuf, size); +X return buf; X} X X#else @@ -1625,30 +1625,30 @@ X#define PWD_CMD "/bin/pwd" X Xchar * Xgetcwd(buf, size) -X char *buf; -X int size; +X char *buf; +X int size; X{ -X FILE *fp; -X char *p; -X int sts; -X if (size <= 0) { -X errno = EINVAL; -X return NULL; -X } -X if ((fp = popen(PWD_CMD, "r")) == NULL) -X return NULL; -X if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { -X errno = EACCES; /* Most likely error */ -X return NULL; -X } -X for (p = buf; *p != '\n'; p++) { -X if (*p == '\0') { -X errno = ERANGE; -X return NULL; -X } -X } -X *p = '\0'; -X return buf; +X FILE *fp; +X char *p; +X int sts; +X if (size <= 0) { +X errno = EINVAL; +X return NULL; +X } +X if ((fp = popen(PWD_CMD, "r")) == NULL) +X return NULL; +X if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { +X errno = EACCES; /* Most likely error */ +X return NULL; +X } +X for (p = buf; *p != '\n'; p++) { +X if (*p == '\0') { +X errno = ERANGE; +X return NULL; +X } +X } +X *p = '\0'; +X return buf; X} X X#endif @@ -1663,12 +1663,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1736,12 +1736,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1767,63 +1767,63 @@ Xstatic void list1node PROTO((FILE *, node *)); X Xvoid Xlisttree(n) -X node *n; +X node *n; X{ -X listnode(stdout, n); +X listnode(stdout, n); X} X Xstatic int level, atbol; X Xvoid Xlistnode(fp, n) -X FILE *fp; -X node *n; +X FILE *fp; +X node *n; X{ -X level = 0; -X atbol = 1; -X list1node(fp, n); +X level = 0; +X atbol = 1; +X list1node(fp, n); X} X Xstatic void Xlist1node(fp, n) -X FILE *fp; -X node *n; +X FILE *fp; +X node *n; X{ -X if (n == 0) -X return; -X if (ISNONTERMINAL(TYPE(n))) { -X int i; -X for (i = 0; i < NCH(n); i++) -X list1node(fp, CHILD(n, i)); -X } -X else if (ISTERMINAL(TYPE(n))) { -X switch (TYPE(n)) { -X case INDENT: -X ++level; -X break; -X case DEDENT: -X --level; -X break; -X default: -X if (atbol) { -X int i; -X for (i = 0; i < level; ++i) -X fprintf(fp, "\t"); -X atbol = 0; -X } -X if (TYPE(n) == NEWLINE) { -X if (STR(n) != NULL) -X fprintf(fp, "%s", STR(n)); -X fprintf(fp, "\n"); -X atbol = 1; -X } -X else -X fprintf(fp, "%s ", STR(n)); -X break; -X } -X } -X else -X fprintf(fp, "? "); +X if (n == 0) +X return; +X if (ISNONTERMINAL(TYPE(n))) { +X int i; +X for (i = 0; i < NCH(n); i++) +X list1node(fp, CHILD(n, i)); +X } +X else if (ISTERMINAL(TYPE(n))) { +X switch (TYPE(n)) { +X case INDENT: +X ++level; +X break; +X case DEDENT: +X --level; +X break; +X default: +X if (atbol) { +X int i; +X for (i = 0; i < level; ++i) +X fprintf(fp, "\t"); +X atbol = 0; +X } +X if (TYPE(n) == NEWLINE) { +X if (STR(n) != NULL) +X fprintf(fp, "%s", STR(n)); +X fprintf(fp, "\n"); +X atbol = 1; +X } +X else +X fprintf(fp, "%s ", STR(n)); +X break; +X } +X } +X else +X fprintf(fp, "? "); X} EOF fi @@ -1836,12 +1836,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1863,18 +1863,18 @@ X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 X XAnother generally useful object type is an list of object pointers. XThis is a mutable type: the list items can be changed, and items can be -Xadded or removed. Out-of-range indices or non-list objects are ignored. +Xadded or removed. Out-of-range indices or non-list objects are ignored. X X*** WARNING *** setlistitem does not increment the new item's reference Xcount, but does decrement the reference count of the item it replaces, -Xif not nil. It does *decrement* the reference count if it is *not* -Xinserted in the list. Similarly, getlistitem does not increment the +Xif not nil. It does *decrement* the reference count if it is *not* +Xinserted in the list. Similarly, getlistitem does not increment the Xreturned item's reference count. X*/ X Xtypedef struct { -X OB_VARHEAD -X object **ob_item; +X OB_VARHEAD +X object **ob_item; X} listobject; X Xextern typeobject Listtype; @@ -1902,12 +1902,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1929,17 +1929,17 @@ X#include "node.h" X Xnode * Xnewtree(type) -X int type; +X int type; X{ -X node *n = NEW(node, 1); -X if (n == NULL) -X return NULL; -X n->n_type = type; -X n->n_str = NULL; -X n->n_lineno = 0; -X n->n_nchildren = 0; -X n->n_child = NULL; -X return n; +X node *n = NEW(node, 1); +X if (n == NULL) +X return NULL; +X n->n_type = type; +X n->n_str = NULL; +X n->n_lineno = 0; +X n->n_nchildren = 0; +X n->n_child = NULL; +X return n; X} X X#define XXX 3 /* Node alignment factor to speed up realloc */ @@ -1947,29 +1947,29 @@ X#define XXXROUNDUP(n) ((n) == 1 ? 1 : ((n) + XXX - 1) / XXX * XXX) X Xnode * Xaddchild(n1, type, str, lineno) -X register node *n1; -X int type; -X char *str; -X int lineno; +X register node *n1; +X int type; +X char *str; +X int lineno; X{ -X register int nch = n1->n_nchildren; -X register int nch1 = nch+1; -X register node *n; -X if (XXXROUNDUP(nch) < nch1) { -X n = n1->n_child; -X nch1 = XXXROUNDUP(nch1); -X RESIZE(n, node, nch1); -X if (n == NULL) -X return NULL; -X n1->n_child = n; -X } -X n = &n1->n_child[n1->n_nchildren++]; -X n->n_type = type; -X n->n_str = str; -X n->n_lineno = lineno; -X n->n_nchildren = 0; -X n->n_child = NULL; -X return n; +X register int nch = n1->n_nchildren; +X register int nch1 = nch+1; +X register node *n; +X if (XXXROUNDUP(nch) < nch1) { +X n = n1->n_child; +X nch1 = XXXROUNDUP(nch1); +X RESIZE(n, node, nch1); +X if (n == NULL) +X return NULL; +X n1->n_child = n; +X } +X n = &n1->n_child[n1->n_nchildren++]; +X n->n_type = type; +X n->n_str = str; +X n->n_lineno = lineno; +X n->n_nchildren = 0; +X n->n_child = NULL; +X return n; X} X X/* Forward */ @@ -1978,25 +1978,25 @@ X X Xvoid Xfreetree(n) -X node *n; +X node *n; X{ -X if (n != NULL) { -X freechildren(n); -X DEL(n); -X } +X if (n != NULL) { +X freechildren(n); +X DEL(n); +X } X} X Xstatic void Xfreechildren(n) -X node *n; +X node *n; X{ -X int i; -X for (i = NCH(n); --i >= 0; ) -X freechildren(CHILD(n, i)); -X if (n->n_child != NULL) -X DEL(n->n_child); -X if (STR(n) != NULL) -X DEL(STR(n)); +X int i; +X for (i = NCH(n); --i >= 0; ) +X freechildren(CHILD(n, i)); +X if (n->n_child != NULL) +X DEL(n->n_child); +X if (STR(n) != NULL) +X DEL(STR(n)); X} EOF fi @@ -2009,12 +2009,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2034,25 +2034,25 @@ X X/* X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 X -XType stringobject represents a character string. An extra zero byte is +XType stringobject represents a character string. An extra zero byte is Xreserved at the end to ensure it is zero-terminated, but a size is -Xpresent so strings with null bytes in them can be represented. This +Xpresent so strings with null bytes in them can be represented. This Xis an immutable object type. X XThere are functions to create new string objects, to test Xan object for string-ness, and to get the -Xstring value. The latter function returns a null pointer +Xstring value. The latter function returns a null pointer Xif the object is not of the proper type. XThere is a variant that takes an explicit size as well as a -Xvariant that assumes a zero-terminated string. Note that none of the +Xvariant that assumes a zero-terminated string. Note that none of the Xfunctions should be applied to nil objects. X*/ X X/* NB The type is revealed here only because it is used in dictobject.c */ X Xtypedef struct { -X OB_VARHEAD -X char ob_sval[1]; +X OB_VARHEAD +X char ob_sval[1]; X} stringobject; X Xextern typeobject Stringtype; @@ -2079,12 +2079,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2102,40 +2102,40 @@ X X/* Interface to map C struct members to Python object attributes */ X X/* The offsetof() macro calculates the offset of a structure member -X in its structure. Unfortunately this cannot be written down -X portably, hence it is provided by a Standard C header file. -X For pre-Standard C compilers, here is a version that usually works -X (but watch out!): */ +X in its structure. Unfortunately this cannot be written down +X portably, hence it is provided by a Standard C header file. +X For pre-Standard C compilers, here is a version that usually works +X (but watch out!): */ X X#ifndef offsetof X#define offsetof(type, member) ( (int) & ((type*)0) -> member ) X#endif X X/* An array of memberlist structures defines the name, type and offset -X of selected members of a C structure. These can be read by -X getmember() and set by setmember() (except if their READONLY flag -X is set). The array must be terminated with an entry whose name -X pointer is NULL. */ +X of selected members of a C structure. These can be read by +X getmember() and set by setmember() (except if their READONLY flag +X is set). The array must be terminated with an entry whose name +X pointer is NULL. */ X Xstruct memberlist { -X char *name; -X int type; -X int offset; -X int readonly; +X char *name; +X int type; +X int offset; +X int readonly; X}; X X/* Types */ -X#define T_SHORT 0 -X#define T_INT 1 -X#define T_LONG 2 -X#define T_FLOAT 3 -X#define T_DOUBLE 4 -X#define T_STRING 5 -X#define T_OBJECT 6 +X#define T_SHORT 0 +X#define T_INT 1 +X#define T_LONG 2 +X#define T_FLOAT 3 +X#define T_DOUBLE 4 +X#define T_STRING 5 +X#define T_OBJECT 6 X X/* Readonly flag */ -X#define READONLY 1 -X#define RO READONLY /* Shorthand */ +X#define READONLY 1 +X#define RO READONLY /* Shorthand */ X Xobject *getmember PROTO((char *, struct memberlist *, char *)); Xint setmember PROTO((char *, struct memberlist *, char *, object *)); @@ -2150,12 +2150,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2172,27 +2172,27 @@ X******************************************************************/ X X/* Tokenizer interface */ X -X#include "token.h" /* For token types */ +X#include "token.h" /* For token types */ X -X#define MAXINDENT 100 /* Max indentation level */ +X#define MAXINDENT 100 /* Max indentation level */ X X/* Tokenizer state */ Xstruct tok_state { -X /* Input state; buf <= cur <= inp <= end */ -X /* NB an entire token must fit in the buffer */ -X char *buf; /* Input buffer */ -X char *cur; /* Next character in buffer */ -X char *inp; /* End of data in buffer */ -X char *end; /* End of input buffer */ -X int done; /* 0 normally, 1 at EOF, -1 after error */ -X FILE *fp; /* Rest of input; NULL if tokenizing a string */ -X int tabsize; /* Tab spacing */ -X int indent; /* Current indentation index */ -X int indstack[MAXINDENT]; /* Stack of indents */ -X int atbol; /* Nonzero if at begin of new line */ -X int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ -X char *prompt, *nextprompt; /* For interactive prompting */ -X int lineno; /* Current line number */ +X /* Input state; buf <= cur <= inp <= end */ +X /* NB an entire token must fit in the buffer */ +X char *buf; /* Input buffer */ +X char *cur; /* Next character in buffer */ +X char *inp; /* End of data in buffer */ +X char *end; /* End of input buffer */ +X int done; /* 0 normally, 1 at EOF, -1 after error */ +X FILE *fp; /* Rest of input; NULL if tokenizing a string */ +X int tabsize; /* Tab spacing */ +X int indent; /* Current indentation index */ +X int indstack[MAXINDENT]; /* Stack of indents */ +X int atbol; /* Nonzero if at begin of new line */ +X int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ +X char *prompt, *nextprompt; /* For interactive prompting */ +X int lineno; /* Current line number */ X}; X Xextern struct tok_state *tok_setups PROTO((char *)); @@ -2210,12 +2210,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -2237,18 +2237,18 @@ X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 X XAnother generally useful object type is an tuple of object pointers. XThis is a mutable type: the tuple items can be changed (but not their -Xnumber). Out-of-range indices or non-tuple objects are ignored. +Xnumber). Out-of-range indices or non-tuple objects are ignored. X X*** WARNING *** settupleitem does not increment the new item's reference Xcount, but does decrement the reference count of the item it replaces, -Xif not nil. It does *decrement* the reference count if it is *not* -Xinserted in the tuple. Similarly, gettupleitem does not increment the +Xif not nil. It does *decrement* the reference count if it is *not* +Xinserted in the tuple. Similarly, gettupleitem does not increment the Xreturned item's reference count. X*/ X Xtypedef struct { -X OB_VARHEAD -X object *ob_item[1]; +X OB_VARHEAD +X object *ob_item[1]; X} tupleobject; X Xextern typeobject Tupletype; @@ -2265,4 +2265,4 @@ X#define GETTUPLEITEM(op, i) ((op)->ob_item[i]) EOF fi echo 'Part 18 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-19-21.shar b/shar/python-0.9.1-19-21.shar index c52113b..8fcaf4d 100644 --- a/shar/python-0.9.1-19-21.shar +++ b/shar/python-0.9.1-19-21.shar @@ -23,66 +23,66 @@ X XMAXSIZE = 200*1024 # Files this big must be binaries and are skipped. X Xdef getargs(): -X args = sys.argv[1:] -X if args: -X return args -X print 'No arguments, checking almost *' -X for file in posix.listdir('.'): -X if not skipfile(file): -X args.append(file) -X if not args: -X print 'Nothing to do -- exit 1' -X sys.exit(1) -X args.sort() -X return args +X args = sys.argv[1:] +X if args: +X return args +X print 'No arguments, checking almost *' +X for file in posix.listdir('.'): +X if not skipfile(file): +X args.append(file) +X if not args: +X print 'Nothing to do -- exit 1' +X sys.exit(1) +X args.sort() +X return args X Xbadnames = ['tags', 'xyzzy'] Xbadprefixes = ['.', ',', '@', '#', 'o.'] Xbadsuffixes = \ -X ['~', '.a', '.o', '.old', '.bak', '.orig', '.new', '.prev', '.not'] +X ['~', '.a', '.o', '.old', '.bak', '.orig', '.new', '.prev', '.not'] X# XXX Should generalize even more to use fnmatch! X Xdef skipfile(file): -X if file in badnames or \ -X badprefix(file) or badsuffix(file) or \ -X path.islink(file) or path.isdir(file): -X return 1 -X # Skip huge files -- probably binaries. -X try: -X st = posix.stat(file) -X except posix.error: -X return 1 # Doesn't exist -- skip it -X return st[stat.ST_SIZE] >= MAXSIZE +X if file in badnames or \ +X badprefix(file) or badsuffix(file) or \ +X path.islink(file) or path.isdir(file): +X return 1 +X # Skip huge files -- probably binaries. +X try: +X st = posix.stat(file) +X except posix.error: +X return 1 # Doesn't exist -- skip it +X return st[stat.ST_SIZE] >= MAXSIZE X Xdef badprefix(file): -X for bad in badprefixes: -X if file[:len(bad)] = bad: return 1 -X return 0 +X for bad in badprefixes: +X if file[:len(bad)] = bad: return 1 +X return 0 X Xdef badsuffix(file): -X for bad in badsuffixes: -X if file[-len(bad):] = bad: return 1 -X return 0 +X for bad in badsuffixes: +X if file[-len(bad):] = bad: return 1 +X return 0 X Xdef go(args): -X for file in args: -X print file + ':' -X if run('rcsdiff -c', file): -X if askyesno('Check in ' + file + ' ? '): -X sts = run('rcs -l', file) # ignored -X # can't use run() here because it's interactive -X sts = posix.system('ci -l ' + file) +X for file in args: +X print file + ':' +X if run('rcsdiff -c', file): +X if askyesno('Check in ' + file + ' ? '): +X sts = run('rcs -l', file) # ignored +X # can't use run() here because it's interactive +X sts = posix.system('ci -l ' + file) X Xdef run(cmd, file): -X sts, output = commands.getstatusoutput(cmd + commands.mkarg(file)) -X if sts: -X print output -X print 'Exit status', sts -X return sts +X sts, output = commands.getstatusoutput(cmd + commands.mkarg(file)) +X if sts: +X print output +X print 'Exit status', sts +X return sts X Xdef askyesno(prompt): -X s = raw_input(prompt) -X return s in ['y', 'yes'] +X s = raw_input(prompt) +X return s in ['y', 'yes'] X Xgo(getargs()) EOF @@ -373,45 +373,45 @@ X# For historical reasons, button creation methods are called X# define() while split creation methods are called create(). X Xclass AbstractParent(): -X # -X # Upcalls from child to parent -X # -X def addchild(self, child): unimpl() -X def delchild(self, child): unimpl() -X # -X def need_mouse(self, child): unimpl() -X def no_mouse(self, child): unimpl() -X # -X def need_timer(self, child): unimpl() -X def no_timer(self, child): unimpl() -X # -X # XXX need_kbd, no_kbd; focus??? -X # -X def begindrawing(self): return unimpl() -X def beginmeasuring(self): return unimpl() -X # -X def change(self, area): unimpl() -X def scroll(self, (area, (dh, dv))): unimpl() -X def settimer(self, itimer): unimpl() +X # +X # Upcalls from child to parent +X # +X def addchild(self, child): unimpl() +X def delchild(self, child): unimpl() +X # +X def need_mouse(self, child): unimpl() +X def no_mouse(self, child): unimpl() +X # +X def need_timer(self, child): unimpl() +X def no_timer(self, child): unimpl() +X # +X # XXX need_kbd, no_kbd; focus??? +X # +X def begindrawing(self): return unimpl() +X def beginmeasuring(self): return unimpl() +X # +X def change(self, area): unimpl() +X def scroll(self, (area, (dh, dv))): unimpl() +X def settimer(self, itimer): unimpl() X Xclass AbstractChild(): -X # -X # Downcalls from parent to child -X # -X def destroy(self): unimpl() -X # -X def minsize(self, m): return unimpl() -X def getbounds(self): return unimpl() -X def setbounds(self, bounds): unimpl() -X def draw(self, (d, area)): unimpl() -X # -X # Downcalls only made after certain upcalls -X # -X def mouse_down(self, detail): unimpl() -X def mouse_move(self, detail): unimpl() -X def mouse_up(self, detail): unimpl() -X # -X def timer(self): unimpl() +X # +X # Downcalls from parent to child +X # +X def destroy(self): unimpl() +X # +X def minsize(self, m): return unimpl() +X def getbounds(self): return unimpl() +X def setbounds(self, bounds): unimpl() +X def draw(self, (d, area)): unimpl() +X # +X # Downcalls only made after certain upcalls +X # +X def mouse_down(self, detail): unimpl() +X def mouse_move(self, detail): unimpl() +X def mouse_up(self, detail): unimpl() +X # +X def timer(self): unimpl() X X# A "Split" is a child that manages one or more children. X# (This terminology is due to DEC SRC, except for CSplits.) @@ -420,7 +420,7 @@ X# Certain upcalls and downcalls can be handled transparently, but X# for others (e.g., all geometry related calls) this is not possible. X Xclass AbstractSplit() = AbstractChild(), AbstractParent(): -X pass +X pass EOF fi if test -s 'lib/StripChart.py' @@ -437,65 +437,65 @@ X# A StripChart doesn't really look like a label but it needs a base class. X# LabelAppearance allows it to be disabled and hilited. X Xclass StripChart() = LabelAppearance(), NoReactivity(): -X # -X def define(self, (parent, scale)): -X self.parent = parent -X parent.addchild(self) -X self.init_appearance() -X self.init_reactivity() -X self.ydata = [] -X self.scale = scale -X self.resetbounds() -X return self -X # -X def setbounds(self, bounds): -X LabelAppearance.setbounds(self, bounds) -X self.resetbounds() -X # -X def resetbounds(self): -X (left, top), (right, bottom) = self.bounds -X self.width = right-left -X self.height = bottom-top -X excess = len(self.ydata) - self.width -X if excess > 0: -X del self.ydata[:excess] -X elif excess < 0: -X while len(self.ydata) < self.width: -X self.ydata.insert(0, 0) -X # -X def append(self, y): -X self.ydata.append(y) -X excess = len(self.ydata) - self.width -X if excess > 0: -X del self.ydata[:excess] -X if self.bounds <> rect.empty: -X self.parent.scroll(self.bounds, (-excess, 0)) -X if self.bounds <> rect.empty: -X (left, top), (right, bottom) = self.bounds -X i = len(self.ydata) -X area = (left+i-1, top), (left+i, bottom) -X self.draw(self.parent.begindrawing(), area) -X # -X def draw(self, (d, area)): -X area = rect.intersect(area, self.bounds) -X if area = rect.empty: -X print 'mt' -X return -X d.cliprect(area) -X d.erase(self.bounds) -X (a_left, a_top), (a_right, a_bottom) = area -X (left, top), (right, bottom) = self.bounds -X height = bottom - top -X i1 = a_left - left -X i2 = a_right - left -X for i in range(max(0, i1), min(len(self.ydata), i2)): -X split = bottom-self.ydata[i]*height/self.scale -X d.paint((left+i, split), (left+i+1, bottom)) -X if not self.enabled: -X self.flipenable(d) -X if self.hilited: -X self.fliphilite(d) -X d.noclip() +X # +X def define(self, (parent, scale)): +X self.parent = parent +X parent.addchild(self) +X self.init_appearance() +X self.init_reactivity() +X self.ydata = [] +X self.scale = scale +X self.resetbounds() +X return self +X # +X def setbounds(self, bounds): +X LabelAppearance.setbounds(self, bounds) +X self.resetbounds() +X # +X def resetbounds(self): +X (left, top), (right, bottom) = self.bounds +X self.width = right-left +X self.height = bottom-top +X excess = len(self.ydata) - self.width +X if excess > 0: +X del self.ydata[:excess] +X elif excess < 0: +X while len(self.ydata) < self.width: +X self.ydata.insert(0, 0) +X # +X def append(self, y): +X self.ydata.append(y) +X excess = len(self.ydata) - self.width +X if excess > 0: +X del self.ydata[:excess] +X if self.bounds <> rect.empty: +X self.parent.scroll(self.bounds, (-excess, 0)) +X if self.bounds <> rect.empty: +X (left, top), (right, bottom) = self.bounds +X i = len(self.ydata) +X area = (left+i-1, top), (left+i, bottom) +X self.draw(self.parent.begindrawing(), area) +X # +X def draw(self, (d, area)): +X area = rect.intersect(area, self.bounds) +X if area = rect.empty: +X print 'mt' +X return +X d.cliprect(area) +X d.erase(self.bounds) +X (a_left, a_top), (a_right, a_bottom) = area +X (left, top), (right, bottom) = self.bounds +X height = bottom - top +X i1 = a_left - left +X i2 = a_right - left +X for i in range(max(0, i1), min(len(self.ydata), i2)): +X split = bottom-self.ydata[i]*height/self.scale +X d.paint((left+i, split), (left+i+1, bottom)) +X if not self.enabled: +X self.flipenable(d) +X if self.hilited: +X self.fliphilite(d) +X d.noclip() EOF fi if test -s 'lib/cmp.py' @@ -508,62 +508,62 @@ X X# Efficiently compare files, boolean outcome only (equal / not equal). X X# Tricks (used in this order): -X# - Files with identical type, size & mtime are assumed to be clones -X# - Files with different type or size cannot be identical -X# - We keep a cache of outcomes of earlier comparisons -X# - We don't fork a process to run 'cmp' but read the files ourselves +X# - Files with identical type, size & mtime are assumed to be clones +X# - Files with different type or size cannot be identical +X# - We keep a cache of outcomes of earlier comparisons +X# - We don't fork a process to run 'cmp' but read the files ourselves X Ximport posix X Xcache = {} X Xdef cmp(f1, f2): # Compare two files, use the cache if possible. -X # Return 1 for identical files, 0 for different. -X # Raise exceptions if either file could not be statted, read, etc. -X s1, s2 = sig(posix.stat(f1)), sig(posix.stat(f2)) -X if s1[0] <> 8 or s2[0] <> 8: -X # Either is a not a plain file -- always report as different -X return 0 -X if s1 = s2: -X # type, size & mtime match -- report same -X return 1 -X if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother -X # types or sizes differ -- report different -X return 0 -X # same type and size -- look in the cache -X key = f1 + ' ' + f2 -X try: -X cs1, cs2, outcome = cache[key] -X # cache hit -X if s1 = cs1 and s2 = cs2: -X # cached signatures match -X return outcome -X # stale cached signature(s) -X except RuntimeError: -X # cache miss -X pass -X # really compare -X outcome = do_cmp(f1, f2) -X cache[key] = s1, s2, outcome -X return outcome +X # Return 1 for identical files, 0 for different. +X # Raise exceptions if either file could not be statted, read, etc. +X s1, s2 = sig(posix.stat(f1)), sig(posix.stat(f2)) +X if s1[0] <> 8 or s2[0] <> 8: +X # Either is a not a plain file -- always report as different +X return 0 +X if s1 = s2: +X # type, size & mtime match -- report same +X return 1 +X if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother +X # types or sizes differ -- report different +X return 0 +X # same type and size -- look in the cache +X key = f1 + ' ' + f2 +X try: +X cs1, cs2, outcome = cache[key] +X # cache hit +X if s1 = cs1 and s2 = cs2: +X # cached signatures match +X return outcome +X # stale cached signature(s) +X except RuntimeError: +X # cache miss +X pass +X # really compare +X outcome = do_cmp(f1, f2) +X cache[key] = s1, s2, outcome +X return outcome X Xdef sig(st): # Return signature (i.e., type, size, mtime) from raw stat data -X # 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid -X # 6-9: st_size, st_atime, st_mtime, st_ctime -X type = st[0] / 4096 -X size = st[6] -X mtime = st[8] -X return type, size, mtime +X # 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid +X # 6-9: st_size, st_atime, st_mtime, st_ctime +X type = st[0] / 4096 +X size = st[6] +X mtime = st[8] +X return type, size, mtime X Xdef do_cmp(f1, f2): # Compare two files, really -X bufsize = 8096 # Could be tuned -X fp1 = open(f1, 'r') -X fp2 = open(f2, 'r') -X while 1: -X b1 = fp1.read(bufsize) -X b2 = fp2.read(bufsize) -X if b1 <> b2: return 0 -X if not b1: return 1 +X bufsize = 8096 # Could be tuned +X fp1 = open(f1, 'r') +X fp2 = open(f2, 'r') +X while 1: +X b1 = fp1.read(bufsize) +X b2 = fp2.read(bufsize) +X if b1 <> b2: return 0 +X if not b1: return 1 EOF fi if test -s 'lib/commands.py' @@ -584,7 +584,7 @@ X X# Get 'ls -l' status for an object into a string X# Xdef getstatus(file): -X return getoutput('ls -ld' + mkarg(file)) +X return getoutput('ls -ld' + mkarg(file)) X X X# Get the output from a shell command into a string. @@ -593,44 +593,44 @@ X# Assume the command will work with ' >tempfile 2>&1' appended. X# XXX This should use posix.popen() instead, should it exist. X# Xdef getoutput(cmd): -X return getstatusoutput(cmd)[1] +X return getstatusoutput(cmd)[1] X X X# Ditto but preserving the exit status. X# Returns a pair (sts, output) X# Xdef getstatusoutput(cmd): -X tmp = '/usr/tmp/wdiff' + `rand.rand()` -X sts = -1 -X try: -X sts = posix.system(cmd + ' >' + tmp + ' 2>&1') -X text = readfile(tmp) -X finally: -X altsts = posix.system('rm -f ' + tmp) -X if text[-1:] = '\n': text = text[:-1] -X return sts, text +X tmp = '/usr/tmp/wdiff' + `rand.rand()` +X sts = -1 +X try: +X sts = posix.system(cmd + ' >' + tmp + ' 2>&1') +X text = readfile(tmp) +X finally: +X altsts = posix.system('rm -f ' + tmp) +X if text[-1:] = '\n': text = text[:-1] +X return sts, text X X X# Return a string containing a file's contents. X# Xdef readfile(fn): -X st = posix.stat(fn) -X size = st[stat.ST_SIZE] -X if not size: return '' -X try: -X fp = open(fn, 'r') -X except: -X raise posix.error, 'readfile(' + fn + '): open failed' -X try: -X return fp.read(size) -X except: -X raise posix.error, 'readfile(' + fn + '): read failed' +X st = posix.stat(fn) +X size = st[stat.ST_SIZE] +X if not size: return '' +X try: +X fp = open(fn, 'r') +X except: +X raise posix.error, 'readfile(' + fn + '): open failed' +X try: +X return fp.read(size) +X except: +X raise posix.error, 'readfile(' + fn + '): read failed' X X X# Make command argument from directory and pathname (prefix space, add quotes). X# Xdef mk2arg(head, x): -X return mkarg(path.cat(head, x)) +X return mkarg(path.cat(head, x)) X X X# Make a shell command argument from a string. @@ -639,15 +639,15 @@ X# otherwis, enclose in double quotes and prefix quotable characters X# with backslash. X# Xdef mkarg(x): -X if '\'' not in x: -X return ' \'' + x + '\'' -X s = ' "' -X for c in x: -X if c in '\\$"': -X s = s + '\\' -X s = s + c -X s = s + '"' -X return s +X if '\'' not in x: +X return ' \'' + x + '\'' +X s = ' "' +X for c in x: +X if c in '\\$"': +X s = s + '\\' +X s = s + c +X s = s + '"' +X return s EOF fi if test -s 'lib/getopt.py' @@ -669,39 +669,39 @@ X# It raises the exception getopt.error with a string argument if it X# detects an error. X X# It returns two items: -X# (1) a list of pairs (option, option_argument) giving the options in -X# the order in which they were specified. (I'd use a dictionary -X# but applications may depend on option order or multiple -X# occurrences.) Boolean options have '' as option_argument. -X# (2) the list of remaining arguments (may be empty). +X# (1) a list of pairs (option, option_argument) giving the options in +X# the order in which they were specified. (I'd use a dictionary +X# but applications may depend on option order or multiple +X# occurrences.) Boolean options have '' as option_argument. +X# (2) the list of remaining arguments (may be empty). X Xerror = 'getopt error' X Xdef getopt(args, options): -X list = [] -X while args and args[0][0] = '-' and args[0] <> '-': -X if args[0] = '--': -X args = args[1:] -X break -X optstring, args = args[0][1:], args[1:] -X while optstring <> '': -X opt, optstring = optstring[0], optstring[1:] -X if classify(opt, options): # May raise exception as well -X if optstring = '': -X if not args: -X raise error, 'option -' + opt + ' requires argument' -X optstring, args = args[0], args[1:] -X optarg, optstring = optstring, '' -X else: -X optarg = '' -X list.append('-' + opt, optarg) -X return list, args +X list = [] +X while args and args[0][0] = '-' and args[0] <> '-': +X if args[0] = '--': +X args = args[1:] +X break +X optstring, args = args[0][1:], args[1:] +X while optstring <> '': +X opt, optstring = optstring[0], optstring[1:] +X if classify(opt, options): # May raise exception as well +X if optstring = '': +X if not args: +X raise error, 'option -' + opt + ' requires argument' +X optstring, args = args[0], args[1:] +X optarg, optstring = optstring, '' +X else: +X optarg = '' +X list.append('-' + opt, optarg) +X return list, args X Xdef classify(opt, options): # Helper to check type of option -X for i in range(len(options)): -X if opt = options[i] <> ':': -X return options[i+1:i+2] = ':' -X raise error, 'option -' + opt + ' not recognized' +X for i in range(len(options)): +X if opt = options[i] <> ':': +X return options[i+1:i+2] = ':' +X raise error, 'option -' + opt + ' not recognized' EOF fi if test -s 'lib/rect.py' @@ -729,74 +729,74 @@ X X# Check if a rectangle is empty. X# Xdef is_empty((left, top), (right, bottom)): -X return left >= right or top >= bottom +X return left >= right or top >= bottom X X X# Compute the intersection or two or more rectangles. X# This works with a list or tuple argument. X# Xdef intersect(list): -X if not list: raise error, 'intersect called with empty list' -X if is_empty(list[0]): return empty -X (left, top), (right, bottom) = list[0] -X for rect in list[1:]: -X if is_empty(rect): -X return empty -X (l, t), (r, b) = rect -X if left < l: left = l -X if top < t: top = t -X if right > r: right = r -X if bottom > b: bottom = b -X if is_empty((left, top), (right, bottom)): -X return empty -X return (left, top), (right, bottom) +X if not list: raise error, 'intersect called with empty list' +X if is_empty(list[0]): return empty +X (left, top), (right, bottom) = list[0] +X for rect in list[1:]: +X if is_empty(rect): +X return empty +X (l, t), (r, b) = rect +X if left < l: left = l +X if top < t: top = t +X if right > r: right = r +X if bottom > b: bottom = b +X if is_empty((left, top), (right, bottom)): +X return empty +X return (left, top), (right, bottom) X X X# Compute the smallest rectangle containing all given rectangles. X# This works with a list or tuple argument. X# Xdef union(list): -X (left, top), (right, bottom) = empty -X for (l, t), (r, b) in list[1:]: -X if not is_empty((l, t), (r, b)): -X if l < left: left = l -X if t < top: top = t -X if r > right: right = r -X if b > bottom: bottom = b -X res = (left, top), (right, bottom) -X if is_empty(res): -X return empty -X return res +X (left, top), (right, bottom) = empty +X for (l, t), (r, b) in list[1:]: +X if not is_empty((l, t), (r, b)): +X if l < left: left = l +X if t < top: top = t +X if r > right: right = r +X if b > bottom: bottom = b +X res = (left, top), (right, bottom) +X if is_empty(res): +X return empty +X return res X X X# Check if a point is in a rectangle. X# Xdef pointinrect((h, v), ((left, top), (right, bottom))): -X return left <= h < right and top <= v < bottom +X return left <= h < right and top <= v < bottom X X X# Return a rectangle that is dh, dv inside another X# Xdef inset(((left, top), (right, bottom)), (dh, dv)): -X left = left + dh -X top = top + dv -X right = right - dh -X bottom = bottom - dv -X r = (left, top), (right, bottom) -X if is_empty(r): -X return empty -X else: -X return r +X left = left + dh +X top = top + dv +X right = right - dh +X bottom = bottom - dv +X r = (left, top), (right, bottom) +X if is_empty(r): +X return empty +X else: +X return r X X X# Conversions between rectangles and 'geometry tuples', X# given as origin (h, v) and dimensions (width, height). X# Xdef rect2geom((left, top), (right, bottom)): -X return (left, top), (right-left, bottom-top) +X return (left, top), (right-left, bottom-top) X Xdef geom2rect((h, v), (width, height)): -X return (h, v), (h+width, v+height) +X return (h, v), (h+width, v+height) EOF fi if test -s 'lib/selection.py' @@ -806,7 +806,7 @@ echo 'x - lib/selection.py' sed 's/^X//' > 'lib/selection.py' << 'EOF' X# DAWKINS' BLIND WATCHMAKER -- "METHINKS IT IS LIKE A WEASEL" EXAMPLE X# -X# Start with a random phrase. Successively: +X# Start with a random phrase. Successively: X# Breed a next generation by copying with small mutations. X# Choose the member of the next generation that most closely resembles X# the target phrase to start breeding the next generation. @@ -822,58 +822,58 @@ X# Parameters to play with XGenerationSize = 100 XMutationChance = 1.0/28.0 X -XIndexSet = range(len(Target)) # Used to speed up loops +XIndexSet = range(len(Target)) # Used to speed up loops X Xdef choice(sequence): -X n = len(sequence) -X i = int(random() * float(n)) % n -X return sequence[i] +X n = len(sequence) +X i = int(random() * float(n)) % n +X return sequence[i] X Xdef random_phrase(): -X phrase = '' -X for i in IndexSet: -X phrase = phrase + choice(Alphabet) -X return phrase +X phrase = '' +X for i in IndexSet: +X phrase = phrase + choice(Alphabet) +X return phrase X Xdef mutate_phrase(phrase): -X mutant = phrase -X for i in range(int(0.5 + MutationChance*float(len(phrase)))): -X i = choice(IndexSet) -X c = choice(Alphabet) -X mutant = mutant[:i] + c + mutant[i+1:] -X #print `mutant` -X return mutant +X mutant = phrase +X for i in range(int(0.5 + MutationChance*float(len(phrase)))): +X i = choice(IndexSet) +X c = choice(Alphabet) +X mutant = mutant[:i] + c + mutant[i+1:] +X #print `mutant` +X return mutant X Xdef matching_factor(phrase): -X factor = 0 -X for i in IndexSet: -X if phrase[i] = Target[i]: factor = factor + 1 -X return factor +X factor = 0 +X for i in IndexSet: +X if phrase[i] = Target[i]: factor = factor + 1 +X return factor X Xdef breed_generation(phrase): -X generation = [phrase] -X while len(generation) < GenerationSize: -X generation.append(mutate_phrase(phrase)) -X return generation +X generation = [phrase] +X while len(generation) < GenerationSize: +X generation.append(mutate_phrase(phrase)) +X return generation X Xdef select_best(generation): -X factor, selected = -1, '' -X for phrase in generation: -X f = matching_factor(phrase) -X if f > factor: -X factor, selected = f, phrase -X return selected +X factor, selected = -1, '' +X for phrase in generation: +X f = matching_factor(phrase) +X if f > factor: +X factor, selected = f, phrase +X return selected X Xdef main(): -X gen = 0 -X phrase = random_phrase() -X print gen, `phrase` -X while phrase <> Target: -X next_generation = breed_generation(phrase) -X #print next_generation -X phrase = select_best(next_generation) -X gen = gen+1 -X print gen, `phrase` +X gen = 0 +X phrase = random_phrase() +X print gen, `phrase` +X while phrase <> Target: +X next_generation = breed_generation(phrase) +X #print next_generation +X phrase = select_best(next_generation) +X gen = gen+1 +X print gen, `phrase` X Xmain() EOF @@ -900,75 +900,75 @@ X X# Stat a file, possibly out of the cache. X# Xdef stat(path): -X if cache.has_key(path): -X return cache[path] -X cache[path] = ret = posix.stat(path) -X return ret +X if cache.has_key(path): +X return cache[path] +X cache[path] = ret = posix.stat(path) +X return ret X X X# Reset the cache completely. X# Hack: to reset a global variable, we import this module. X# Xdef reset(): -X import statcache -X # Check that we really imported the same module -X if cache is not statcache.cache: -X raise 'sorry, statcache identity crisis' -X statcache.cache = {} +X import statcache +X # Check that we really imported the same module +X if cache is not statcache.cache: +X raise 'sorry, statcache identity crisis' +X statcache.cache = {} X X X# Remove a given item from the cache, if it exists. X# Xdef forget(path): -X if cache.has_key(path): -X del cache[path] +X if cache.has_key(path): +X del cache[path] X X X# Remove all pathnames with a given prefix. X# Xdef forget_prefix(prefix): -X n = len(prefix) -X for path in cache.keys(): -X if path[:n] = prefix: -X del cache[path] +X n = len(prefix) +X for path in cache.keys(): +X if path[:n] = prefix: +X del cache[path] X X X# Forget about a directory and all entries in it, but not about X# entries in subdirectories. X# Xdef forget_dir(prefix): -X if prefix[-1:] = '/' and prefix <> '/': -X prefix = prefix[:-1] -X forget(prefix) -X if prefix[-1:] <> '/': -X prefix = prefix + '/' -X n = len(prefix) -X for path in cache.keys(): -X if path[:n] = prefix: -X rest = path[n:] -X if rest[-1:] = '/': rest = rest[:-1] -X if '/' not in rest: -X del cache[path] +X if prefix[-1:] = '/' and prefix <> '/': +X prefix = prefix[:-1] +X forget(prefix) +X if prefix[-1:] <> '/': +X prefix = prefix + '/' +X n = len(prefix) +X for path in cache.keys(): +X if path[:n] = prefix: +X rest = path[n:] +X if rest[-1:] = '/': rest = rest[:-1] +X if '/' not in rest: +X del cache[path] X X X# Remove all pathnames except with a given prefix. X# Normally used with prefix = '/' after a chdir(). X# Xdef forget_except_prefix(prefix): -X n = len(prefix) -X for path in cache.keys(): -X if path[:n] <> prefix: -X del cache[path] +X n = len(prefix) +X for path in cache.keys(): +X if path[:n] <> prefix: +X del cache[path] X X X# Check for directory. X# Xdef isdir(path): -X try: -X st = stat(path) -X except posix.error: -X return 0 -X return S_ISDIR(st[ST_MODE]) +X try: +X st = stat(path) +X except posix.error: +X return 0 +X return S_ISDIR(st[ST_MODE]) EOF fi if test -s 'src/allobjects.h' @@ -980,12 +980,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1037,12 +1037,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1059,7 +1059,7 @@ X******************************************************************/ X X/* Bitset interface */ X -X#define BYTE char +X#define BYTE char X Xtypedef BYTE *bitset; X @@ -1070,13 +1070,13 @@ Xint addbit PROTO((bitset bs, int ibit)); /* Returns 0 if already set */ Xint samebitset PROTO((bitset bs1, bitset bs2, int nbits)); Xvoid mergebitset PROTO((bitset bs1, bitset bs2, int nbits)); X -X#define BITSPERBYTE (8*sizeof(BYTE)) -X#define NBYTES(nbits) (((nbits) + BITSPERBYTE - 1) / BITSPERBYTE) +X#define BITSPERBYTE (8*sizeof(BYTE)) +X#define NBYTES(nbits) (((nbits) + BITSPERBYTE - 1) / BITSPERBYTE) X -X#define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE) -X#define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE) -X#define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit)) -X#define BYTE2BIT(ibyte) ((ibyte) * BITSPERBYTE) +X#define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE) +X#define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE) +X#define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit)) +X#define BYTE2BIT(ibyte) ((ibyte) * BITSPERBYTE) X X#define testbit(ss, ibit) (((ss)[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0) EOF @@ -1090,12 +1090,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1136,12 +1136,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1161,7 +1161,7 @@ X X/* XClasses are really hacked in at the last moment. XIt should be possible to use other object types as base classes, -Xbut currently it isn't. We'll see if we can fix that later, sigh... +Xbut currently it isn't. We'll see if we can fix that later, sigh... X*/ X Xextern typeobject Classtype, Classmembertype, Classmethodtype; @@ -1187,12 +1187,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1211,16 +1211,16 @@ X/* Definitions for compiled intermediate code */ X X X/* An intermediate code fragment contains: -X - a string that encodes the instructions, -X - a list of the constants, -X - and a list of the names used. */ +X - a string that encodes the instructions, +X - a list of the constants, +X - and a list of the names used. */ X Xtypedef struct { -X OB_HEAD -X stringobject *co_code; /* instruction opcodes */ -X object *co_consts; /* list of immutable constant objects */ -X object *co_names; /* list of stringobjects */ -X object *co_filename; /* string */ +X OB_HEAD +X stringobject *co_code; /* instruction opcodes */ +X object *co_consts; /* list of immutable constant objects */ +X object *co_names; /* list of stringobjects */ +X object *co_filename; /* string */ X} codeobject; X Xextern typeobject Codetype; @@ -1241,12 +1241,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1264,9 +1264,9 @@ X X/* XDictionary object type -- mapping from char * to object. XNB: the key is given as a char *, not as a stringobject. -XThese functions set errno for errors. Functions dictremove() and +XThese functions set errno for errors. Functions dictremove() and Xdictinsert() return nonzero for errors, getdictsize() returns -1, -Xthe others NULL. A successful call to dictinsert() calls INCREF() +Xthe others NULL. A successful call to dictinsert() calls INCREF() Xfor the inserted item. X*/ X @@ -1292,12 +1292,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1333,10 +1333,10 @@ Xextern object *KeyboardInterrupt; X X/* Some more planned for the future */ X -X#define IndexError RuntimeError -X#define KeyError RuntimeError -X#define ZeroDivisionError RuntimeError -X#define OverflowError RuntimeError +X#define IndexError RuntimeError +X#define KeyError RuntimeError +X#define ZeroDivisionError RuntimeError +X#define OverflowError RuntimeError X X/* Convenience functions */ X @@ -1357,12 +1357,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1388,45 +1388,45 @@ X/* Return the DFA for the given type */ X Xdfa * Xfinddfa(g, type) -X grammar *g; -X register int type; +X grammar *g; +X register int type; X{ -X register int i; -X register dfa *d; -X -X for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { -X if (d->d_type == type) -X return d; -X } -X assert(0); -X /* NOTREACHED */ +X register int i; +X register dfa *d; +X +X for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { +X if (d->d_type == type) +X return d; +X } +X assert(0); +X /* NOTREACHED */ X} X Xchar * Xlabelrepr(lb) -X label *lb; +X label *lb; X{ -X static char buf[100]; -X -X if (lb->lb_type == ENDMARKER) -X return "EMPTY"; -X else if (ISNONTERMINAL(lb->lb_type)) { -X if (lb->lb_str == NULL) { -X sprintf(buf, "NT%d", lb->lb_type); -X return buf; -X } -X else -X return lb->lb_str; -X } -X else { -X if (lb->lb_str == NULL) -X return tok_name[lb->lb_type]; -X else { -X sprintf(buf, "%.32s(%.32s)", -X tok_name[lb->lb_type], lb->lb_str); -X return buf; -X } -X } +X static char buf[100]; +X +X if (lb->lb_type == ENDMARKER) +X return "EMPTY"; +X else if (ISNONTERMINAL(lb->lb_type)) { +X if (lb->lb_str == NULL) { +X sprintf(buf, "NT%d", lb->lb_type); +X return buf; +X } +X else +X return lb->lb_str; +X } +X else { +X if (lb->lb_str == NULL) +X return tok_name[lb->lb_type]; +X else { +X sprintf(buf, "%.32s(%.32s)", +X tok_name[lb->lb_type], lb->lb_str); +X return buf; +X } +X } X} EOF fi @@ -1439,12 +1439,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1483,10 +1483,10 @@ X#endif X X#define NEW(type, n) ( (type *) malloc((n) * sizeof(type)) ) X#define RESIZE(p, type, n) \ -X if ((p) == NULL) \ -X (p) = (type *) malloc((n) * sizeof(type)); \ -X else \ -X (p) = (type *) realloc((char *)(p), (n) * sizeof(type)) +X if ((p) == NULL) \ +X (p) = (type *) malloc((n) * sizeof(type)); \ +X else \ +X (p) = (type *) realloc((char *)(p), (n) * sizeof(type)) X#define DEL(p) free((char *)p) X#define XDEL(p) if ((p) == NULL) ; else DEL(p) X @@ -1509,12 +1509,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1532,11 +1532,11 @@ X X/* Parse tree node interface */ X Xtypedef struct _node { -X int n_type; -X char *n_str; -X int n_lineno; -X int n_nchildren; -X struct _node *n_child; +X int n_type; +X char *n_str; +X int n_lineno; +X int n_nchildren; +X struct _node *n_child; X} node; X Xextern node *newtree PROTO((int type)); @@ -1544,21 +1544,21 @@ Xextern node *addchild PROTO((node *n, int type, char *str, int lineno)); Xextern void freetree PROTO((node *n)); X X/* Node access functions */ -X#define NCH(n) ((n)->n_nchildren) -X#define CHILD(n, i) (&(n)->n_child[i]) -X#define TYPE(n) ((n)->n_type) -X#define STR(n) ((n)->n_str) +X#define NCH(n) ((n)->n_nchildren) +X#define CHILD(n, i) (&(n)->n_child[i]) +X#define TYPE(n) ((n)->n_type) +X#define STR(n) ((n)->n_str) X X/* Assert that the type of a node is what we expect */ X#ifndef DEBUG X#define REQ(n, type) { /*pass*/ ; } X#else X#define REQ(n, type) \ -X { if (TYPE(n) != (type)) { \ -X fprintf(stderr, "FATAL: node type %d, required %d\n", \ -X TYPE(n), type); \ -X abort(); \ -X } } +X { if (TYPE(n) != (type)) { \ +X fprintf(stderr, "FATAL: node type %d, required %d\n", \ +X TYPE(n), type); \ +X abort(); \ +X } } X#endif X Xextern void listtree PROTO((node *)); @@ -1574,12 +1574,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1599,21 +1599,21 @@ X X#define MAXSTACK 100 X Xtypedef struct _stackentry { -X int s_state; /* State in current DFA */ -X dfa *s_dfa; /* Current DFA */ -X struct _node *s_parent; /* Where to add next node */ +X int s_state; /* State in current DFA */ +X dfa *s_dfa; /* Current DFA */ +X struct _node *s_parent; /* Where to add next node */ X} stackentry; X Xtypedef struct _stack { -X stackentry *s_top; /* Top entry */ -X stackentry s_base[MAXSTACK];/* Array of stack entries */ -X /* NB The stack grows down */ +X stackentry *s_top; /* Top entry */ +X stackentry s_base[MAXSTACK];/* Array of stack entries */ +X /* NB The stack grows down */ X} stack; X Xtypedef struct { -X struct _stack p_stack; /* Stack of parser states */ -X struct _grammar *p_grammar; /* Grammar to use */ -X struct _node *p_tree; /* Top of parse tree */ +X struct _stack p_stack; /* Stack of parser states */ +X struct _grammar *p_grammar; /* Grammar to use */ +X struct _node *p_tree; /* Top of parse tree */ X} parser_state; X Xparser_state *newparser PROTO((struct _grammar *g, int start)); @@ -1631,12 +1631,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1652,13 +1652,13 @@ X X******************************************************************/ X X/* Include files and extern declarations used by most of the parser. -X This is a precompiled header for THINK C. */ +X This is a precompiled header for THINK C. */ X X#include <stdio.h> X#include <string.h> X X#ifdef THINK_C -X/* #define THINK_C_3_0 /*** TURN THIS ON FOR THINK C 3.0 ****/ +X/* #define THINK_C_3_0 /*** TURN THIS ON FOR THINK C 3.0 ****/ X#define label label_ X#undef label X#endif @@ -1688,12 +1688,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1742,12 +1742,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1765,21 +1765,21 @@ X X/* X * Definitions etc. for regexp(3) routines. X * -X * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof], +X * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof], X * not the System V one. X */ X X#define MULTILINE X -X#define NSUBEXP 10 +X#define NSUBEXP 10 Xtypedef struct regexp { -X char *startp[NSUBEXP]; -X char *endp[NSUBEXP]; -X char regstart; /* Internal use only. */ -X char reganch; /* Internal use only. */ -X char *regmust; /* Internal use only. */ -X int regmlen; /* Internal use only. */ -X char program[1]; /* Unwarranted chumminess with compiler. */ +X char *startp[NSUBEXP]; +X char *endp[NSUBEXP]; +X char regstart; /* Internal use only. */ +X char reganch; /* Internal use only. */ +X char *regmust; /* Internal use only. */ +X int regmlen; /* Internal use only. */ +X char program[1]; /* Unwarranted chumminess with compiler. */ X} regexp; X Xextern regexp *regcomp(); @@ -1800,12 +1800,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1821,10 +1821,10 @@ X X******************************************************************/ X X/* The type of signal handlers is somewhat problematic. -X This file encapsulates my knowledge about it: -X - on the Mac (THINK C), it's int for 3.0, void for 4.0 -X - on other systems, it's usually void, except it's int on vax Ultrix. -X Pass -DSIGTYPE=... to cc if you know better. */ +X This file encapsulates my knowledge about it: +X - on the Mac (THINK C), it's int for 3.0, void for 4.0 +X - on other systems, it's usually void, except it's int on vax Ultrix. +X Pass -DSIGTYPE=... to cc if you know better. */ X X#ifndef SIGTYPE X @@ -1858,12 +1858,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1880,45 +1880,45 @@ X******************************************************************/ X X/* Token types */ X -X#define ENDMARKER 0 -X#define NAME 1 -X#define NUMBER 2 -X#define STRING 3 -X#define NEWLINE 4 -X#define INDENT 5 -X#define DEDENT 6 -X#define LPAR 7 -X#define RPAR 8 -X#define LSQB 9 -X#define RSQB 10 -X#define COLON 11 -X#define COMMA 12 -X#define SEMI 13 -X#define PLUS 14 -X#define MINUS 15 -X#define STAR 16 -X#define SLASH 17 -X#define VBAR 18 -X#define AMPER 19 -X#define LESS 20 -X#define GREATER 21 -X#define EQUAL 22 -X#define DOT 23 -X#define PERCENT 24 -X#define BACKQUOTE 25 -X#define LBRACE 26 -X#define RBRACE 27 -X#define OP 28 -X#define ERRORTOKEN 29 -X#define N_TOKENS 30 +X#define ENDMARKER 0 +X#define NAME 1 +X#define NUMBER 2 +X#define STRING 3 +X#define NEWLINE 4 +X#define INDENT 5 +X#define DEDENT 6 +X#define LPAR 7 +X#define RPAR 8 +X#define LSQB 9 +X#define RSQB 10 +X#define COLON 11 +X#define COMMA 12 +X#define SEMI 13 +X#define PLUS 14 +X#define MINUS 15 +X#define STAR 16 +X#define SLASH 17 +X#define VBAR 18 +X#define AMPER 19 +X#define LESS 20 +X#define GREATER 21 +X#define EQUAL 22 +X#define DOT 23 +X#define PERCENT 24 +X#define BACKQUOTE 25 +X#define LBRACE 26 +X#define RBRACE 27 +X#define OP 28 +X#define ERRORTOKEN 29 +X#define N_TOKENS 30 X X/* Special definitions for cooperation with parser */ X -X#define NT_OFFSET 256 +X#define NT_OFFSET 256 X -X#define ISTERMINAL(x) ((x) < NT_OFFSET) -X#define ISNONTERMINAL(x) ((x) >= NT_OFFSET) -X#define ISEOF(x) ((x) == ENDMARKER) +X#define ISTERMINAL(x) ((x) < NT_OFFSET) +X#define ISNONTERMINAL(x) ((x) >= NT_OFFSET) +X#define ISEOF(x) ((x) == ENDMARKER) X X Xextern char *tok_name[]; /* Token names */ @@ -1934,12 +1934,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1962,36 +1962,36 @@ X/* Type object implementation */ X Xstatic void Xtype_print(v, fp, flags) -X typeobject *v; -X FILE *fp; -X int flags; +X typeobject *v; +X FILE *fp; +X int flags; X{ -X fprintf(fp, "<type '%s'>", v->tp_name); +X fprintf(fp, "<type '%s'>", v->tp_name); X} X Xstatic object * Xtype_repr(v) -X typeobject *v; +X typeobject *v; X{ -X char buf[100]; -X sprintf(buf, "<type '%.80s'>", v->tp_name); -X return newstringobject(buf); +X char buf[100]; +X sprintf(buf, "<type '%.80s'>", v->tp_name); +X return newstringobject(buf); X} X Xtypeobject Typetype = { -X OB_HEAD_INIT(&Typetype) -X 0, /* Number of items for varobject */ -X "type", /* Name of this type */ -X sizeof(typeobject), /* Basic object size */ -X 0, /* Item size for varobject */ -X 0, /*tp_dealloc*/ -X type_print, /*tp_print*/ -X 0, /*tp_getattr*/ -X 0, /*tp_setattr*/ -X 0, /*tp_compare*/ -X type_repr, /*tp_repr*/ +X OB_HEAD_INIT(&Typetype) +X 0, /* Number of items for varobject */ +X "type", /* Name of this type */ +X sizeof(typeobject), /* Basic object size */ +X 0, /* Item size for varobject */ +X 0, /*tp_dealloc*/ +X type_print, /*tp_print*/ +X 0, /*tp_getattr*/ +X 0, /*tp_setattr*/ +X 0, /*tp_compare*/ +X type_repr, /*tp_repr*/ X}; EOF fi echo 'Part 19 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-20-21.shar b/shar/python-0.9.1-20-21.shar index 59df200..e39278e 100644 --- a/shar/python-0.9.1-20-21.shar +++ b/shar/python-0.9.1-20-21.shar @@ -26,51 +26,51 @@ X XBUFSIZE = 32*1024 X Xdef mkrealfile(name): -X st = posix.stat(name) # Get the mode -X mode = S_IMODE(st[ST_MODE]) -X linkto = posix.readlink(name) # Make sure again it's a symlink -X f_in = open(name, 'r') # This ensures it's a file -X posix.unlink(name) -X f_out = open(name, 'w') -X while 1: -X buf = f_in.read(BUFSIZE) -X if not buf: break -X f_out.write(buf) -X del f_out # Flush data to disk before changing mode -X posix.chmod(name, mode) +X st = posix.stat(name) # Get the mode +X mode = S_IMODE(st[ST_MODE]) +X linkto = posix.readlink(name) # Make sure again it's a symlink +X f_in = open(name, 'r') # This ensures it's a file +X posix.unlink(name) +X f_out = open(name, 'w') +X while 1: +X buf = f_in.read(BUFSIZE) +X if not buf: break +X f_out.write(buf) +X del f_out # Flush data to disk before changing mode +X posix.chmod(name, mode) X Xdef mkrealdir(name): -X st = posix.stat(name) # Get the mode -X mode = S_IMODE(st[ST_MODE]) -X linkto = posix.readlink(name) -X files = posix.listdir(name) -X posix.unlink(name) -X posix.mkdir(name, mode) -X posix.chmod(name, mode) -X linkto = cat('..', linkto) -X # -X for file in files: -X if file not in ('.', '..'): -X posix.symlink(cat(linkto, file), cat(name, file)) +X st = posix.stat(name) # Get the mode +X mode = S_IMODE(st[ST_MODE]) +X linkto = posix.readlink(name) +X files = posix.listdir(name) +X posix.unlink(name) +X posix.mkdir(name, mode) +X posix.chmod(name, mode) +X linkto = cat('..', linkto) +X # +X for file in files: +X if file not in ('.', '..'): +X posix.symlink(cat(linkto, file), cat(name, file)) X Xdef main(): -X sys.stdout = sys.stderr -X progname = path.basename(sys.argv[0]) -X args = sys.argv[1:] -X if not args: -X print 'usage:', progname, 'path ...' -X sys.exit(2) -X status = 0 -X for name in args: -X if not path.islink(name): -X print progname+':', name+':', 'not a symlink' -X status = 1 -X else: -X if path.isdir(name): -X mkrealdir(name) -X else: -X mkrealfile(name) -X sys.exit(status) +X sys.stdout = sys.stderr +X progname = path.basename(sys.argv[0]) +X args = sys.argv[1:] +X if not args: +X print 'usage:', progname, 'path ...' +X sys.exit(2) +X status = 0 +X for name in args: +X if not path.islink(name): +X print progname+':', name+':', 'not a symlink' +X status = 1 +X else: +X if path.isdir(name): +X mkrealdir(name) +X else: +X mkrealfile(name) +X sys.exit(status) X Xmain() EOF @@ -98,53 +98,53 @@ Ximport posix Ximport path Ximport string X -Xkeywords = ['def', 'class'] # If you add keywords, update starts!!! -Xstarts = 'dc' # Starting characters of keywords +Xkeywords = ['def', 'class'] # If you add keywords, update starts!!! +Xstarts = 'dc' # Starting characters of keywords X Xwhitespace = string.whitespace Xidentchars = string.letters + string.digits + '_' X -Xtags = [] # Modified! +Xtags = [] # Modified! X Xdef main(): -X args = sys.argv[1:] -X for file in args: treat_file(file) -X if tags: -X fp = open('tags', 'w') -X tags.sort() -X for s in tags: fp.write(s) +X args = sys.argv[1:] +X for file in args: treat_file(file) +X if tags: +X fp = open('tags', 'w') +X tags.sort() +X for s in tags: fp.write(s) X Xdef treat_file(file): -X try: -X fp = open(file, 'r') -X except: -X print 'Cannot open', file -X return -X base = path.basename(file) -X if base[-3:] = '.py': base = base[:-3] -X s = base + '\t' + file + '\t' + '1\n' -X tags.append(s) -X while 1: -X line = fp.readline() -X if not line: break -X maketag(line, file) +X try: +X fp = open(file, 'r') +X except: +X print 'Cannot open', file +X return +X base = path.basename(file) +X if base[-3:] = '.py': base = base[:-3] +X s = base + '\t' + file + '\t' + '1\n' +X tags.append(s) +X while 1: +X line = fp.readline() +X if not line: break +X maketag(line, file) X Xdef maketag(line, file): -X i = 0 -X while line[i:i+1] in whitespace: i = i+1 -X if line[i:i+1] not in starts: return -X n = len(line) -X j = i -X while i < n and line[i] not in whitespace: i = i+1 -X if line[j:i] not in keywords: return -X while i < n and line[i] in whitespace: i = i+1 -X j = i -X while i < n and line[i] in identchars: i = i+1 -X name = line[j:i] -X while i < n and line[i] in whitespace: i = i+1 -X if i < n and line[i] = '(': i = i+1 -X s = name + '\t' + file + '\t' + '/^' + line[:i] + '/\n' -X tags.append(s) +X i = 0 +X while line[i:i+1] in whitespace: i = i+1 +X if line[i:i+1] not in starts: return +X n = len(line) +X j = i +X while i < n and line[i] not in whitespace: i = i+1 +X if line[j:i] not in keywords: return +X while i < n and line[i] in whitespace: i = i+1 +X j = i +X while i < n and line[i] in identchars: i = i+1 +X name = line[j:i] +X while i < n and line[i] in whitespace: i = i+1 +X if i < n and line[i] = '(': i = i+1 +X s = name + '\t' + file + '\t' + '/^' + line[:i] + '/\n' +X tags.append(s) X Xmain() EOF @@ -169,67 +169,67 @@ X XDEF_RATE = 3 X Xdef main(): -X # -X gain = 100 -X rate = 0 -X starter = audio.write -X stopper = 0 -X # -X optlist, args = getopt.getopt(sys.argv[1:], 'adg:r:') -X # -X for optname, optarg in optlist: -X if 0: -X pass -X elif optname = '-d': -X debug.append(1) -X elif optname = '-g': -X gain = string.atoi(optarg) -X if not (0 < gain < 256): -X raise optarg.error, '-g gain out of range' -X elif optname = '-r': -X rate = string.atoi(optarg) -X if not (1 <= rate <= 3): -X raise optarg.error, '-r rate out of range' -X elif optname = '-a': -X starter = audio.start_playing -X stopper = audio.wait_playing -X # -X audio.setoutgain(gain) -X audio.setrate(rate) -X # -X if not args: -X play(starter, rate, auds.loadfp(sys.stdin)) -X else: -X real_stopper = 0 -X for file in args: -X if real_stopper: -X real_stopper() -X play(starter, rate, auds.load(file)) -X real_stopper = stopper +X # +X gain = 100 +X rate = 0 +X starter = audio.write +X stopper = 0 +X # +X optlist, args = getopt.getopt(sys.argv[1:], 'adg:r:') +X # +X for optname, optarg in optlist: +X if 0: +X pass +X elif optname = '-d': +X debug.append(1) +X elif optname = '-g': +X gain = string.atoi(optarg) +X if not (0 < gain < 256): +X raise optarg.error, '-g gain out of range' +X elif optname = '-r': +X rate = string.atoi(optarg) +X if not (1 <= rate <= 3): +X raise optarg.error, '-r rate out of range' +X elif optname = '-a': +X starter = audio.start_playing +X stopper = audio.wait_playing +X # +X audio.setoutgain(gain) +X audio.setrate(rate) +X # +X if not args: +X play(starter, rate, auds.loadfp(sys.stdin)) +X else: +X real_stopper = 0 +X for file in args: +X if real_stopper: +X real_stopper() +X play(starter, rate, auds.load(file)) +X real_stopper = stopper X Xdef play(starter, rate, data): -X magic = data[:4] -X if magic = '0008': -X mrate = 3 -X elif magic = '0016': -X mrate = 2 -X elif magic = '0032': -X mrate = 1 -X else: -X mrate = 0 -X if mrate: -X data = data[4:] -X else: -X mrate = DEF_RATE -X if not rate: rate = mrate -X audio.setrate(rate) -X starter(data) +X magic = data[:4] +X if magic = '0008': +X mrate = 3 +X elif magic = '0016': +X mrate = 2 +X elif magic = '0032': +X mrate = 1 +X else: +X mrate = 0 +X if mrate: +X data = data[4:] +X else: +X mrate = DEF_RATE +X if not rate: rate = mrate +X audio.setrate(rate) +X starter(data) X Xtry: -X main() +X main() Xfinally: -X audio.setoutgain(0) -X audio.done() +X audio.setoutgain(0) +X audio.done() EOF chmod +x 'demo/sgi/audio/play.py' fi @@ -314,59 +314,59 @@ X# X# list of list of control points X# Xdef make_ctlpoints(): -X c = [] -X # -X ci = [] -X ci.append(-2.5, -3.7, 1.0) -X ci.append(-1.5, -3.7, 3.0) -X ci.append(1.5, -3.7, -2.5) -X ci.append(2.5, -3.7, -0.75) -X c.append(ci) -X # -X ci = [] -X ci.append(-2.5, -2.0, 3.0) -X ci.append(-1.5, -2.0, 4.0) -X ci.append(1.5, -2.0, -3.0) -X ci.append(2.5, -2.0, 0.0) -X c.append(ci) -X # -X ci = [] -X ci.append(-2.5, 2.0, 1.0) -X ci.append(-1.5, 2.0, 0.0) -X ci.append(1.5, 2.0, -1.0) -X ci.append(2.5, 2.0, 2.0) -X c.append(ci) -X # -X ci = [] -X ci.append(-2.5, 2.7, 1.25) -X ci.append(-1.5, 2.7, 0.1) -X ci.append(1.5, 2.7, -0.6) -X ci.append(2.5, 2.7, 0.2) -X c.append(ci) -X # -X return c +X c = [] +X # +X ci = [] +X ci.append(-2.5, -3.7, 1.0) +X ci.append(-1.5, -3.7, 3.0) +X ci.append(1.5, -3.7, -2.5) +X ci.append(2.5, -3.7, -0.75) +X c.append(ci) +X # +X ci = [] +X ci.append(-2.5, -2.0, 3.0) +X ci.append(-1.5, -2.0, 4.0) +X ci.append(1.5, -2.0, -3.0) +X ci.append(2.5, -2.0, 0.0) +X c.append(ci) +X # +X ci = [] +X ci.append(-2.5, 2.0, 1.0) +X ci.append(-1.5, 2.0, 0.0) +X ci.append(1.5, 2.0, -1.0) +X ci.append(2.5, 2.0, 2.0) +X c.append(ci) +X # +X ci = [] +X ci.append(-2.5, 2.7, 1.25) +X ci.append(-1.5, 2.7, 0.1) +X ci.append(1.5, 2.7, -0.6) +X ci.append(2.5, 2.7, 0.2) +X c.append(ci) +X # +X return c X Xctlpoints = make_ctlpoints () X X# X# trim knots X# -Xtrimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] +Xtrimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] X Xdef make_trimpoints(): -X c = [] -X # -X c.append(1.0, 0.0, 1.0) -X c.append(1.0, 1.0, 1.0) -X c.append(0.0, 2.0, 2.0) -X c.append(-1.0, 1.0, 1.0) -X c.append(-1.0, 0.0, 1.0) -X c.append(-1.0, -1.0, 1.0) -X c.append(0.0, -2.0, 2.0) -X c.append(1.0, -1.0, 1.0) -X c.append(1.0, 0.0, 1.0) -X # -X return c +X c = [] +X # +X c.append(1.0, 0.0, 1.0) +X c.append(1.0, 1.0, 1.0) +X c.append(0.0, 2.0, 2.0) +X c.append(-1.0, 1.0, 1.0) +X c.append(-1.0, 0.0, 1.0) +X c.append(-1.0, -1.0, 1.0) +X c.append(0.0, -2.0, 2.0) +X c.append(1.0, -1.0, 1.0) +X c.append(1.0, 0.0, 1.0) +X # +X return c X Xtrimpoints = make_trimpoints() EOF @@ -385,70 +385,70 @@ X# Draw a single 2x2x2 block with its center at (0, 0, 0) X# Arguments are the material indices (0 = don't call lmbind) X# Xdef block(m_front, m_back, m_left, m_right, m_top, m_bottom): -X # -X # Distances defining the sides -X # -X x_left = -1.0 -X x_right = 1.0 -X y_top = 1.0 -X y_bottom = -1.0 -X z_front = 1.0 -X z_back = -1.0 -X # -X # Top surface points: A, B, C, D -X # -X A = x_right, y_top, z_front -X B = x_right, y_top, z_back -X C = x_left, y_top, z_back -X D = x_left, y_top, z_front -X # -X # Bottom surface points: E, F, G, H -X # -X E = x_right, y_bottom, z_front -X F = x_right, y_bottom, z_back -X G = x_left, y_bottom, z_back -X H = x_left, y_bottom, z_front -X # -X # Draw front face -X # -X if m_front: lmbind(MATERIAL, m_front) -X n3f(0.0, 0.0, 1.0) -X face(H, E, A, D) -X # -X # Draw back face -X # -X if m_back: lmbind(MATERIAL, m_back) -X n3f(0.0, 0.0, -1.0) -X face(G, F, B, C) -X # -X # Draw left face -X # -X if m_left: lmbind(MATERIAL, m_left) -X n3f(-1.0, 0.0, 0.0) -X face(G, H, D, C) -X # -X # Draw right face -X # -X if m_right: lmbind(MATERIAL, m_right) -X n3f(1.0, 0.0, 0.0) -X face(F, E, A, B) -X # -X # Draw top face -X # -X if m_top: lmbind(MATERIAL, m_top) -X n3f(0.0, 1.0, 0.0) -X face(A, B, C, D) -X # -X # Draw bottom face -X # -X if m_bottom: lmbind(MATERIAL, m_bottom) -X n3f(0.0, -1.0, 0.0) -X face(E, F, G, H) +X # +X # Distances defining the sides +X # +X x_left = -1.0 +X x_right = 1.0 +X y_top = 1.0 +X y_bottom = -1.0 +X z_front = 1.0 +X z_back = -1.0 +X # +X # Top surface points: A, B, C, D +X # +X A = x_right, y_top, z_front +X B = x_right, y_top, z_back +X C = x_left, y_top, z_back +X D = x_left, y_top, z_front +X # +X # Bottom surface points: E, F, G, H +X # +X E = x_right, y_bottom, z_front +X F = x_right, y_bottom, z_back +X G = x_left, y_bottom, z_back +X H = x_left, y_bottom, z_front +X # +X # Draw front face +X # +X if m_front: lmbind(MATERIAL, m_front) +X n3f(0.0, 0.0, 1.0) +X face(H, E, A, D) +X # +X # Draw back face +X # +X if m_back: lmbind(MATERIAL, m_back) +X n3f(0.0, 0.0, -1.0) +X face(G, F, B, C) +X # +X # Draw left face +X # +X if m_left: lmbind(MATERIAL, m_left) +X n3f(-1.0, 0.0, 0.0) +X face(G, H, D, C) +X # +X # Draw right face +X # +X if m_right: lmbind(MATERIAL, m_right) +X n3f(1.0, 0.0, 0.0) +X face(F, E, A, B) +X # +X # Draw top face +X # +X if m_top: lmbind(MATERIAL, m_top) +X n3f(0.0, 1.0, 0.0) +X face(A, B, C, D) +X # +X # Draw bottom face +X # +X if m_bottom: lmbind(MATERIAL, m_bottom) +X n3f(0.0, -1.0, 0.0) +X face(E, F, G, H) X Xdef face(points): -X bgnpolygon() -X varray(points) -X endpolygon() +X bgnpolygon() +X varray(points) +X endpolygon() EOF fi if test -s 'demo/sgi/gl_panel/twoview/camera.s' @@ -528,52 +528,52 @@ X Xfrom Split import Split X Xclass HVSplit() = Split(): -X # -X def create(self, (parent, hv)): -X # hv is 0 or 1 for HSplit or VSplit -X self = Split.create(self, parent) -X self.hv = hv -X return self -X # -X def minsize(self, m): -X hv, vh = self.hv, 1 - self.hv -X size = [0, 0] -X for c in self.children: -X csize = c.minsize(m) -X if csize[vh] > size[vh]: size[vh] = csize[vh] -X size[hv] = size[hv] + csize[hv] -X return size[0], size[1] -X # -X def getbounds(self): -X return self.bounds -X # -X def setbounds(self, bounds): -X self.bounds = bounds -X hv, vh = self.hv, 1 - self.hv -X mf = self.parent.beginmeasuring -X size = self.minsize(mf()) -X # XXX not yet used! Later for stretching -X maxsize_hv = bounds[1][hv] - bounds[0][hv] -X origin = [self.bounds[0][0], self.bounds[0][1]] -X for c in self.children: -X size = c.minsize(mf()) -X corner = [0, 0] -X corner[vh] = bounds[1][vh] -X corner[hv] = origin[hv] + size[hv] -X c.setbounds((origin[0], origin[1]), \ -X (corner[0], corner[1])) -X origin[hv] = corner[hv] -X # XXX stretch -X # XXX too-small -X # +X # +X def create(self, (parent, hv)): +X # hv is 0 or 1 for HSplit or VSplit +X self = Split.create(self, parent) +X self.hv = hv +X return self +X # +X def minsize(self, m): +X hv, vh = self.hv, 1 - self.hv +X size = [0, 0] +X for c in self.children: +X csize = c.minsize(m) +X if csize[vh] > size[vh]: size[vh] = csize[vh] +X size[hv] = size[hv] + csize[hv] +X return size[0], size[1] +X # +X def getbounds(self): +X return self.bounds +X # +X def setbounds(self, bounds): +X self.bounds = bounds +X hv, vh = self.hv, 1 - self.hv +X mf = self.parent.beginmeasuring +X size = self.minsize(mf()) +X # XXX not yet used! Later for stretching +X maxsize_hv = bounds[1][hv] - bounds[0][hv] +X origin = [self.bounds[0][0], self.bounds[0][1]] +X for c in self.children: +X size = c.minsize(mf()) +X corner = [0, 0] +X corner[vh] = bounds[1][vh] +X corner[hv] = origin[hv] + size[hv] +X c.setbounds((origin[0], origin[1]), \ +X (corner[0], corner[1])) +X origin[hv] = corner[hv] +X # XXX stretch +X # XXX too-small +X # X Xclass HSplit() = HVSplit(): -X def create(self, parent): -X return HVSplit.create(self, (parent, 0)) +X def create(self, parent): +X return HVSplit.create(self, (parent, 0)) X Xclass VSplit() = HVSplit(): -X def create(self, parent): -X return HVSplit.create(self, (parent, 1)) +X def create(self, parent): +X return HVSplit.create(self, (parent, 1)) EOF fi if test -s 'lib/dump.py' @@ -606,44 +606,44 @@ X X# Dump a whole symbol table X# Xdef dumpsymtab(dict): -X for key in dict.keys(): -X dumpvar(key, dict[key]) +X for key in dict.keys(): +X dumpvar(key, dict[key]) X X# Dump a single variable X# Xdef dumpvar(name, x): -X import sys -X t = type(x) -X if t = type({}): -X print name, '= {}' -X for key in x.keys(): -X item = x[key] -X if not printable(item): -X print '#', -X print name, '[', `key`, '] =', `item` -X elif t in (type(''), type(0), type(0.0), type([]), type(())): -X if not printable(x): -X print '#', -X print name, '=', `x` -X elif t = type(sys): -X print 'import', name, '#', x -X else: -X print '#', name, '=', x +X import sys +X t = type(x) +X if t = type({}): +X print name, '= {}' +X for key in x.keys(): +X item = x[key] +X if not printable(item): +X print '#', +X print name, '[', `key`, '] =', `item` +X elif t in (type(''), type(0), type(0.0), type([]), type(())): +X if not printable(x): +X print '#', +X print name, '=', `x` +X elif t = type(sys): +X print 'import', name, '#', x +X else: +X print '#', name, '=', x X X# check if a value is printable in a way that can be read back with input() X# Xdef printable(x): -X t = type(x) -X if t in (type(''), type(0), type(0.0)): -X return 1 -X if t in (type([]), type(())): -X for item in x: -X if not printable(item): -X return 0 -X return 1 -X if x = {}: -X return 1 -X return 0 +X t = type(x) +X if t in (type(''), type(0), type(0.0)): +X return 1 +X if t in (type([]), type(())): +X for item in x: +X if not printable(item): +X return 0 +X return 1 +X if x = {}: +X return 1 +X return 0 EOF fi if test -s 'lib/localtime.py' @@ -655,55 +655,55 @@ X# module localtime -- Time conversions X Ximport posix X -Xepoch = 1970 # 1 jan 00:00:00, UCT -Xday0 = 4 # day 0 was a thursday +Xepoch = 1970 # 1 jan 00:00:00, UCT +Xday0 = 4 # day 0 was a thursday X Xday_names = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat') X -Xmonth_names = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') +Xmonth_names = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') Xmonth_names = month_names + ('Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') X Xmonth_sizes = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) X Xdef isleap(year): -X return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) -X -Xdef gmtime(secs): # decode time into UCT -X mins, secs = divmod(secs, 60) -X hours, mins = divmod(mins, 60) -X days, hours = divmod(hours, 24) -X wday = (day0 + days) % 7 -X year = epoch -X lp = isleap(year) -X dpy = 365 + lp -X while days >= dpy: -X days = days - dpy -X year = year + 1 -X lp = isleap(year) -X dpy = 365 + lp -X yday = days -X month = 0 -X dpm = month_sizes[month] + (lp and month = 1) -X while days >= dpm: -X days = days - dpm -X month = month + 1 -X dpm = month_sizes[month] + (lp and month = 1) -X return (year, month, days+1, hours, mins, secs, yday, wday) +X return year % 4 = 0 and (year % 100 <> 0 or year % 400 = 0) +X +Xdef gmtime(secs): # decode time into UCT +X mins, secs = divmod(secs, 60) +X hours, mins = divmod(mins, 60) +X days, hours = divmod(hours, 24) +X wday = (day0 + days) % 7 +X year = epoch +X lp = isleap(year) +X dpy = 365 + lp +X while days >= dpy: +X days = days - dpy +X year = year + 1 +X lp = isleap(year) +X dpy = 365 + lp +X yday = days +X month = 0 +X dpm = month_sizes[month] + (lp and month = 1) +X while days >= dpm: +X days = days - dpm +X month = month + 1 +X dpm = month_sizes[month] + (lp and month = 1) +X return (year, month, days+1, hours, mins, secs, yday, wday) X Xdef dd(x): -X s = `x` -X while len(s) < 2: s = '0' + s -X return s +X s = `x` +X while len(s) < 2: s = '0' + s +X return s X Xdef zd(x): -X s = `x` -X while len(s) < 2: s = ' ' + s -X return s +X s = `x` +X while len(s) < 2: s = ' ' + s +X return s X Xdef format(year, month, days, hours, mins, secs, yday, wday): -X s = day_names[wday] + ' ' + zd(days) + ' ' + month_names[month] + ' ' -X s = s + dd(hours) + ':' + dd(mins) + ':' + dd(secs) -X return s +X s = day_names[wday] + ' ' + zd(days) + ' ' + month_names[month] + ' ' +X s = s + dd(hours) + ':' + dd(mins) + ':' + dd(secs) +X return s EOF fi if test -s 'lib/poly.py' @@ -719,51 +719,51 @@ X# There is no way to suppress internal zeros; trailing zeros are X# taken out by normalize(). X Xdef normalize(p): # Strip unnecessary zero coefficients -X n = len(p) -X while p: -X if p[n-1]: return p[:n] -X n = n-1 -X return [] +X n = len(p) +X while p: +X if p[n-1]: return p[:n] +X n = n-1 +X return [] X Xdef plus(a, b): -X if len(a) < len(b): a, b = b, a # make sure a is the longest -X res = a[:] # make a copy -X for i in range(len(b)): -X res[i] = res[i] + b[i] -X return normalize(res) +X if len(a) < len(b): a, b = b, a # make sure a is the longest +X res = a[:] # make a copy +X for i in range(len(b)): +X res[i] = res[i] + b[i] +X return normalize(res) X Xdef minus(a, b): -X if len(a) < len(b): a, b = b, a # make sure a is the longest -X res = a[:] # make a copy -X for i in range(len(b)): -X res[i] = res[i] - b[i] -X return normalize(res) +X if len(a) < len(b): a, b = b, a # make sure a is the longest +X res = a[:] # make a copy +X for i in range(len(b)): +X res[i] = res[i] - b[i] +X return normalize(res) X Xdef one(power, coeff): # Representation of coeff * x**power -X res = [] -X for i in range(power): res.append(0) -X return res + [coeff] +X res = [] +X for i in range(power): res.append(0) +X return res + [coeff] X Xdef times(a, b): -X res = [] -X for i in range(len(a)): -X for j in range(len(b)): -X res = plus(res, one(i+j, a[i]*b[j])) -X return res +X res = [] +X for i in range(len(a)): +X for j in range(len(b)): +X res = plus(res, one(i+j, a[i]*b[j])) +X return res X Xdef power(a, n): # Raise polynomial a to the positive integral power n -X if n = 0: return [1] -X if n = 1: return a -X if n/2*2 = n: -X b = power(a, n/2) -X return times(b, b) -X return times(power(a, n-1), a) +X if n = 0: return [1] +X if n = 1: return a +X if n/2*2 = n: +X b = power(a, n/2) +X return times(b, b) +X return times(power(a, n-1), a) X Xdef der(a): # First derivative -X res = a[1:] -X for i in range(len(res)): -X res[i] = res[i] * (i+1) -X return res +X res = a[1:] +X for i in range(len(res)): +X res[i] = res[i] * (i+1) +X return res X X# Computing a primitive function would require rational arithmetic... EOF @@ -778,71 +778,71 @@ X Ximport posix Ximport path X -XMODEBITS = 010000 # Lower 12 mode bits +XMODEBITS = 010000 # Lower 12 mode bits X# Change this to 01000 (9 mode bits) to avoid copying setuid etc. X X# Copy data from src to dst X# Xdef copyfile(src, dst): -X fsrc = open(src, 'r') -X fdst = open(dst, 'w') -X while 1: -X buf = fsrc.read(16*1024) -X if not buf: break -X fdst.write(buf) +X fsrc = open(src, 'r') +X fdst = open(dst, 'w') +X while 1: +X buf = fsrc.read(16*1024) +X if not buf: break +X fdst.write(buf) X X# Copy mode bits from src to dst X# Xdef copymode(src, dst): -X st = posix.stat(src) -X mode = divmod(st[0], MODEBITS)[1] -X posix.chmod(dst, mode) +X st = posix.stat(src) +X mode = divmod(st[0], MODEBITS)[1] +X posix.chmod(dst, mode) X X# Copy all stat info (mode bits, atime and mtime) from src to dst X# Xdef copystat(src, dst): -X st = posix.stat(src) -X mode = divmod(st[0], MODEBITS)[1] -X posix.chmod(dst, mode) -X posix.utimes(dst, st[7:9]) +X st = posix.stat(src) +X mode = divmod(st[0], MODEBITS)[1] +X posix.chmod(dst, mode) +X posix.utimes(dst, st[7:9]) X X# Copy data and mode bits ("cp src dst") X# Xdef copy(src, dst): -X copyfile(src, dst) -X copymode(src, dst) +X copyfile(src, dst) +X copymode(src, dst) X X# Copy data and all stat info ("cp -p src dst") X# Xdef copy2(src, dst): -X copyfile(src, dst) -X copystat(src, dst) +X copyfile(src, dst) +X copystat(src, dst) X X# Recursively copy a directory tree. X# The destination must not already exist. X# Xdef copytree(src, dst): -X names = posix.listdir(src) -X posix.mkdir(dst, 0777) -X dot_dotdot = '.', '..' -X for name in names: -X if name not in dot_dotdot: -X srcname = path.cat(src, name) -X dstname = path.cat(dst, name) -X #print 'Copying', srcname, 'to', dstname -X try: -X #if path.islink(srcname): -X # linkto = posix.readlink(srcname) -X # posix.symlink(linkto, dstname) -X #elif path.isdir(srcname): -X if path.isdir(srcname): -X copytree(srcname, dstname) -X else: -X copy2(srcname, dstname) -X # XXX What about devices, sockets etc.? -X except posix.error, why: -X print 'Could not copy', srcname, 'to', dstname, -X print '(', why[1], ')' +X names = posix.listdir(src) +X posix.mkdir(dst, 0777) +X dot_dotdot = '.', '..' +X for name in names: +X if name not in dot_dotdot: +X srcname = path.cat(src, name) +X dstname = path.cat(dst, name) +X #print 'Copying', srcname, 'to', dstname +X try: +X #if path.islink(srcname): +X # linkto = posix.readlink(srcname) +X # posix.symlink(linkto, dstname) +X #elif path.isdir(srcname): +X if path.isdir(srcname): +X copytree(srcname, dstname) +X else: +X copy2(srcname, dstname) +X # XXX What about devices, sockets etc.? +X except posix.error, why: +X print 'Could not copy', srcname, 'to', dstname, +X print '(', why[1], ')' EOF fi if test -s 'lib/stdwinevents.py' @@ -853,49 +853,49 @@ sed 's/^X//' > 'lib/stdwinevents.py' << 'EOF' X# Module 'stdwinevents' -- Constants for stdwin event types X# X# Suggested usage: -X# from stdwinevents import * +X# from stdwinevents import * X X# The function stdwin.getevent() returns a tuple containing: -X# (type, window, detail) +X# (type, window, detail) X# where detail may be <no value> or a value depending on type, see below: X X# Values for type: X -XWE_NULL = 0 # not reported -- means 'no event' internally -XWE_ACTIVATE = 1 # detail is <no object> -XWE_CHAR = 2 # detail is the character -XWE_COMMAND = 3 # detail is one of the WC_* constants below -XWE_MOUSE_DOWN = 4 # detail is ((h, v), clicks, button, mask) -XWE_MOUSE_MOVE = 5 # ditto -XWE_MOUSE_UP = 6 # ditto -XWE_MENU = 7 # detail is (menu, item) -XWE_SIZE = 8 # detail is (width, height) [???] -XWE_MOVE = 9 # not reported -- reserved for future use -XWE_DRAW = 10 # detail is ((left, top), (right, bottom)) -XWE_TIMER = 11 # detail is <no object> -XWE_DEACTIVATE = 12 # detail is <no object> -XWE_EXTERN = 13 # detail is <no object> -XWE_KEY = 14 # detail is ??? -XWE_LOST_SEL = 15 # detail is selection number -XWE_CLOSE = 16 # detail is <no object> +XWE_NULL = 0 # not reported -- means 'no event' internally +XWE_ACTIVATE = 1 # detail is <no object> +XWE_CHAR = 2 # detail is the character +XWE_COMMAND = 3 # detail is one of the WC_* constants below +XWE_MOUSE_DOWN = 4 # detail is ((h, v), clicks, button, mask) +XWE_MOUSE_MOVE = 5 # ditto +XWE_MOUSE_UP = 6 # ditto +XWE_MENU = 7 # detail is (menu, item) +XWE_SIZE = 8 # detail is (width, height) [???] +XWE_MOVE = 9 # not reported -- reserved for future use +XWE_DRAW = 10 # detail is ((left, top), (right, bottom)) +XWE_TIMER = 11 # detail is <no object> +XWE_DEACTIVATE = 12 # detail is <no object> +XWE_EXTERN = 13 # detail is <no object> +XWE_KEY = 14 # detail is ??? +XWE_LOST_SEL = 15 # detail is selection number +XWE_CLOSE = 16 # detail is <no object> X X# Values for detail when type is WE_COMMAND: X -XWC_CLOSE = 1 # user hit close box -XWC_LEFT = 2 # left arrow key -XWC_RIGHT = 3 # right arrow key -XWC_UP = 4 # up arrow key -XWC_DOWN = 5 # down arrow key -XWC_CANCEL = 6 # not reported -- turned into KeyboardInterrupt -XWC_BACKSPACE = 7 # backspace key -XWC_TAB = 8 # tab key -XWC_RETURN = 9 # return or enter key +XWC_CLOSE = 1 # user hit close box +XWC_LEFT = 2 # left arrow key +XWC_RIGHT = 3 # right arrow key +XWC_UP = 4 # up arrow key +XWC_DOWN = 5 # down arrow key +XWC_CANCEL = 6 # not reported -- turned into KeyboardInterrupt +XWC_BACKSPACE = 7 # backspace key +XWC_TAB = 8 # tab key +XWC_RETURN = 9 # return or enter key X X# Selection numbers X -XWS_CLIPBOARD = 0 -XWS_PRIMARY = 1 -XWS_SECONDARY = 2 +XWS_CLIPBOARD = 0 +XWS_PRIMARY = 1 +XWS_SECONDARY = 2 EOF fi if test -s 'lib/sunaudio.py' @@ -915,48 +915,48 @@ X X# convert a 4-char value to integer X Xdef c2i(data): -X if type(data) <> type('') or len(data) <> 4: -X raise error, 'c2i: bad arg (not string[4])' -X bytes = audio.chr2num(data) -X for i in (1, 2, 3): -X if bytes[i] < 0: -X bytes[i] = bytes[i] + 256 -X return ((bytes[0]*256 + bytes[1])*256 + bytes[2])*256 + bytes[3] +X if type(data) <> type('') or len(data) <> 4: +X raise error, 'c2i: bad arg (not string[4])' +X bytes = audio.chr2num(data) +X for i in (1, 2, 3): +X if bytes[i] < 0: +X bytes[i] = bytes[i] + 256 +X return ((bytes[0]*256 + bytes[1])*256 + bytes[2])*256 + bytes[3] X X X# read a sound header from an open file X Xdef gethdr(fp): -X if fp.read(4) <> MAGIC: -X raise error, 'gethdr: bad magic word' -X hdr_size = c2i(fp.read(4)) -X data_size = c2i(fp.read(4)) -X encoding = c2i(fp.read(4)) -X sample_rate = c2i(fp.read(4)) -X channels = c2i(fp.read(4)) -X excess = hdr_size - 24 -X if excess < 0: -X raise error, 'gethdr: bad hdr_size' -X if excess > 0: -X info = fp.read(excess) -X else: -X info = '' -X return (data_size, encoding, sample_rate, channels, info) +X if fp.read(4) <> MAGIC: +X raise error, 'gethdr: bad magic word' +X hdr_size = c2i(fp.read(4)) +X data_size = c2i(fp.read(4)) +X encoding = c2i(fp.read(4)) +X sample_rate = c2i(fp.read(4)) +X channels = c2i(fp.read(4)) +X excess = hdr_size - 24 +X if excess < 0: +X raise error, 'gethdr: bad hdr_size' +X if excess > 0: +X info = fp.read(excess) +X else: +X info = '' +X return (data_size, encoding, sample_rate, channels, info) X X X# read and print the sound header of a named file X Xdef printhdr(file): -X hdr = gethdr(open(file, 'r')) -X data_size, encoding, sample_rate, channels, info = hdr -X while info[-1:] = '\0': -X info = info[:-1] -X print 'File name: ', file -X print 'Data size: ', data_size -X print 'Encoding: ', encoding -X print 'Sample rate:', sample_rate -X print 'Channels: ', channels -X print 'Info: ', `info` +X hdr = gethdr(open(file, 'r')) +X data_size, encoding, sample_rate, channels, info = hdr +X while info[-1:] = '\0': +X info = info[:-1] +X print 'File name: ', file +X print 'Data size: ', data_size +X print 'Encoding: ', encoding +X print 'Sample rate:', sample_rate +X print 'Channels: ', channels +X print 'Info: ', `info` EOF fi if test -s 'lib/whrandom.py' @@ -964,32 +964,32 @@ then echo '*** I will not over-write existing file lib/whrandom.py' else echo 'x - lib/whrandom.py' sed 's/^X//' > 'lib/whrandom.py' << 'EOF' -X# WICHMANN-HILL RANDOM NUMBER GENERATOR +X# WICHMANN-HILL RANDOM NUMBER GENERATOR X# -X# Wichmann, B. A. & Hill, I. D. (1982) -X# Algorithm AS 183: -X# An efficient and portable pseudo-random number generator -X# Applied Statistics 31 (1982) 188-190 +X# Wichmann, B. A. & Hill, I. D. (1982) +X# Algorithm AS 183: +X# An efficient and portable pseudo-random number generator +X# Applied Statistics 31 (1982) 188-190 X# -X# see also: -X# Correction to Algorithm AS 183 -X# Applied Statistics 33 (1984) 123 +X# see also: +X# Correction to Algorithm AS 183 +X# Applied Statistics 33 (1984) 123 X# -X# McLeod, A. I. (1985) -X# A remark on Algorithm AS 183 -X# Applied Statistics 34 (1985),198-200 +X# McLeod, A. I. (1985) +X# A remark on Algorithm AS 183 +X# Applied Statistics 34 (1985),198-200 X# X# -X# USE: -X# whrandom.random() yields double precision random numbers -X# uniformly distributed between 0 and 1. +X# USE: +X# whrandom.random() yields double precision random numbers +X# uniformly distributed between 0 and 1. X# -X# whrandom.seed() must be called before whrandom.random() -X# to seed the generator +X# whrandom.seed() must be called before whrandom.random() +X# to seed the generator X X -X# Translated by Guido van Rossum from C source provided by -X# Adrian Baddeley. +X# Translated by Guido van Rossum from C source provided by +X# Adrian Baddeley. X X X# The seed @@ -1000,39 +1000,39 @@ X X# Set the seed X# Xdef seed(x, y, z): -X _seed[:] = [x, y, z] +X _seed[:] = [x, y, z] X X X# Return the next random number in the range [0.0 .. 1.0) X# Xdef random(): -X from math import floor # floor() function -X # -X [x, y, z] = _seed -X x = 171 * (x % 177) - 2 * (x/177) -X y = 172 * (y % 176) - 35 * (y/176) -X z = 170 * (z % 178) - 63 * (z/178) -X # -X if x < 0: x = x + 30269 -X if y < 0: y = y + 30307 -X if z < 0: z = z + 30323 -X # -X _seed[:] = [x, y, z] -X # -X term = float(x)/30269.0 + float(y)/30307.0 + float(z)/30323.0 -X rand = term - floor(term) -X # -X if rand >= 1.0: rand = 0.0 # floor() inaccuracy? -X # -X return rand +X from math import floor # floor() function +X # +X [x, y, z] = _seed +X x = 171 * (x % 177) - 2 * (x/177) +X y = 172 * (y % 176) - 35 * (y/176) +X z = 170 * (z % 178) - 63 * (z/178) +X # +X if x < 0: x = x + 30269 +X if y < 0: y = y + 30307 +X if z < 0: z = z + 30323 +X # +X _seed[:] = [x, y, z] +X # +X term = float(x)/30269.0 + float(y)/30307.0 + float(z)/30323.0 +X rand = term - floor(term) +X # +X if rand >= 1.0: rand = 0.0 # floor() inaccuracy? +X # +X return rand X X X# Initialize from the current time X# Xdef init(): -X import time -X t = time.time() -X seed(t%256, t/256%256, t/65536%256) +X import time +X t = time.time() +X seed(t%256, t/256%256, t/65536%256) X X X# Make sure the generator is preset to a nonzero value @@ -1051,7 +1051,7 @@ XTo build the interpreter, edit the Makefile, follow the instructions Xthere, and type "make python". X XTo use the interpreter, you must set the environment variable PYTHONPATH -Xto point to the directory containing the standard modules. These are +Xto point to the directory containing the standard modules. These are Xdistributed as a sister directory called 'lib' of this source directory. XTry importing the module 'testall' to see if everything works. X @@ -1067,12 +1067,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1107,12 +1107,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1147,12 +1147,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1168,17 +1168,17 @@ X X******************************************************************/ X X/* Error codes passed around between file input, tokenizer, parser and -X interpreter. This was necessary so we can turn them into Python -X exceptions at a higher level. */ -X -X#define E_OK 10 /* No error */ -X#define E_EOF 11 /* (Unexpected) EOF read */ -X#define E_INTR 12 /* Interrupted */ -X#define E_TOKEN 13 /* Bad token */ -X#define E_SYNTAX 14 /* Syntax error */ -X#define E_NOMEM 15 /* Ran out of memory */ -X#define E_DONE 16 /* Parsing complete */ -X#define E_ERROR 17 /* Execution error */ +X interpreter. This was necessary so we can turn them into Python +X exceptions at a higher level. */ +X +X#define E_OK 10 /* No error */ +X#define E_EOF 11 /* (Unexpected) EOF read */ +X#define E_INTR 12 /* Interrupted */ +X#define E_TOKEN 13 /* Bad token */ +X#define E_SYNTAX 14 /* Syntax error */ +X#define E_NOMEM 15 /* Ran out of memory */ +X#define E_DONE 16 /* Parsing complete */ +X#define E_ERROR 17 /* Execution error */ EOF fi if test -s 'src/fileobject.h' @@ -1190,12 +1190,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1230,12 +1230,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1257,8 +1257,8 @@ Xfloatobject represents a (double precision) floating point number. X*/ X Xtypedef struct { -X OB_HEAD -X double ob_fval; +X OB_HEAD +X double ob_fval; X} floatobject; X Xextern typeobject Floattype; @@ -1281,12 +1281,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1310,23 +1310,23 @@ Xextern int errno; X Xdouble Xfmod(x, y) -X double x, y; +X double x, y; X{ -X double i, f; -X -X if (y == 0.0) { -X errno = EDOM; -X return 0.0; -X } -X -X /* return f such that x = i*y + f for some integer i -X such that |f| < |y| and f has the same sign as x */ -X -X i = floor(x/y); -X f = x - i*y; -X if ((x < 0.0) != (y < 0.0)) -X f = f-y; -X return f; +X double i, f; +X +X if (y == 0.0) { +X errno = EDOM; +X return 0.0; +X } +X +X /* return f such that x = i*y + f for some integer i +X such that |f| < |y| and f has the same sign as x */ +X +X i = floor(x/y); +X f = x - i*y; +X if ((x < 0.0) != (y < 0.0)) +X f = f-y; +X return f; X} EOF fi @@ -1339,12 +1339,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1379,12 +1379,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1417,12 +1417,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1454,12 +1454,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1487,8 +1487,8 @@ Xextern method getmethod PROTO((object *)); Xextern object *getself PROTO((object *)); X Xstruct methodlist { -X char *ml_name; -X method ml_meth; +X char *ml_name; +X method ml_meth; X}; X Xextern object *findmethod PROTO((struct methodlist *, object *, char *)); @@ -1503,12 +1503,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1537,12 +1537,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1577,12 +1577,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1601,7 +1601,7 @@ X/* Parser-tokenizer link interface */ X Xextern int parsestring PROTO((char *, grammar *, int start, node **n_ret)); Xextern int parsefile PROTO((FILE *, char *, grammar *, int start, -X char *ps1, char *ps2, node **n_ret)); +X char *ps1, char *ps2, node **n_ret)); EOF fi if test -s 'src/pgen.h' @@ -1613,12 +1613,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1650,12 +1650,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1674,7 +1674,7 @@ X/* X * The first byte of the regexp internal "program" is actually this magic X * number; the start node begins in the second byte. X */ -X#define MAGIC 0234 +X#define MAGIC 0234 EOF fi if test -s 'src/sc_errors.h' @@ -1686,12 +1686,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1707,18 +1707,18 @@ X X******************************************************************/ X X -X#define NoBufSize 1 -X#define TwoBufSize 2 -X#define StackOverflow 3 -X#define StackUnderflow 4 -X#define TypeFailure 5 -X#define RangeError 6 -X#define SizeError 7 -X#define BufferOverflow 8 -X#define NoEndLoop 9 -X#define FlagError 10 -X#define ElementIsNull 11 -X#define TransError 12 +X#define NoBufSize 1 +X#define TwoBufSize 2 +X#define StackOverflow 3 +X#define StackUnderflow 4 +X#define TypeFailure 5 +X#define RangeError 6 +X#define SizeError 7 +X#define BufferOverflow 8 +X#define NoEndLoop 9 +X#define FlagError 10 +X#define ElementIsNull 11 +X#define TransError 12 X Xextern object *err_scerr PROTO((int sc_errno)); Xextern err_scerrset PROTO((int sc_errno, object *value, char *instr)); @@ -1734,12 +1734,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1772,12 +1772,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1798,14 +1798,14 @@ X#include "string.h" X Xchar * Xstrdup(str) -X const char *str; +X const char *str; X{ -X if (str != NULL) { -X register char *copy = NEW(char, strlen(str) + 1); -X if (copy != NULL) -X return strcpy(copy, str); -X } -X return NULL; +X if (str != NULL) { +X register char *copy = NEW(char, strlen(str) + 1); +X if (copy != NULL) +X return strcpy(copy, str); +X } +X return NULL; X} EOF fi @@ -1818,12 +1818,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1839,7 +1839,7 @@ X X******************************************************************/ X X/* PD implementation of strerror() for systems that don't have it. -X Author: Guido van Rossum, CWI Amsterdam, Oct. 1990, <[email protected]>. */ +X Author: Guido van Rossum, CWI Amsterdam, Oct. 1990, <[email protected]>. */ X X#include <stdio.h> X @@ -1848,13 +1848,13 @@ Xextern char *sys_errlist[]; X Xchar * Xstrerror(err) -X int err; +X int err; X{ -X static char buf[20]; -X if (err >= 0 && err < sys_nerr) -X return sys_errlist[err]; -X sprintf(buf, "Unknown errno %d", err); -X return buf; +X static char buf[20]; +X if (err >= 0 && err < sys_nerr) +X return sys_errlist[err]; +X sprintf(buf, "Unknown errno %d", err); +X return buf; X} X X#ifdef THINK_C @@ -1872,12 +1872,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1909,12 +1909,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1938,4 +1938,4 @@ Xint tb_print PROTO((object *, FILE *)); EOF fi echo 'Part 20 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file diff --git a/shar/python-0.9.1-21-21.shar b/shar/python-0.9.1-21-21.shar index 5e50481..4aecf13 100644 --- a/shar/python-0.9.1-21-21.shar +++ b/shar/python-0.9.1-21-21.shar @@ -9,25 +9,25 @@ else echo 'x - demo/README' sed 's/^X//' > 'demo/README' << 'EOF' XThis directory contains various demonstrations of what you can do with -XPython. The demos are grouped sub(sub*)directories according to +XPython. The demos are grouped sub(sub*)directories according to Xrequired optional built-in modules. X -Xscripts Some useful Python scripts that I put in my bin -X directory. No optional built-in modules meeded. +Xscripts Some useful Python scripts that I put in my bin +X directory. No optional built-in modules meeded. X -Xsgi Demos that only run on Silicon Graphics machines. -X Require the built-in modules 'audio' and/or 'gl'. +Xsgi Demos that only run on Silicon Graphics machines. +X Require the built-in modules 'audio' and/or 'gl'. X -Xstdwin Demos that use the STDWIN library. Require the 'stdwin' -X built-in module. +Xstdwin Demos that use the STDWIN library. Require the 'stdwin' +X built-in module. X XWARNING: some scripts are executable and have a first line saying X -X #! /ufs/guido/bin/sgi/python +X #! /ufs/guido/bin/sgi/python X XThis is unlikely to give good results anywhere else except in my -Xoffice. Edit the first line before installing such scripts; to try -Xthem out, you can just say "python file.py". (The .py suffix is not +Xoffice. Edit the first line before installing such scripts; to try +Xthem out, you can just say "python file.py". (The .py suffix is not Xnecessary in this case, but makes it possible to debug the modules Xinteractively by importing them.) EOF @@ -46,24 +46,24 @@ X Ximport posix, path, sys X Xdef visit(pattern, dirname, names): -X if path.islink(dirname): -X names[:] = [] -X return -X if path.ismount(dirname): -X print 'descend into', dirname -X n = len(pattern) -X for name in names: -X name = path.cat(dirname, name) -X try: -X linkto = posix.readlink(name) -X if linkto[:n] = pattern: -X print name, '->', linkto -X except posix.error: -X pass +X if path.islink(dirname): +X names[:] = [] +X return +X if path.ismount(dirname): +X print 'descend into', dirname +X n = len(pattern) +X for name in names: +X name = path.cat(dirname, name) +X try: +X linkto = posix.readlink(name) +X if linkto[:n] = pattern: +X print name, '->', linkto +X except posix.error: +X pass X Xdef main(pattern, args): -X for dirname in args: -X path.walk(dirname, visit, pattern) +X for dirname in args: +X path.walk(dirname, visit, pattern) X Xmain(sys.argv[1], sys.argv[2:]) EOF @@ -83,24 +83,24 @@ X Ximport sys X Xdef main(): -X files = sys.argv[1:] -X suffixes = {} -X for file in files: -X suff = getsuffix(file) -X if not suffixes.has_key(suff): -X suffixes[suff] = [] -X suffixes[suff].append(file) -X keys = suffixes.keys() -X keys.sort() -X for suff in keys: -X print `suff`, len(suffixes[suff]) +X files = sys.argv[1:] +X suffixes = {} +X for file in files: +X suff = getsuffix(file) +X if not suffixes.has_key(suff): +X suffixes[suff] = [] +X suffixes[suff].append(file) +X keys = suffixes.keys() +X keys.sort() +X for suff in keys: +X print `suff`, len(suffixes[suff]) X Xdef getsuffix(file): -X suff = '' -X for i in range(len(file)): -X if file[i] = '.': -X suff = file[i:] -X return suff +X suff = '' +X for i in range(len(file)): +X if file[i] = '.': +X suff = file[i:] +X return suff X Xmain() EOF @@ -114,18 +114,18 @@ sed 's/^X//' > 'demo/sgi/README' << 'EOF' XDemonstrations of Python that use various features of the Silicon XGraphics IRIS machines. X -Xaudio Demonstrations of the audio capabilities of the 4D/25. -X Require the built-in module 'audio'. +Xaudio Demonstrations of the audio capabilities of the 4D/25. +X Require the built-in module 'audio'. X -Xaudio_stdwin Window-based demonstrations the audio capabilities of -X the 4D/25. Require the built-in modules 'stdwin' and -X 'audio'. +Xaudio_stdwin Window-based demonstrations the audio capabilities of +X the 4D/25. Require the built-in modules 'stdwin' and +X 'audio'. X -Xgl Demonstrations of the Graphics Library (GL). -X Require the built-in module 'gl'. +Xgl Demonstrations of the Graphics Library (GL). +X Require the built-in module 'gl'. X -Xgl_panel Demonstrations of the Panel Library by NASA Ames. -X Require the built-in modules 'gl' and 'pnl'. +Xgl_panel Demonstrations of the Panel Library by NASA Ames. +X Require the built-in modules 'gl' and 'pnl'. EOF fi if test -s 'demo/sgi/audio/README' @@ -136,8 +136,8 @@ sed 's/^X//' > 'demo/sgi/audio/README' << 'EOF' XPrograms that demonstrate the use of the audio device on the SGI 4D/25. XThese require the built-in module 'audio'. X -Xplay Read a sound sample from a file and play it through the -X speaker. Options to set volume, sampling rate etc. +Xplay Read a sound sample from a file and play it through the +X speaker. Options to set volume, sampling rate etc. EOF fi if test -s 'demo/sgi/audio_stdwin/vumeter.py' @@ -159,25 +159,25 @@ XBUFSIZE = NBUFS*48 XSCALE=128 X Xclass MyVUMeter() = VUMeter(): -X def init_reactivity(self): -X self.parent.need_mouse(self) -X def mouse_down(self, detail): -X if self.enabled: -X self.stop() -X else: -X self.start() -X def mouse_move(self, detail): pass -X def mouse_up(self, detail): pass +X def init_reactivity(self): +X self.parent.need_mouse(self) +X def mouse_down(self, detail): +X if self.enabled: +X self.stop() +X else: +X self.start() +X def mouse_move(self, detail): pass +X def mouse_up(self, detail): pass X Xdef main(): -X audio.setrate(3) -X audio.setoutgain(0) -X w = WindowParent().create('VU Meter', (200, 100)) -X v = MyVUMeter().define(w) -X v.start() -X w.realize() -X while 1: -X w.dispatch(stdwin.getevent()) +X audio.setrate(3) +X audio.setoutgain(0) +X w = WindowParent().create('VU Meter', (200, 100)) +X v = MyVUMeter().define(w) +X v.start() +X w.realize() +X while 1: +X w.dispatch(stdwin.getevent()) X Xmain() EOF @@ -190,26 +190,26 @@ echo 'x - demo/sgi/gl/README' sed 's/^X//' > 'demo/sgi/gl/README' << 'EOF' XThese demos run only on SGI machines and require the 'gl' built-in module. XThe demonstrate the abilities of SGI's GL library as well as the ease of -XGL programming in Python. Most demos require the Z-buffer (aka +XGL programming in Python. Most demos require the Z-buffer (aka X24-bitplane) option. X -Xbackface Demonstrates the 'backface' GL function. +Xbackface Demonstrates the 'backface' GL function. X -Xkites Show 3 flying kites. Demonstrates the rendering speed -X obtainable by Python programs. +Xkites Show 3 flying kites. Demonstrates the rendering speed +X obtainable by Python programs. X -Xmclock A colorful clock with more options than you can -X remember. Works on 8-bit machines (but allows more -X colors on 24-bit machines). +Xmclock A colorful clock with more options than you can +X remember. Works on 8-bit machines (but allows more +X colors on 24-bit machines). X -Xmixing Demonstrates the effect of color mixing: through -X frequent color switching it gives the effect of white -X light. +Xmixing Demonstrates the effect of color mixing: through +X frequent color switching it gives the effect of white +X light. X -Xnurbs A simple demonstration of the 'nurbs' GL functions. +Xnurbs A simple demonstration of the 'nurbs' GL functions. X -Xzrgb Displays a 3-D Gouraud-shaded figure which can be moved -X around with the mouse. +Xzrgb Displays a 3-D Gouraud-shaded figure which can be moved +X around with the mouse. EOF fi if test -s 'demo/sgi/gl_panel/README' @@ -219,27 +219,27 @@ echo 'x - demo/sgi/gl_panel/README' sed 's/^X//' > 'demo/sgi/gl_panel/README' << 'EOF' XThis directory contains demos that use the Panel Library by NASA Ames. XThey only run on SGI machines and require the 'pnl' and 'gl' built-in -Xmodules. Each subdirectory contains one demo. -X -Xapanel A trivial user interface to the audio capabilities of -X the 4D/25 (Personal IRIS). Lets you record a sample and -X play it back at different volumes. Requires the 'audio' -X built-in module. -X -Xflying A large demonstration that can display several -X differently shaped objects through space. Control -X panels let you manipulate light sources, material -X properties and drawing modes. -X -Xnurbs A demo of the capabilities of the GL 'nurbs' functions -X that can display the control points. (It was intended -X to let you move these as well, but there was a problem -X with the mapping of mouse movements in a 3-D world.) -X -Xtwoview A demo of GL's transformation primitives. Two views on -X a scene are given, and the position and orientation of a -X viewer in one of the views can be changed through -X various buttons and dials in a control panel. +Xmodules. Each subdirectory contains one demo. +X +Xapanel A trivial user interface to the audio capabilities of +X the 4D/25 (Personal IRIS). Lets you record a sample and +X play it back at different volumes. Requires the 'audio' +X built-in module. +X +Xflying A large demonstration that can display several +X differently shaped objects through space. Control +X panels let you manipulate light sources, material +X properties and drawing modes. +X +Xnurbs A demo of the capabilities of the GL 'nurbs' functions +X that can display the control points. (It was intended +X to let you move these as well, but there was a problem +X with the mapping of mouse movements in a 3-D world.) +X +Xtwoview A demo of GL's transformation primitives. Two views on +X a scene are given, and the position and orientation of a +X viewer in one of the views can be changed through +X various buttons and dials in a control panel. EOF fi if test -s 'demo/sgi/gl_panel/apanel/apanel.py' @@ -263,51 +263,51 @@ X Ximport audio X Xdef main(): -X gl.foreground() -X gl.noport() -X #gl.prefposition(700, 850, 950, 970) -X wid = gl.winopen('audio demo') -X # -X panels = panel.defpanellist('apanel.s') # XXX -X p = panels[0] -X p.playbackbutton.back = p -X p.recordbutton.back = p -X p.sample = '' -X # -X def quit(a): -X sys.exit(0) -X # -X p.quitbutton.downfunc = quit -X # -X def playback(a): -X p = a.back -X gain = int(255.0*p.outputgain.val) -X a.val = 1.0 -X a.fixact() -X panel.drawpanel() -X audio.setoutgain(gain) -X audio.write(p.sample) -X audio.setoutgain(0) -X a.val = 0.0 -X a.fixact() -X # -X p.playbackbutton.downfunc = playback -X # -X def record(a): -X p = a.back -X size = int(10.0 * 8192.0 * p.recordsize.val) -X a.val = 1.0 -X a.fixact() -X panel.drawpanel() -X audio.setoutgain(0) -X p.sample = audio.read(size) -X a.val = 0.0 -X a.fixact() -X # -X p.recordbutton.downfunc = record -X # -X while 1: -X act = panel.dopanel() +X gl.foreground() +X gl.noport() +X #gl.prefposition(700, 850, 950, 970) +X wid = gl.winopen('audio demo') +X # +X panels = panel.defpanellist('apanel.s') # XXX +X p = panels[0] +X p.playbackbutton.back = p +X p.recordbutton.back = p +X p.sample = '' +X # +X def quit(a): +X sys.exit(0) +X # +X p.quitbutton.downfunc = quit +X # +X def playback(a): +X p = a.back +X gain = int(255.0*p.outputgain.val) +X a.val = 1.0 +X a.fixact() +X panel.drawpanel() +X audio.setoutgain(gain) +X audio.write(p.sample) +X audio.setoutgain(0) +X a.val = 0.0 +X a.fixact() +X # +X p.playbackbutton.downfunc = playback +X # +X def record(a): +X p = a.back +X size = int(10.0 * 8192.0 * p.recordsize.val) +X a.val = 1.0 +X a.fixact() +X panel.drawpanel() +X audio.setoutgain(0) +X p.sample = audio.read(size) +X a.val = 0.0 +X a.fixact() +X # +X p.recordbutton.downfunc = record +X # +X while 1: +X act = panel.dopanel() X Xmain() EOF @@ -321,27 +321,27 @@ sed 's/^X//' > 'demo/sgi/gl_panel/flying/material.py' << 'EOF' Ximport light X Xdef mkmatdict () : -X m = {} -X m['material 1'] = light.m1 -X m['material 2'] = light.m2 -X m['material 3'] = light.m3 -X m['material 4'] = light.m4 -X m['material 5'] = light.m5 -X m['material 6'] = light.m6 -X m['material 7'] = light.m7 -X m['material 8'] = light.m8 -X m['material 9'] = light.m9 -X # -X return m +X m = {} +X m['material 1'] = light.m1 +X m['material 2'] = light.m2 +X m['material 3'] = light.m3 +X m['material 4'] = light.m4 +X m['material 5'] = light.m5 +X m['material 6'] = light.m6 +X m['material 7'] = light.m7 +X m['material 8'] = light.m8 +X m['material 9'] = light.m9 +X # +X return m X Xmaterdict = mkmatdict () X Xdef mklichtdict () : -X m = {} -X m['light 1'] = light.light1 -X m['light 2'] = light.light2 -X # -X return m +X m = {} +X m['light 1'] = light.light1 +X m['light 2'] = light.light2 +X # +X return m X Xlichtdict = mklichtdict () EOF @@ -376,14 +376,14 @@ Xobjects['table'] = [ZERO, o8] X X# 'putDict' sets the value of entry 'key' of dictionary 'dict' Xdef putDict(dict, key, val) : -X dict[key][0] = val +X dict[key][0] = val X X# -X# 'getDict' get the contents of entry i of key 'key' +X# 'getDict' get the contents of entry i of key 'key' X# of dictionary 'dict' X# Xdef getDict(dict, key, i) : -X return dict[key][i] +X return dict[key][i] X X# the 'options' dictionary contains the strings of the menu items X# that denote the options @@ -459,8 +459,8 @@ Xstarted. X XThe following are the important latex source files: X -X tut.tex A tutorial -X mod.tex The library reference +X tut.tex A tutorial +X mod.tex The library reference X XThey both read the style option file "myformat.sty". X @@ -473,9 +473,9 @@ XType "make clean" to get rid of all the intermediate files produced by Xthe latex process, and other junk files. X XYou can just as well ignore the Makefile; all you really need is: -X latex tut -X latex tut -X dvips tut | lpr +X latex tut +X latex tut +X dvips tut | lpr Xand similar for the "mod" document. EOF fi @@ -485,22 +485,22 @@ else echo 'x - doc/SetClass.py' sed 's/^X//' > 'doc/SetClass.py' << 'EOF' Xclass Set(): -X def new(self): -X self.elements = [] -X return self -X def add(self, e): -X if e not in self.elements: -X self.elements.append(e) -X def remove(self, e): -X if e in self.elements: -X for i in range(len(self.elements)): -X if self.elements[i] = e: -X del self.elements[i] -X break -X def is_element(self, e): -X return e in self.elements -X def size(self): -X return len(self.elements) +X def new(self): +X self.elements = [] +X return self +X def add(self, e): +X if e not in self.elements: +X self.elements.append(e) +X def remove(self, e): +X if e in self.elements: +X for i in range(len(self.elements)): +X if self.elements[i] = e: +X del self.elements[i] +X break +X def is_element(self, e): +X return e in self.elements +X def size(self): +X return len(self.elements) EOF fi if test -s 'doc/fibo.py' @@ -510,19 +510,19 @@ echo 'x - doc/fibo.py' sed 's/^X//' > 'doc/fibo.py' << 'EOF' X# Fibonacci numbers demo X -Xdef fib(n): # write Fibonacci series up to n -X a, b = 0, 1 -X while b <= n: -X print b, -X a, b = b, a+b +Xdef fib(n): # write Fibonacci series up to n +X a, b = 0, 1 +X while b <= n: +X print b, +X a, b = b, a+b X Xdef fib2(n): # return Fibonacci series up to n -X ret = [] -X a, b = 0, 1 -X while b <= n: -X ret.append(b) -X a, b = b, a+b -X return ret +X ret = [] +X a, b = 0, 1 +X while b <= n: +X ret.append(b) +X a, b = b, a+b +X return ret EOF fi if test -s 'doc/mod.tex' @@ -537,7 +537,7 @@ X\documentstyle[11pt,myformat]{article} X X% A command to force the text after an item to start on a new line X\newcommand{\itembreak}{ -X \mbox{}\\*[0mm] +X \mbox{}\\*[0mm] X} X X% A command to define a function item @@ -549,16 +549,16 @@ X\item[#1 = {\tt '#2'}] X\itembreak X} X -X\title{\bf -X Python Library Reference \\ -X (DRAFT) +X itle{\bf +X Python Library Reference \\ +X (DRAFT) X} X X\author{ -X Guido van Rossum \\ -X Dept. CST, CWI, Kruislaan 413 \\ -X 1098 SJ Amsterdam, The Netherlands \\ -X E-mail: {\tt [email protected]} +X Guido van Rossum \\ +X Dept. CST, CWI, Kruislaan 413 \\ +X 1098 SJ Amsterdam, The Netherlands \\ +X E-mail: {\tt [email protected]} X} X X\begin{document} @@ -581,7 +581,7 @@ X\end{abstract} X X\pagebreak X -X\tableofcontents +X ableofcontents X X\pagebreak X @@ -602,36 +602,36 @@ sed 's/^X//' > 'doc/myformat.sty' << 'EOF' X% Style parameters and macros used by all documents here X X% Page lay-out parameters -X\textwidth = 160mm -X\textheight = 240mm -X\topmargin = -11mm -X\oddsidemargin = 0mm -X\evensidemargin = 0mm -X%\parindent = 0mm +X extwidth = 160mm +X extheight = 240mm +X opmargin = -11mm +X\oddsidemargin = 0mm +X\evensidemargin = 0mm +X%\parindent = 0mm X X% Frequently used system names -X\newcommand{\Python}{Python} % Sometimes I want this italicized +X\newcommand{\Python}{Python} % Sometimes I want this italicized X\newcommand{\UNIX}{U{\sc nix}} X X% Variable used by begin code command X\newlength{\codewidth} X X\newcommand{\bcode}{ -X % Calculate the text width for the minipage: -X \setlength{\codewidth}{\linewidth} -X \addtolength{\codewidth}{-\parindent} -X % -X \vspace{3mm} -X \par -X \indent -X \begin{minipage}[t]{\codewidth} +X % Calculate the text width for the minipage: +X \setlength{\codewidth}{\linewidth} +X \addtolength{\codewidth}{-\parindent} +X % +X \vspace{3mm} +X \par +X \indent +X \begin{minipage}[t]{\codewidth} X} X X\newcommand{\ecode}{ -X \end{minipage} -X \vspace{3mm} -X \par -X \noindent +X \end{minipage} +X \vspace{3mm} +X \par +X \noindent X} EOF fi @@ -646,17 +646,17 @@ X Xcat $* >$TMP X X( -X cat $TMP -X -X sed ' -X s/^>>> // -X s/^>>>$// -X s/^\.\.\. // -X s/^\.\.\.$// -X ' $TMP | -X python -X -X echo '>>> ' +X cat $TMP +X +X sed ' +X s/^>>> // +X s/^>>>$// +X s/^\.\.\. // +X s/^\.\.\.$// +X ' $TMP | +X python +X +X echo '>>> ' X) 2>&1 X Xrm $TMP @@ -675,33 +675,33 @@ X X# A Histogram displays a histogram of numeric data. X# Xclass HistogramAppearance() = LabelAppearance(), Define(): -X # -X def define(self, parent): -X Define.define(self, (parent, '')) -X self.ydata = [] -X self.scale = (0, 100) -X return self -X # -X def setdata(self, (ydata, scale)): -X self.ydata = ydata -X self.scale = scale # (min, max) -X self.parent.change(self.bounds) -X # -X def drawpict(self, d): -X (left, top), (right, bottom) = self.bounds -X min, max = self.scale -X size = max-min -X width, height = right-left, bottom-top -X ydata = self.ydata -X npoints = len(ydata) -X v1 = top + height # constant -X h1 = left # changed in loop -X for i in range(npoints): -X h0 = h1 -X v0 = top + height - (ydata[i]-min)*height/size -X h1 = left + (i+1) * width/npoints -X d.paint((h0, v0), (h1, v1)) -X # +X # +X def define(self, parent): +X Define.define(self, (parent, '')) +X self.ydata = [] +X self.scale = (0, 100) +X return self +X # +X def setdata(self, (ydata, scale)): +X self.ydata = ydata +X self.scale = scale # (min, max) +X self.parent.change(self.bounds) +X # +X def drawpict(self, d): +X (left, top), (right, bottom) = self.bounds +X min, max = self.scale +X size = max-min +X width, height = right-left, bottom-top +X ydata = self.ydata +X npoints = len(ydata) +X v1 = top + height # constant +X h1 = left # changed in loop +X for i in range(npoints): +X h0 = h1 +X v0 = top + height - (ydata[i]-min)*height/size +X h1 = left + (i+1) * width/npoints +X d.paint((h0, v0), (h1, v1)) +X # X Xclass Histogram() = NoReactivity(), HistogramAppearance(): pass EOF @@ -717,36 +717,36 @@ Ximport audio Xfrom Histogram import Histogram X Xclass Soundogram() = Histogram(): -X # -X def define(self, (win, chunk)): -X width, height = corner = win.getwinsize() -X bounds = (0, 0), corner -X self.chunk = chunk -X self.step = (len(chunk)-1)/(width/2+1) + 1 -X ydata = _make_ydata(chunk, self.step) -X return Histogram.define(self, (win, bounds, ydata, (0, 128))) -X # -X def setchunk(self, chunk): -X self.chunk = chunk -X self.recompute() -X # -X def recompute(self): -X (left, top), (right, bottom) = self.bounds -X width = right - left -X self.step = (len(chunk)-1)/width + 1 -X ydata = _make_ydata(chunk, self.step) -X self.setdata(ydata, (0, 128)) -X # +X # +X def define(self, (win, chunk)): +X width, height = corner = win.getwinsize() +X bounds = (0, 0), corner +X self.chunk = chunk +X self.step = (len(chunk)-1)/(width/2+1) + 1 +X ydata = _make_ydata(chunk, self.step) +X return Histogram.define(self, (win, bounds, ydata, (0, 128))) +X # +X def setchunk(self, chunk): +X self.chunk = chunk +X self.recompute() +X # +X def recompute(self): +X (left, top), (right, bottom) = self.bounds +X width = right - left +X self.step = (len(chunk)-1)/width + 1 +X ydata = _make_ydata(chunk, self.step) +X self.setdata(ydata, (0, 128)) +X # X X Xdef _make_ydata(chunk, step): -X ydata = [] -X for i in range(0, len(chunk), step): -X piece = audio.chr2num(chunk[i:i+step]) -X mi, ma = min(piece), max(piece) -X y = max(abs(mi), abs(ma)) -X ydata.append(y) -X return ydata +X ydata = [] +X for i in range(0, len(chunk), step): +X piece = audio.chr2num(chunk[i:i+step]) +X mi, ma = min(piece), max(piece) +X y = max(abs(mi), abs(ma)) +X ydata.append(y) +X return ydata EOF fi if test -s 'lib/TestCSplit.py' @@ -762,22 +762,22 @@ Xfrom WindowParent import WindowParent Xfrom Buttons import PushButton X Xdef main(n): -X from CSplit import CSplit -X -X the_window = WindowParent().create('TestCSplit', (0, 0)) -X the_csplit = CSplit().create(the_window) -X -X for i in range(n): -X the_child = PushButton().define(the_csplit) -X the_child.settext(`(i+n-1)%n+1`) -X -X the_window.realize() -X -X while 1: -X the_event = stdwin.getevent() -X if the_event[0] = WE_CLOSE: break -X the_window.dispatch(the_event) -X the_window.destroy() +X from CSplit import CSplit +X +X the_window = WindowParent().create('TestCSplit', (0, 0)) +X the_csplit = CSplit().create(the_window) +X +X for i in range(n): +X the_child = PushButton().define(the_csplit) +X the_child.settext(`(i+n-1)%n+1`) +X +X the_window.realize() +X +X while 1: +X the_event = stdwin.getevent() +X if the_event[0] = WE_CLOSE: break +X the_window.dispatch(the_event) +X the_window.destroy() X Xmain(12) EOF @@ -796,44 +796,44 @@ XK = 1024 XRates = [0, 32*K, 16*K, 8*K] X Xclass VUMeter() = StripChart(): -X # -X # Override define() and timer() methods -X # -X def define(self, parent): -X self = StripChart.define(self, (parent, 128)) -X self.parent.need_timer(self) -X self.sampling = 0 -X self.rate = 3 -X self.enable(0) -X return self -X # -X def timer(self): -X if self.sampling: -X chunk = audio.wait_recording() -X self.sampling = 0 -X nums = audio.chr2num(chunk) -X ampl = max(abs(min(nums)), abs(max(nums))) -X self.append(ampl) -X if self.enabled and not self.sampling: -X audio.setrate(self.rate) -X size = Rates[self.rate]/10 -X size = size/48*48 -X audio.start_recording(size) -X self.sampling = 1 -X if self.sampling: -X self.parent.settimer(1) -X # -X # New methods: start() and stop() -X # -X def stop(self): -X if self.sampling: -X chunk = audio.stop_recording() -X self.sampling = 0 -X self.enable(0) -X # -X def start(self): -X self.enable(1) -X self.timer() +X # +X # Override define() and timer() methods +X # +X def define(self, parent): +X self = StripChart.define(self, (parent, 128)) +X self.parent.need_timer(self) +X self.sampling = 0 +X self.rate = 3 +X self.enable(0) +X return self +X # +X def timer(self): +X if self.sampling: +X chunk = audio.wait_recording() +X self.sampling = 0 +X nums = audio.chr2num(chunk) +X ampl = max(abs(min(nums)), abs(max(nums))) +X self.append(ampl) +X if self.enabled and not self.sampling: +X audio.setrate(self.rate) +X size = Rates[self.rate]/10 +X size = size/48*48 +X audio.start_recording(size) +X self.sampling = 1 +X if self.sampling: +X self.parent.settimer(1) +X # +X # New methods: start() and stop() +X # +X def stop(self): +X if self.sampling: +X chunk = audio.stop_recording() +X self.sampling = 0 +X self.enable(0) +X # +X def start(self): +X self.enable(1) +X self.timer() EOF fi if test -s 'lib/anywin.py' @@ -849,12 +849,12 @@ Ximport filewin Ximport path X Xdef open(name): -X print 'opening', name, '...' -X if path.isdir(name): -X w = dirwin.open(name) -X else: -X w = filewin.open(name) -X return w +X print 'opening', name, '...' +X if path.isdir(name): +X w = dirwin.open(name) +X else: +X w = filewin.open(name) +X return w EOF fi if test -s 'lib/dircache.py' @@ -874,30 +874,30 @@ X Xcache = {} X Xdef listdir(path): # List directory contents, using cache -X try: -X cached_mtime, list = cache[path] -X del cache[path] -X except RuntimeError: -X cached_mtime, list = -1, [] -X try: -X mtime = posix.stat(path)[8] -X except posix.error: -X return [] -X if mtime <> cached_mtime: -X try: -X list = posix.listdir(path) -X except posix.error: -X return [] -X list.sort() -X cache[path] = mtime, list -X return list +X try: +X cached_mtime, list = cache[path] +X del cache[path] +X except RuntimeError: +X cached_mtime, list = -1, [] +X try: +X mtime = posix.stat(path)[8] +X except posix.error: +X return [] +X if mtime <> cached_mtime: +X try: +X list = posix.listdir(path) +X except posix.error: +X return [] +X list.sort() +X cache[path] = mtime, list +X return list X Xopendir = listdir # XXX backward compatibility X Xdef annotate(head, list): # Add '/' suffixes to directories -X for i in range(len(list)): -X if path.isdir(path.cat(head, list[i])): -X list[i] = list[i] + '/' +X for i in range(len(list)): +X if path.isdir(path.cat(head, list[i])): +X list[i] = list[i] + '/' EOF fi if test -s 'lib/dirwin.py' @@ -916,24 +916,24 @@ Ximport path Ximport dircache X Xdef action(w, string, i, detail): -X (h, v), clicks, button, mask = detail -X if clicks = 2: -X name = path.cat(w.name, string) -X try: -X w2 = anywin.open(name) -X w2.parent = w -X except posix.error, why: -X stdwin.message('Can\'t open ' + name + ': ' + why[1]) +X (h, v), clicks, button, mask = detail +X if clicks = 2: +X name = path.cat(w.name, string) +X try: +X w2 = anywin.open(name) +X w2.parent = w +X except posix.error, why: +X stdwin.message('Can\'t open ' + name + ': ' + why[1]) X Xdef open(name): -X name = path.cat(name, '') -X list = dircache.opendir(name)[:] -X list.sort() -X dircache.annotate(name, list) -X w = listwin.open(name, list) -X w.name = name -X w.action = action -X return w +X name = path.cat(name, '') +X list = dircache.opendir(name)[:] +X list.sort() +X dircache.annotate(name, list) +X w = listwin.open(name, list) +X w.name = name +X w.action = action +X return w EOF fi if test -s 'lib/fact.py' @@ -946,36 +946,36 @@ X Ximport sys Ximport math X -Xerror = 'fact.error' # exception +Xerror = 'fact.error' # exception X Xdef fact(n): -X if n < 1: raise error # fact() argument should be >= 1 -X if n = 1: return [] # special case -X res = [] -X _fact(n, 2, res) -X return res +X if n < 1: raise error # fact() argument should be >= 1 +X if n = 1: return [] # special case +X res = [] +X _fact(n, 2, res) +X return res X Xdef _fact(n, lowest, res): -X highest = int(math.sqrt(float(n+1))) -X for i in range(lowest, highest+1): -X if n%i = 0: -X res.append(i) -X _fact(n/i, i, res) -X break -X else: -X res.append(n) +X highest = int(math.sqrt(float(n+1))) +X for i in range(lowest, highest+1): +X if n%i = 0: +X res.append(i) +X _fact(n/i, i, res) +X break +X else: +X res.append(n) X Xdef main(): -X if len(sys.argv) > 1: -X for arg in sys.argv[1:]: -X n = eval(arg) -X print n, fact(n) -X else: -X try: -X while 1: -X print fact(input()) -X except EOFError: -X pass +X if len(sys.argv) > 1: +X for arg in sys.argv[1:]: +X n = eval(arg) +X print n, fact(n) +X else: +X try: +X while 1: +X print fact(input()) +X except EOFError: +X pass X Xmain() EOF @@ -995,14 +995,14 @@ X X# FILE WINDOW X Xdef open_readonly(fn): # Open a file window -X w = textwin.open_readonly(fn, readfile(fn)) -X w.fn = fn -X return w +X w = textwin.open_readonly(fn, readfile(fn)) +X w.fn = fn +X return w X Xdef open(fn): # Open a file window -X w = textwin.open(fn, readfile(fn)) -X w.fn = fn -X return w +X w = textwin.open(fn, readfile(fn)) +X w.fn = fn +X return w EOF fi if test -s 'lib/fnmatch.py' @@ -1015,36 +1015,36 @@ X X# XXX [] patterns are not supported (but recognized) X Xdef fnmatch(name, pat): -X if '*' in pat or '?' in pat or '[' in pat: -X return fnmatch1(name, pat) -X return name = pat +X if '*' in pat or '?' in pat or '[' in pat: +X return fnmatch1(name, pat) +X return name = pat X Xdef fnmatch1(name, pat): -X for i in range(len(pat)): -X c = pat[i] -X if c = '*': -X restpat = pat[i+1:] -X if '*' in restpat or '?' in restpat or '[' in restpat: -X for i in range(i, len(name)): -X if fnmatch1(name[i:], restpat): -X return 1 -X return 0 -X else: -X return name[len(name)-len(restpat):] = restpat -X elif c = '?': -X if len(name) <= i : return 0 -X elif c = '[': -X return 0 # XXX -X else: -X if name[i:i+1] <> c: -X return 0 -X return 1 +X for i in range(len(pat)): +X c = pat[i] +X if c = '*': +X restpat = pat[i+1:] +X if '*' in restpat or '?' in restpat or '[' in restpat: +X for i in range(i, len(name)): +X if fnmatch1(name[i:], restpat): +X return 1 +X return 0 +X else: +X return name[len(name)-len(restpat):] = restpat +X elif c = '?': +X if len(name) <= i : return 0 +X elif c = '[': +X return 0 # XXX +X else: +X if name[i:i+1] <> c: +X return 0 +X return 1 X Xdef fnmatchlist(names, pat): -X res = [] -X for name in names: -X if fnmatch(name, pat): res.append(name) -X return res +X res = [] +X for name in names: +X if fnmatch(name, pat): res.append(name) +X return res EOF fi if test -s 'lib/glob.py' @@ -1059,43 +1059,43 @@ Ximport path Ximport fnmatch X Xdef glob(pathname): -X if not has_magic(pathname): return [pathname] -X dirname, basename = path.split(pathname) -X if dirname[-1:] = '/' and dirname <> '/': -X dirname = dirname[:-1] -X if has_magic(dirname): -X list = glob(dirname) -X else: -X list = [dirname] -X if not has_magic(basename): -X result = [] -X for dirname in list: -X if basename or path.isdir(dirname): -X name = path.cat(dirname, basename) -X if path.exists(name): -X result.append(name) -X else: -X result = [] -X for dirname in list: -X sublist = glob1(dirname, basename) -X for name in sublist: -X result.append(path.cat(dirname, name)) -X return result +X if not has_magic(pathname): return [pathname] +X dirname, basename = path.split(pathname) +X if dirname[-1:] = '/' and dirname <> '/': +X dirname = dirname[:-1] +X if has_magic(dirname): +X list = glob(dirname) +X else: +X list = [dirname] +X if not has_magic(basename): +X result = [] +X for dirname in list: +X if basename or path.isdir(dirname): +X name = path.cat(dirname, basename) +X if path.exists(name): +X result.append(name) +X else: +X result = [] +X for dirname in list: +X sublist = glob1(dirname, basename) +X for name in sublist: +X result.append(path.cat(dirname, name)) +X return result X Xdef glob1(dirname, pattern): -X if not dirname: dirname = '.' -X try: -X names = posix.listdir(dirname) -X except posix.error: -X return [] -X result = [] -X for name in names: -X if name[0] <> '.' or pattern[0] = '.': -X if fnmatch.fnmatch(name, pattern): result.append(name) -X return result +X if not dirname: dirname = '.' +X try: +X names = posix.listdir(dirname) +X except posix.error: +X return [] +X result = [] +X for name in names: +X if name[0] <> '.' or pattern[0] = '.': +X if fnmatch.fnmatch(name, pattern): result.append(name) +X return result X Xdef has_magic(s): -X return '*' in s or '?' in s or '[' in s +X return '*' in s or '?' in s or '[' in s EOF fi if test -s 'lib/grep.py' @@ -1109,32 +1109,32 @@ Ximport regexp Ximport string X Xdef grep(expr, filename): -X prog = regexp.compile(expr) -X fp = open(filename, 'r') -X lineno = 0 -X while 1: -X line = fp.readline() -X if not line: break -X lineno = lineno + 1 -X res = prog.exec(line) -X if res: -X #print res -X start, end = res[0] -X if line[-1:] = '\n': line = line[:-1] -X prefix = string.rjust(`lineno`, 3) + ': ' -X print prefix + line -X if 0: -X line = line[:start] -X if '\t' not in line: -X prefix = ' ' * (len(prefix) + start) -X else: -X prefix = ' ' * len(prefix) -X for c in line: -X if c <> '\t': c = ' ' -X prefix = prefix + c -X if start = end: prefix = prefix + '\\' -X else: prefix = prefix + '^'*(end-start) -X print prefix +X prog = regexp.compile(expr) +X fp = open(filename, 'r') +X lineno = 0 +X while 1: +X line = fp.readline() +X if not line: break +X lineno = lineno + 1 +X res = prog.exec(line) +X if res: +X #print res +X start, end = res[0] +X if line[-1:] = '\n': line = line[:-1] +X prefix = string.rjust(`lineno`, 3) + ': ' +X print prefix + line +X if 0: +X line = line[:start] +X if '\t' not in line: +X prefix = ' ' * (len(prefix) + start) +X else: +X prefix = ' ' * len(prefix) +X for c in line: +X if c <> '\t': c = ' ' +X prefix = prefix + c +X if start = end: prefix = prefix + '\\' +X else: prefix = prefix + '^'*(end-start) +X print prefix EOF fi if test -s 'lib/maccache.py' @@ -1169,40 +1169,40 @@ XFILE = 1 XLISTTYPE = type([]) X Xdef _stat(name): -X name = macpath.cat(cwd, name) -X if cache.has_key(name): -X return cache[name] -X if macpath.isfile(name): -X cache[name] = FILE -X return FILE -X try: -X list = mac.listdir(name) -X except: -X cache[name] = NONE -X return NONE -X cache[name] = list -X if name[-1:] = ':': cache[name[:-1]] = list -X else: cache[name+':'] = list -X return list +X name = macpath.cat(cwd, name) +X if cache.has_key(name): +X return cache[name] +X if macpath.isfile(name): +X cache[name] = FILE +X return FILE +X try: +X list = mac.listdir(name) +X except: +X cache[name] = NONE +X return NONE +X cache[name] = list +X if name[-1:] = ':': cache[name[:-1]] = list +X else: cache[name+':'] = list +X return list X Xdef isdir(name): -X st = _stat(name) -X return type(st) = LISTTYPE +X st = _stat(name) +X return type(st) = LISTTYPE X Xdef isfile(name): -X st = _stat(name) -X return st = FILE +X st = _stat(name) +X return st = FILE X Xdef exists(name): -X st = _stat(name) -X return st <> NONE +X st = _stat(name) +X return st <> NONE X Xdef listdir(name): -X st = _stat(name) -X if type(st) = LISTTYPE: -X return st -X else: -X raise RuntimeError, 'list non-directory' +X st = _stat(name) +X if type(st) = LISTTYPE: +X return st +X else: +X raise RuntimeError, 'list non-directory' EOF fi if test -s 'lib/macglob.py' @@ -1220,42 +1220,42 @@ Ximport macpath Ximport fnmatch X Xdef glob(pathname): -X if not has_magic(pathname): return [pathname] -X dirname, basename = macpath.split(pathname) -X if has_magic(dirname): -X if dirname[-1:] = ':': dirname = dirname[:-1] -X list = glob(dirname) -X else: -X list = [dirname] -X if not has_magic(basename): -X result = [] -X for dirname in list: -X if basename or macpath.isdir(dirname): -X name = macpath.cat(dirname, basename) -X if macpath.exists(name): -X result.append(name) -X else: -X result = [] -X for dirname in list: -X sublist = glob1(dirname, basename) -X for name in sublist: -X result.append(macpath.cat(dirname, name)) -X return result +X if not has_magic(pathname): return [pathname] +X dirname, basename = macpath.split(pathname) +X if has_magic(dirname): +X if dirname[-1:] = ':': dirname = dirname[:-1] +X list = glob(dirname) +X else: +X list = [dirname] +X if not has_magic(basename): +X result = [] +X for dirname in list: +X if basename or macpath.isdir(dirname): +X name = macpath.cat(dirname, basename) +X if macpath.exists(name): +X result.append(name) +X else: +X result = [] +X for dirname in list: +X sublist = glob1(dirname, basename) +X for name in sublist: +X result.append(macpath.cat(dirname, name)) +X return result X Xdef glob1(dirname, pattern): -X if not dirname: dirname = ':' -X try: -X names = mac.listdir(dirname) -X except mac.error: -X return [] -X result = [] -X for name in names: -X if name[0] <> '.' or pattern[0] = '.': -X if fnmatch.fnmatch(name, pattern): result.append(name) -X return result +X if not dirname: dirname = ':' +X try: +X names = mac.listdir(dirname) +X except mac.error: +X return [] +X result = [] +X for name in names: +X if name[0] <> '.' or pattern[0] = '.': +X if fnmatch.fnmatch(name, pattern): result.append(name) +X return result X Xdef has_magic(s): -X return '*' in s or '?' in s or '[' in s +X return '*' in s or '?' in s or '[' in s EOF fi if test -s 'lib/minmax.py' @@ -1284,46 +1284,46 @@ Xfrom stat import ST_MTIME X X# Pack one file Xdef pack(outfp, file, name): -X fp = open(file, 'r') -X outfp.write('sed "s/^X//" >' + name + ' <<"!"\n') -X while 1: -X line = fp.readline() -X if not line: break -X if line[-1:] <> '\n': -X line = line + '\n' -X outfp.write('X' + line) -X outfp.write('!\n') +X fp = open(file, 'r') +X outfp.write('sed "s/^X//" >' + name + ' <<"!"\n') +X while 1: +X line = fp.readline() +X if not line: break +X if line[-1:] <> '\n': +X line = line + '\n' +X outfp.write('X' + line) +X outfp.write('!\n') X X# Pack some files from a directory Xdef packsome(outfp, dirname, names): -X for name in names: -X print name -X file = macpath.cat(dirname, name) -X pack(outfp, file, name) +X for name in names: +X print name +X file = macpath.cat(dirname, name) +X pack(outfp, file, name) X X# Pack all files from a directory Xdef packall(outfp, dirname): -X names = mac.listdir(dirname) -X names.sort() -X packsome(outfp, dirname, names) +X names = mac.listdir(dirname) +X names.sort() +X packsome(outfp, dirname, names) X X# Pack all files from a directory that are not older than a give one Xdef packnotolder(outfp, dirname, oldest): -X names = mac.listdir(dirname) -X oldest = macpath.cat(dirname, oldest) -X st = mac.stat(oldest) -X mtime = st[ST_MTIME] -X todo = [] -X for name in names: -X print name, '...', -X st = mac.stat(macpath.cat(dirname, name)) -X if st[ST_MTIME] >= mtime: -X print 'Yes.' -X todo.append(name) -X else: -X print 'No.' -X todo.sort() -X packsome(outfp, dirname, todo) +X names = mac.listdir(dirname) +X oldest = macpath.cat(dirname, oldest) +X st = mac.stat(oldest) +X mtime = st[ST_MTIME] +X todo = [] +X for name in names: +X print name, '...', +X st = mac.stat(macpath.cat(dirname, name)) +X if st[ST_MTIME] >= mtime: +X print 'Yes.' +X todo.append(name) +X else: +X print 'No.' +X todo.sort() +X packsome(outfp, dirname, todo) EOF fi if test -s 'lib/rand.py' @@ -1336,13 +1336,13 @@ X Ximport whrandom X Xdef srand(seed): -X whrandom.seed(seed%256, seed/256%256, seed/65536%256) +X whrandom.seed(seed%256, seed/256%256, seed/65536%256) X Xdef rand(): -X return int(whrandom.random() * 32768.0) % 32768 +X return int(whrandom.random() * 32768.0) % 32768 X Xdef choice(seq): -X return seq[rand() % len(seq)] +X return seq[rand() % len(seq)] EOF fi if test -s 'lib/stat.py' @@ -1363,50 +1363,50 @@ X# Suggested usage: from stat import * X X# Tuple indices for stat struct members X -XST_MODE = 0 -XST_INO = 1 -XST_DEV = 2 +XST_MODE = 0 +XST_INO = 1 +XST_DEV = 2 XST_NLINK = 3 -XST_UID = 4 -XST_GID = 5 -XST_SIZE = 6 +XST_UID = 4 +XST_GID = 5 +XST_SIZE = 6 XST_ATIME = 7 XST_MTIME = 8 XST_CTIME = 9 X Xdef S_IMODE(mode): -X return mode%4096 +X return mode%4096 Xdef S_IFMT(mode): -X return mode - mode%4096 -X -XS_IFDIR = 0040000 -XS_IFCHR = 0020000 -XS_IFBLK = 0060000 -XS_IFREG = 0100000 -XS_IFIFO = 0010000 -XS_IFLNK = 0120000 +X return mode - mode%4096 +X +XS_IFDIR = 0040000 +XS_IFCHR = 0020000 +XS_IFBLK = 0060000 +XS_IFREG = 0100000 +XS_IFIFO = 0010000 +XS_IFLNK = 0120000 XS_IFSOCK = 0140000 X Xdef S_ISDIR(mode): -X return S_IFMT(mode) = S_IFDIR +X return S_IFMT(mode) = S_IFDIR X Xdef S_ISCHR(mode): -X return S_IFMT(mode) = S_IFCHR +X return S_IFMT(mode) = S_IFCHR X Xdef S_ISBLK(mode): -X return S_IFMT(mode) = S_IFBLK +X return S_IFMT(mode) = S_IFBLK X Xdef S_ISREG(mode): -X return S_IFMT(mode) = S_IFREG +X return S_IFMT(mode) = S_IFREG X Xdef S_ISFIFO(mode): -X return S_IFMT(mode) = S_IFIFO +X return S_IFMT(mode) = S_IFIFO X Xdef S_ISLNK(mode): -X return S_IFMT(mode) = S_IFLNK +X return S_IFMT(mode) = S_IFLNK X Xdef S_ISSOCK(mode): -X return S_IFMT(mode) = S_IFSOCK +X return S_IFMT(mode) = S_IFSOCK EOF fi if test -s 'lib/stdwinsupport.py' @@ -1418,36 +1418,36 @@ X# Module 'stdwinsupport' X Ximport stdwin X -Xeventnames = ['null', 'activate', 'char', 'command'] +Xeventnames = ['null', 'activate', 'char', 'command'] Xeventnames = eventnames + ['mouse_down', 'mouse_move', 'mouse_up', 'menu'] Xeventnames = eventnames + ['size', 'move', 'draw', 'timer', 'deactivate'] X -Xwe_null = 0 -Xwe_activate = 1 -Xwe_char = 2 -Xwe_command = 3 -Xwe_mouse_down = 4 -Xwe_mouse_move = 5 -Xwe_mouse_up = 6 -Xwe_menu = 7 -Xwe_size = 8 -Xwe_move = 9 -Xwe_draw = 10 -Xwe_timer = 11 +Xwe_null = 0 +Xwe_activate = 1 +Xwe_char = 2 +Xwe_command = 3 +Xwe_mouse_down = 4 +Xwe_mouse_move = 5 +Xwe_mouse_up = 6 +Xwe_menu = 7 +Xwe_size = 8 +Xwe_move = 9 +Xwe_draw = 10 +Xwe_timer = 11 Xwe_deactivate = 12 X Xcommandnames = ['?', 'close', 'left', 'right', 'up', 'down', 'cancel'] Xcommandnames = commandnames + ['backspace', 'tab', 'return'] X -Xwc_close = 1 -Xwc_left = 2 -Xwc_right = 3 -Xwc_up = 4 -Xwc_down = 5 -Xwc_cancel = 6 # not reported -- turned into KeyboardInterrupt +Xwc_close = 1 +Xwc_left = 2 +Xwc_right = 3 +Xwc_up = 4 +Xwc_down = 5 +Xwc_cancel = 6 # not reported -- turned into KeyboardInterrupt Xwc_backspace = 7 -Xwc_tab = 8 -Xwc_return = 9 +Xwc_tab = 8 +Xwc_return = 9 EOF fi if test -s 'lib/util.py' @@ -1463,28 +1463,28 @@ X# No complaints if it isn't in the list at all. X# If it occurs more than once, remove the first occurrence. X# Xdef remove(item, list): -X for i in range(len(list)): -X if list[i] = item: -X del list[i] -X break +X for i in range(len(list)): +X if list[i] = item: +X del list[i] +X break X X X# Return a string containing a file's contents. X# Xdef readfile(fn): -X return readopenfile(open(fn, 'r')) +X return readopenfile(open(fn, 'r')) X X X# Read an open file until EOF. X# Xdef readopenfile(fp): -X BUFSIZE = 512*8 -X data = '' -X while 1: -X buf = fp.read(BUFSIZE) -X if not buf: break -X data = data + buf -X return data +X BUFSIZE = 512*8 +X data = '' +X while 1: +X buf = fp.read(BUFSIZE) +X if not buf: break +X data = data + buf +X return data EOF fi if test -s 'src/To.do' @@ -1499,10 +1499,10 @@ X X- why do reads from stdin fail when I suspend the process? X X- introduce macros to set/inspect errno for syscalls, to support things -X like getoserr() +X like getoserr() X X- fix interrupt handling (interruptable system calls should call -X intrcheck() to clear the interrupt status) +X intrcheck() to clear the interrupt status) EOF fi if test -s 'src/assert.h' @@ -1514,12 +1514,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1546,12 +1546,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1580,12 +1580,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1612,12 +1612,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1645,12 +1645,12 @@ X/*********************************************************** XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The XNetherlands. X -X All Rights Reserved +X All Rights Reserved X -XPermission to use, copy, modify, and distribute this software and its -Xdocumentation for any purpose and without fee is hereby granted, +XPermission to use, copy, modify, and distribute this software and its +Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and that -Xboth that copyright notice and this permission notice appear in +Xboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting Mathematisch XCentrum or CWI not be used in advertising or publicity pertaining to Xdistribution of the software without specific, written prior permission. @@ -1666,10 +1666,10 @@ X X******************************************************************/ X X -X#define CAP 0 -X#define STUBC 1 -X#define NAME 2 +X#define CAP 0 +X#define STUBC 1 +X#define NAME 2 EOF fi echo 'Part 21 out of 21 of pack.out complete.' -exit 0 +exit 0
\ No newline at end of file |
