home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 2 / 2809 < prev    next >
Encoding:
Internet Message Format  |  1991-02-20  |  60.7 KB

  1. From: guido@cwi.nl (Guido van Rossum)
  2. Newsgroups: alt.sources
  3. Subject: Python 0.9.1 part 17/21
  4. Message-ID: <2979@charon.cwi.nl>
  5. Date: 19 Feb 91 17:42:37 GMT
  6.  
  7. : This is a shell archive.
  8. : Extract with 'sh this_file'.
  9. :
  10. : Extract part 01 first since it makes all directories
  11. echo 'Start of pack.out, part 17 out of 21:'
  12. if test -s 'demo/sgi/gl/nurbs.py'
  13. then echo '*** I will not over-write existing file demo/sgi/gl/nurbs.py'
  14. else
  15. echo 'x - demo/sgi/gl/nurbs.py'
  16. sed 's/^X//' > 'demo/sgi/gl/nurbs.py' << 'EOF'
  17. X#! /ufs/guido/bin/sgi/python
  18. X
  19. X# Rotate a 3D surface created using NURBS.
  20. X#
  21. X# Press left mouse button to toggle surface trimming.
  22. X# Press ESC to quit.
  23. X#
  24. X# See the GL manual for an explanation of NURBS.
  25. X
  26. Xfrom gl import *
  27. Xfrom GL import *
  28. Xfrom DEVICE import *
  29. X
  30. XTRUE = 1
  31. XFALSE = 0
  32. XORDER = 4
  33. X
  34. Xidmat = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]
  35. X
  36. Xsurfknots = [-1, -1, -1, -1, 1, 1, 1, 1]
  37. X
  38. Xdef make_ctlpoints():
  39. X    c = []
  40. X    #
  41. X    ci = []
  42. X    ci.append(-2.5,  -3.7,  1.0)
  43. X    ci.append(-1.5,  -3.7,  3.0)
  44. X    ci.append(1.5,  -3.7, -2.5)
  45. X    ci.append(2.5,  -3.7,  -0.75)
  46. X    c.append(ci)
  47. X    #
  48. X    ci = []
  49. X    ci.append(-2.5,  -2.0,  3.0)
  50. X    ci.append(-1.5,  -2.0,  4.0)
  51. X    ci.append(1.5,  -2.0,  -3.0)
  52. X    ci.append(2.5,  -2.0,  0.0)
  53. X    c.append(ci)
  54. X    #
  55. X    ci = []
  56. X    ci.append(-2.5, 2.0,  1.0)
  57. X    ci.append(-1.5, 2.0,  0.0)
  58. X    ci.append(1.5,  2.0,  -1.0)
  59. X    ci.append(2.5,  2.0,  2.0)
  60. X    c.append(ci)
  61. X    #
  62. X    ci = []
  63. X    ci.append(-2.5,  2.7,  1.25)
  64. X    ci.append(-1.5,  2.7,  0.1)
  65. X    ci.append(1.5,  2.7,  -0.6)
  66. X    ci.append(2.5,  2.7,  0.2)
  67. X    c.append(ci)
  68. X    #
  69. X    return c
  70. X
  71. Xctlpoints = make_ctlpoints()
  72. X
  73. Xtrimknots = [0., 0., 0.,  1., 1.,  2., 2.,  3., 3.,   4., 4., 4.]
  74. X
  75. Xdef make_trimpoints():
  76. X    c = []
  77. X    c.append(1.0, 0.0, 1.0)
  78. X    c.append(1.0, 1.0, 1.0)
  79. X    c.append(0.0, 2.0, 2.0)
  80. X    c.append(-1.0, 1.0, 1.0)
  81. X    c.append(-1.0, 0.0, 1.0)
  82. X    c.append(-1.0, -1.0, 1.0)
  83. X    c.append(0.0, -2.0, 2.0)
  84. X    c.append(1.0, -1.0, 1.0) 
  85. X    c.append(1.0, 0.0, 1.0)
  86. X    return c
  87. X
  88. Xtrimpoints = make_trimpoints()
  89. X
  90. Xdef main():
  91. X    init_windows()
  92. X    setup_queue()
  93. X    make_lights()
  94. X    init_view()
  95. X    #
  96. X    set_scene()
  97. X    setnurbsproperty( N_ERRORCHECKING, 1.0 )
  98. X    setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 )
  99. X    trim_flag = 0
  100. X    draw_trim_surface(trim_flag)
  101. X    #
  102. X    while 1:
  103. X        while qtest():
  104. X            dev, val = qread()
  105. X            if dev = ESCKEY:
  106. X                return
  107. X            elif dev = WINQUIT:
  108. X                dglclose(-1)    # this for DGL only
  109. X                return
  110. X            elif dev = REDRAW:
  111. X                reshapeviewport()
  112. X                set_scene()
  113. X                draw_trim_surface(trim_flag)
  114. X            elif dev = LEFTMOUSE:
  115. X                if val:
  116. X                    trim_flag = (not trim_flag)
  117. X        set_scene()
  118. X        draw_trim_surface(trim_flag)
  119. X
  120. Xdef init_windows():
  121. X    foreground()
  122. X    #prefposition(0, 500, 0, 500)
  123. X    wid = winopen('nurbs')
  124. X    wintitle('NURBS Surface')
  125. X    doublebuffer()
  126. X    RGBmode()
  127. X    gconfig()
  128. X    lsetdepth(0x000, 0x7fffff)
  129. X    zbuffer( TRUE )
  130. X
  131. Xdef setup_queue():
  132. X    qdevice(ESCKEY)
  133. X    qdevice(REDRAW)
  134. X    qdevice(RIGHTMOUSE)
  135. X    qdevice(WINQUIT)
  136. X    qdevice(LEFTMOUSE) #trimming
  137. X
  138. Xdef init_view():
  139. X    mmode(MPROJECTION)
  140. X    ortho( -4., 4., -4., 4., -4., 4. )
  141. X    #
  142. X    mmode(MVIEWING)
  143. X    loadmatrix(idmat)
  144. X    #
  145. X    lmbind(MATERIAL, 1)
  146. X
  147. Xdef set_scene():
  148. X    lmbind(MATERIAL, 0)
  149. X    RGBcolor(150,150,150)
  150. X    lmbind(MATERIAL, 1)
  151. X    clear()
  152. X    zclear()
  153. X    #
  154. X    rotate( 100, 'y' )
  155. X    rotate( 100, 'z' )
  156. X
  157. Xdef draw_trim_surface(trim_flag):
  158. X    bgnsurface()
  159. X    nurbssurface(surfknots, surfknots, ctlpoints, ORDER, ORDER, N_XYZ)
  160. X    if trim_flag:
  161. X        bgntrim()
  162. X        nurbscurve(trimknots, trimpoints, ORDER-1, N_STW)
  163. X        endtrim()
  164. X    endsurface()
  165. X    swapbuffers()
  166. X
  167. Xdef make_lights():
  168. X    lmdef(DEFLMODEL,1,[])
  169. X    lmdef(DEFLIGHT,1,[])
  170. X    #
  171. X    # define material #1
  172. X    #
  173. X    a = []
  174. X    a = a + [EMISSION, 0.0, 0.0, 0.0]
  175. X    a = a + [AMBIENT,  0.1, 0.1, 0.1]
  176. X    a = a + [DIFFUSE,  0.6, 0.3, 0.3]
  177. X    a = a + [SPECULAR,  0.0, 0.6, 0.0]
  178. X    a = a + [SHININESS, 2.0]
  179. X    a = a + [LMNULL]
  180. X    lmdef(DEFMATERIAL, 1, a)
  181. X    #
  182. X    # turn on lighting
  183. X    #
  184. X    lmbind(LIGHT0, 1)
  185. X    lmbind(LMODEL, 1)
  186. X
  187. Xmain()
  188. EOF
  189. chmod +x 'demo/sgi/gl/nurbs.py'
  190. fi
  191. if test -s 'demo/sgi/gl/zrgb.py'
  192. then echo '*** I will not over-write existing file demo/sgi/gl/zrgb.py'
  193. else
  194. echo 'x - demo/sgi/gl/zrgb.py'
  195. sed 's/^X//' > 'demo/sgi/gl/zrgb.py' << 'EOF'
  196. X#! /ufs/guido/bin/sgi/python
  197. X
  198. X#   zrgb  (Requires Z buffer.)
  199. X#
  200. X# This program demostrates zbuffering 3 intersecting RGB polygons while
  201. X# in doublebuffer mode where, movement of the mouse with the LEFTMOUSE 
  202. X# button depressed will, rotate the 3 polygons. This is done by compound
  203. X# rotations allowing continuous screen-oriented rotations. 
  204. X#
  205. X#    Press the "Esc" key to exit.  
  206. X
  207. Xfrom gl import *
  208. Xfrom GL import *
  209. Xfrom DEVICE import *
  210. X
  211. X
  212. Xobjmat=[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]
  213. X
  214. 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]
  215. X
  216. Xdef main() :
  217. X    #
  218. X    # old and new mouse position
  219. X    #
  220. X    #
  221. X    mode = 0
  222. X    omx = 0
  223. X    mx = 0
  224. X    omy = 0
  225. X    my = 0
  226. X    #
  227. X    initialize ()
  228. X    #
  229. X    draw_scene (objmat)
  230. X    #
  231. X    while (1) :
  232. X        #
  233. X        dev, val = qread()
  234. X        #
  235. X        if dev = ESCKEY :
  236. X            if val :
  237. X                break    
  238. X            # exit when key is going up, not down
  239. X            # this avoids the scenario where a window 
  240. X            # underneath this program's window
  241. X            # would otherwise "eat up" the up-
  242. X            # event of the Esc key being released
  243. X            return        
  244. X            #
  245. X        elif dev = REDRAW :
  246. X            reshapeviewport()
  247. X            draw_scene(objmat)
  248. X            #
  249. X        elif dev = LEFTMOUSE:
  250. X            omx = mx
  251. X            omy = my
  252. X            if val :
  253. X                mode = 1
  254. X            else :
  255. X                mode = 0
  256. X        elif dev = MOUSEX :
  257. X            omx = mx
  258. X            mx = val
  259. X            #print omx, mx
  260. X            objmat = update_scene(objmat,mx,my,omx,omy,mode)
  261. X            #
  262. X        elif dev = MOUSEY :
  263. X            omy = my
  264. X            my = val
  265. X            #print omy, my
  266. X            objmat = update_scene(objmat,mx,my,omx,omy,mode)
  267. X            #
  268. X
  269. X
  270. Xdef initialize () :
  271. X    #
  272. X    foreground ()
  273. X    keepaspect(5, 4)
  274. X    w = winopen('Zbuffered RGB')
  275. X    #
  276. X    doublebuffer()
  277. X    RGBmode()
  278. X    gconfig()
  279. X    zbuffer(1)
  280. X    lsetdepth(0x0, 0x7FFFFF)
  281. X    #
  282. X    qdevice(ESCKEY)
  283. X    qdevice(LEFTMOUSE)
  284. X    qdevice(MOUSEX)
  285. X    qdevice(MOUSEY)
  286. X
  287. Xdef update_scene (mat, mx, my, omx, omy, mode) :
  288. X    #
  289. X    if mode = 1 :
  290. X        mat = orient(mat, mx, my, omx, omy)
  291. X        draw_scene(mat)
  292. X    return mat
  293. X
  294. Xdef orient (mat, mx, my, omx, omy) :
  295. X    #
  296. X    #
  297. X    pushmatrix()
  298. X    loadmatrix(idmat)
  299. X    #
  300. X    if mx - omx : rot (float (mx - omx), 'y')
  301. X    if omy - my : rot (float (omy - my), 'x')
  302. X    #
  303. X    multmatrix(mat)
  304. X    mat = getmatrix()
  305. X    #
  306. X    #
  307. X    popmatrix()
  308. X    #
  309. X    return mat
  310. X
  311. Xdef draw_scene (mat) :
  312. X    RGBcolor(40, 100, 200)
  313. X    clear()
  314. X    zclear()
  315. X    #
  316. X    perspective(400, 1.25, 30.0, 60.0)
  317. X    translate(0.0, 0.0, -40.0)
  318. X    multmatrix(mat)
  319. X    #
  320. X    # skews original view to show all polygons
  321. X    #
  322. X    rotate(-580, 'y')
  323. X    draw_polys()
  324. X    #
  325. X    swapbuffers()
  326. X
  327. Xpolygon1 = [(-10.0,-10.0,0.0),(10.0,-10.0,0.0),(-10.0,10.0,0.0)]
  328. X
  329. Xpolygon2 = [(0.0,-10.0,-10.0),(0.0,-10.0,10.0),(0.0,5.0,-10.0)]
  330. X
  331. 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)]
  332. X
  333. Xdef draw_polys():
  334. X    bgnpolygon()
  335. X    cpack(0x0)
  336. X    v3f(polygon1[0])
  337. X    cpack(0x007F7F7F)
  338. X    v3f(polygon1[1])
  339. X    cpack(0x00FFFFFF)
  340. X    v3f(polygon1[2])
  341. X    endpolygon()
  342. X    #
  343. X    bgnpolygon()
  344. X    cpack(0x0000FFFF)
  345. X    v3f(polygon2[0])
  346. X    cpack(0x007FFF00)
  347. X    v3f(polygon2[1])
  348. X    cpack(0x00FF0000)
  349. X    v3f(polygon2[2])
  350. X    endpolygon()
  351. X    #
  352. X    bgnpolygon()
  353. X    cpack(0x0000FFFF)
  354. X    v3f(polygon3[0])
  355. X    cpack(0x00FF00FF)
  356. X    v3f(polygon3[1])
  357. X    cpack(0x00FF0000)
  358. X    v3f(polygon3[2])
  359. X    cpack(0x00FF00FF)
  360. X    v3f(polygon3[3])
  361. X    endpolygon()
  362. X
  363. X
  364. Xmain ()
  365. EOF
  366. chmod +x 'demo/sgi/gl/zrgb.py'
  367. fi
  368. if test -s 'demo/sgi/gl_panel/flying/flying.s'
  369. then echo '*** I will not over-write existing file demo/sgi/gl_panel/flying/flying.s'
  370. else
  371. echo 'x - demo/sgi/gl_panel/flying/flying.s'
  372. sed 's/^X//' > 'demo/sgi/gl_panel/flying/flying.s' << 'EOF'
  373. X;;; This file was automatically generated by the panel editor.
  374. X;;; If you read it into gnu emacs, it will automagically format itself.
  375. X
  376. X(panel (prop help creator:user-panel-help)
  377. X(prop user-panel #t)
  378. X(label "flying objects")
  379. X(al (pnl_toggle_button (name "table")
  380. X(prop help creator:user-act-help)
  381. X(label "table")
  382. X(x 4.75)
  383. X(y 0.25)
  384. X(downfunc move-then-resize)
  385. X)
  386. X(pnl_toggle_button (name "pyramid")
  387. X(prop help creator:user-act-help)
  388. X(label "pyramid")
  389. X(x 4.75)
  390. X(y 0.75)
  391. X(downfunc move-then-resize)
  392. X)
  393. X(pnl_toggle_button (name "glass")
  394. X(prop help creator:user-act-help)
  395. X(label "glass")
  396. X(x 4.75)
  397. X(y 1.25)
  398. X(downfunc move-then-resize)
  399. X)
  400. X(pnl_toggle_button (name "diamond")
  401. X(prop help creator:user-act-help)
  402. X(label "diamond")
  403. X(x 4.75)
  404. X(y 1.75)
  405. X(downfunc move-then-resize)
  406. X)
  407. X(pnl_toggle_button (name "disk")
  408. X(prop help creator:user-act-help)
  409. X(label "disk")
  410. X(x 4.75)
  411. X(y 2.25)
  412. X(downfunc move-then-resize)
  413. X)
  414. X(pnl_toggle_button (name "icecream")
  415. X(prop help creator:user-act-help)
  416. X(label "ice cream")
  417. X(x 4.75)
  418. X(y 2.75)
  419. X(downfunc move-then-resize)
  420. X)
  421. X(pnl_toggle_button (name "cube")
  422. X(prop help creator:user-act-help)
  423. X(label "cube")
  424. X(x 4.75)
  425. X(y 3.25)
  426. X(val 1)
  427. X(downfunc move-then-resize)
  428. X)
  429. X(pnl_toggle_button (name "cylinder")
  430. X(prop help creator:user-act-help)
  431. X(label "cylinder")
  432. X(x 4.75)
  433. X(y 3.75)
  434. X(downfunc move-then-resize)
  435. X)
  436. X(pnl_toggle_button (name "sphere")
  437. X(prop help creator:user-act-help)
  438. X(label "sphere")
  439. X(x 4.75)
  440. X(y 4.25)
  441. X(downfunc move-then-resize)
  442. X)
  443. X(pnl_button (name "quit")
  444. X(prop help creator:user-act-help)
  445. X(label "quit")
  446. X(x 0.25)
  447. X(y 2.25)
  448. X(w 1.3)
  449. X(h 0.65)
  450. X(labeltype 16)
  451. X(downfunc move-then-resize)
  452. X)
  453. X(pnl_button (name "showall")
  454. X(prop help creator:user-act-help)
  455. X(label "show all")
  456. X(x 3.75)
  457. X(y 3.75)
  458. X(labeltype 8)
  459. X(downfunc move-then-resize)
  460. X)
  461. X(pnl_button (name "shownone")
  462. X(prop help creator:user-act-help)
  463. X(label "show none")
  464. X(x 3.75)
  465. X(y 3.25)
  466. X(labeltype 8)
  467. X(downfunc move-then-resize)
  468. X)
  469. X(pnl_radio_button (name "wire")
  470. X(prop end-of-group #t)
  471. X(prop help creator:user-act-help)
  472. X(label "wire frame")
  473. X(x 0.25)
  474. X(y 4.5)
  475. X(h 0.36)
  476. X(downfunc move-then-resize)
  477. X)
  478. X(pnl_radio_button (name "filled")
  479. X(prop help creator:user-act-help)
  480. X(label "filled")
  481. X(x 0.25)
  482. X(y 4)
  483. X(h 0.36)
  484. X(val 1)
  485. X(downfunc move-then-resize)
  486. X)
  487. X(pnl_radio_button (name "flat")
  488. X(prop end-of-group #t)
  489. X(prop help creator:user-act-help)
  490. X(label "flat shaded")
  491. X(x 0.25)
  492. X(y 0.5)
  493. X(h 0.36)
  494. X(downfunc move-then-resize)
  495. X)
  496. X(pnl_radio_button (name "gouraud")
  497. X(prop help creator:user-act-help)
  498. X(label "gouraud shaded")
  499. X(x 0.25)
  500. X(h 0.36)
  501. X(val 1)
  502. X(downfunc move-then-resize)
  503. X)
  504. X)
  505. X)
  506. X;;; Local Variables:
  507. X;;; mode: scheme
  508. X;;; eval: (save-excursion (goto-char (point-min)) (kill-line 3))
  509. X;;; eval: (save-excursion (goto-char (point-min)) (replace-regexp "[ \n]*)" ")"))
  510. X;;; eval: (indent-region (point-min) (point-max) nil)
  511. X;;; eval: (progn (kill-line -3) (delete-backward-char 1) (save-buffer))
  512. X;;; End:
  513. EOF
  514. fi
  515. if test -s 'demo/sgi/gl_panel/flying/objectdef.py'
  516. then echo '*** I will not over-write existing file demo/sgi/gl_panel/flying/objectdef.py'
  517. else
  518. echo 'x - demo/sgi/gl_panel/flying/objectdef.py'
  519. sed 's/^X//' > 'demo/sgi/gl_panel/flying/objectdef.py' << 'EOF'
  520. Xfrom math import *
  521. Xfrom objdict import *
  522. Xfrom gl import *
  523. X
  524. XFUZZY = 0.00001
  525. X
  526. X# first try - brute force method (ala M.Overmars...)
  527. X
  528. Xdef makespinobject (smooth,rot,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2) :
  529. X    object = []
  530. X    dth = 2.0 * pi / float (rot)
  531. X    for i in range (0, n) :
  532. X        for j in range (0, rot) :
  533. X            th = dth * float (j)
  534. X            #
  535. X            if smooth = 1:
  536. X                a1 = th
  537. X                a2 =th+dth
  538. X            else :
  539. X                a1 = th + dth / 2.0
  540. X                a2 = th + dth / 2.0
  541. X            #
  542. X            v0 = (x1[i]*sin(th),x1[i]*cos(th),z1[i])
  543. X            n0 = (nx1[i]*sin(a1),nx1[i]*cos(a1),nz1[i])
  544. X            #
  545. X            v1 = (x1[i]*sin(th+dth),x1[i]*cos(th+dth),z1[i])
  546. X            n1 = (nx1[i]*sin(a2), nx1[i]*cos(a2), nz1[i])
  547. X            #
  548. X            v2 = (x2[i]*sin(th+dth),x2[i]*cos(th+dth),z2[i])
  549. X            n2 = (nx2[i]*sin(a2), nx2[i]*cos(a2), nz2[i])
  550. X            #
  551. X            v3 = (x2[i]*sin(th), x2[i]*cos(th), z2[i])
  552. X            n3 = (nx2[i]*sin(a1), nx2[i]*cos(a1), nz2[i])
  553. X            #
  554. X            patch = ((v0,n0), (v1,n1), (v2,n2), (v3,n3))
  555. X            #patch = ((n0,v0), (n1,v1), (n2,v2), (n3,v3))
  556. X            #
  557. X            if x1[i] < FUZZY :
  558. X                patch = patch[1:]
  559. X            #
  560. X            object.append (patch)
  561. X    #
  562. X    return object
  563. X
  564. Xdef makesphere (n):
  565. X    asin = []
  566. X    acos = []
  567. X    for i in range (0, n-1):
  568. X        asin.append (sin((pi/float (n))*(1.0+float (i))))
  569. X        acos.append(cos((pi/float (n))*(1.0+float (i))))
  570. X    #
  571. X    x1 = [0.0] + asin
  572. X    z1 = [1.0] + acos
  573. X    nx1 = [0.0] + asin
  574. X    nz1 = [1.0] + acos
  575. X    #
  576. X    x2 = asin + [0.0]
  577. X    z2 = acos + [-1.0]
  578. X    nx2 = asin + [0.0]
  579. X    nz2 = acos + [-1.0]
  580. X    #
  581. X    return makespinobject (1,2*n,n,x1,z1,nx1,nz1,x2,z2,nx2,nz2)
  582. X
  583. Xdef makecylinder(n) :
  584. X    x1 =  [0.0, 1.0, 1.0]
  585. X    nx1 = [0.0, 1.0, 0.0]
  586. X    z1 =  [1.0, 1.0, -1.0]
  587. X    nz1 =  [1.0, 0.0, -1.0]
  588. X    #
  589. X    z2 =  [1.0, -1.0, -1.0]
  590. X    nz2 =  [1.0, 0.0, -1.0]
  591. X    x2 =  [1.0, 1.0, 0.0]
  592. X    nx2 = [0.0, 1.0, 0.0]
  593. X    #
  594. X    return makespinobject(1,2*n,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2)
  595. X
  596. Xdef makecone(n) :
  597. X    x1 =  [0.0, 1.0, 1.0]
  598. X    nx1 = [2.0/sqrt(5.0), 0.0, 0.0]
  599. X    z1 =  [1.0, -1.0, -1.0]
  600. X    nz1 = [1.0/sqrt(5.0), -1.0, -1.0]
  601. X    #
  602. X    x2 =  [1.0, 0.0, 0.0]
  603. X    nx2 = [2.0/sqrt(5.0), 0.0, 0.0]
  604. X    nz2 = [1.0/sqrt(5.0), -1.0, -1.0]
  605. X    z2 = [-1.0, -1.0, -1.0]
  606. X    #
  607. X    return makespinobject(1,2*n,2,x1,z1,nx1,nz1,x2,z2,nx2,nz2)
  608. X
  609. Xdef makecube() :
  610. X    x1 =  [0.0, sqrt(2.0), sqrt (2.0)]
  611. X    nx1 = [0.0, 1.0, 0.0]
  612. X    z1 =  [1.0, 1.0, -1.0]
  613. X    nz1 = [1.0, 0.0, -1.0]
  614. X    #
  615. X    x2 =  [sqrt(2.0), sqrt(2.0), 0.0]
  616. X    nx2 = [0.0, 1.0, 0.0]
  617. X    z2 =  [1.0, -1.0, -1.0]
  618. X    nz2 = [1.0, 0.0, -1.0]
  619. X    #
  620. X    return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2)
  621. X
  622. X
  623. Xdef makepyramid() :
  624. X    x1 =  [0.0, sqrt(2.0), 0.0]
  625. X    nx1 = [2.0 / sqrt(5.0), 0.0, 0.0]
  626. X    z1 =  [1.0, -1.0, 0.0]
  627. X    nz1 = [1.0 / sqrt(5.0), -1.0, 0.0]
  628. X    #
  629. X    x2 =  [sqrt(2.0), 0.0, 0.0]
  630. X    nx2 = [2.0 / sqrt(5.0), 0.0, 0.0]
  631. X    z2 =  [-1.0, -1.0, -1.0]
  632. X    nz2 = [1.0/sqrt(5.0), -1.0, 0.0]
  633. X    #
  634. X    return makespinobject(0,4,3,x1,z1,nx1,nz1,x2,z2,nx2,nz2)
  635. X
  636. Xdef makeobjects () :
  637. X    cube = makecube()
  638. X    sphere = makesphere (6)
  639. X    cylinder = makecylinder (6)
  640. X    cone = makecone (6)
  641. X    pyramid = makepyramid ()
  642. X    #
  643. X    odict = {}
  644. X    odict ['cube'] = cube
  645. X    odict ['pyramid'] = pyramid
  646. X    odict ['sphere'] = sphere
  647. X    odict ['cylinder'] = cylinder
  648. X    odict ['cone'] = cone
  649. X    odict ['diamond'] = cube
  650. X    odict ['disk'] = sphere
  651. X    #
  652. X    return odict
  653. X
  654. X
  655. Xrenderfuncs = [bgnpolygon, endpolygon]
  656. X
  657. Xdef putFunc (funcs) :
  658. X    renderfuncs [:] = funcs
  659. X
  660. Xdef drawobject (obj) :
  661. X    #
  662. X    for patch in obj :
  663. X        renderfuncs[0] ()
  664. X        vnarray (patch)
  665. X        renderfuncs[1] ()
  666. X
  667. EOF
  668. fi
  669. if test -s 'lib/Split.py'
  670. then echo '*** I will not over-write existing file lib/Split.py'
  671. else
  672. echo 'x - lib/Split.py'
  673. sed 's/^X//' > 'lib/Split.py' << 'EOF'
  674. X# Generic Split implementation.
  675. X# Use as a base class for other splits.
  676. X# Derived classes should at least implement the methods that call
  677. X# unimpl() below: minsize(), getbounds() and setbounds().
  678. X
  679. XError = 'Split.Error'    # Exception
  680. X
  681. Ximport rect
  682. Xfrom util import remove
  683. X
  684. Xclass Split():
  685. X    #
  686. X    # Calls from creator
  687. X    # NB derived classes may add parameters to create()
  688. X    #
  689. X    def create(self, parent):
  690. X        parent.addchild(self)
  691. X        self.parent = parent
  692. X        self.children = []
  693. X        self.mouse_interest = []
  694. X        self.timer_interest = []
  695. X        self.mouse_focus = 0
  696. X        return self
  697. X    #
  698. X    # Downcalls from parent to child
  699. X    #
  700. X    def destroy(self):
  701. X        self.parent = None
  702. X        for child in self.children:
  703. X            child.destroy()
  704. X        del self.children[:]
  705. X        del self.mouse_interest[:]
  706. X        del self.timer_interest[:]
  707. X        self.mouse_focus = None
  708. X    #
  709. X    def minsize(self, m): return unimpl()
  710. X    def getbounds(self): return unimpl()
  711. X    def setbounds(self, bounds): unimpl()
  712. X    #
  713. X    def draw(self, d_detail):
  714. X        # (Could avoid calls to children outside the area)
  715. X        for child in self.children:
  716. X            child.draw(d_detail)
  717. X    #
  718. X    # Downcalls only made after certain upcalls
  719. X    #
  720. X    def mouse_down(self, detail):
  721. X        if self.mouse_focus:
  722. X            self.mouse_focus.mouse_down(detail)
  723. X        p = detail[0]
  724. X        for child in self.mouse_interest:
  725. X            if rect.pointinrect(p, child.getbounds()):
  726. X                self.mouse_focus = child
  727. X                child.mouse_down(detail)
  728. X    def mouse_move(self, detail):
  729. X        if self.mouse_focus:
  730. X            self.mouse_focus.mouse_move(detail)
  731. X    def mouse_up(self, detail):
  732. X        if self.mouse_focus:
  733. X            self.mouse_focus.mouse_up(detail)
  734. X            self.mouse_focus = 0
  735. X    #
  736. X    def timer(self):
  737. X        for child in self.timer_interest:
  738. X            child.timer()
  739. X    #
  740. X    # Upcalls from child to parent
  741. X    #
  742. X    def addchild(self, child):
  743. X        if child in self.children:
  744. X            raise Error, 'addchild: child already inlist'
  745. X        self.children.append(child)
  746. X    def delchild(self, child):
  747. X        if child not in self.children:
  748. X            raise Error, 'delchild: child not in list'
  749. X        remove(child, self.children)
  750. X        if child in self.mouse_interest:
  751. X            remove(child, self.mouse_interest)
  752. X        if child in self.timer_interest:
  753. X            remove(child, self.timer_interest)
  754. X        if child = self.mouse_focus:
  755. X            self.mouse_focus = 0
  756. X    #
  757. X    def need_mouse(self, child):
  758. X        if child not in self.mouse_interest:
  759. X            self.mouse_interest.append(child)
  760. X            self.parent.need_mouse(self)
  761. X    def no_mouse(self, child):
  762. X        if child in self.mouse_interest:
  763. X            remove(child, self.mouse_interest)
  764. X            if not self.mouse_interest:
  765. X                self.parent.no_mouse(self)
  766. X    #
  767. X    def need_timer(self, child):
  768. X        if child not in self.timer_interest:
  769. X            self.timer_interest.append(child)
  770. X            self.parent.need_timer(self)
  771. X    def no_timer(self, child):
  772. X        if child in self.timer_interest:
  773. X            remove(child, self.timer_interest)
  774. X            if not self.timer_interest:
  775. X                self.parent.no_timer(self)
  776. X    #
  777. X    # The rest are transparent:
  778. X    #
  779. X    def begindrawing(self):
  780. X        return self.parent.begindrawing()
  781. X    def beginmeasuring(self):
  782. X        return self.parent.beginmeasuring()
  783. X    #
  784. X    def change(self, area):
  785. X        self.parent.change(area)
  786. X    def scroll(self, area_vector):
  787. X        self.parent.scroll(area_vector)
  788. X    def settimer(self, itimer):
  789. X        self.parent.settimer(itimer)
  790. EOF
  791. fi
  792. if test -s 'lib/WindowParent.py'
  793. then echo '*** I will not over-write existing file lib/WindowParent.py'
  794. else
  795. echo 'x - lib/WindowParent.py'
  796. sed 's/^X//' > 'lib/WindowParent.py' << 'EOF'
  797. X# A 'WindowParent' is the only module that uses real stdwin functionality.
  798. X# It is the root of the tree.
  799. X# It should have exactly one child when realized.
  800. X
  801. Ximport stdwin
  802. Xfrom stdwinevents import *
  803. X
  804. Xfrom TransParent import ManageOneChild
  805. X
  806. XError = 'WindowParent.Error'    # Exception
  807. X
  808. Xclass WindowParent() = ManageOneChild():
  809. X    #
  810. X    def create(self, (title, size)):
  811. X        self.title = title
  812. X        self.size = size        # (width, height)
  813. X        self._reset()
  814. X        return self
  815. X    #
  816. X    def _reset(self):
  817. X        self.child = 0
  818. X        self.win = 0
  819. X        self.itimer = 0
  820. X        self.do_mouse = 0
  821. X        self.do_timer = 0
  822. X    #
  823. X    def destroy(self):
  824. X        if self.child: self.child.destroy()
  825. X        self._reset()
  826. X    #
  827. X    def need_mouse(self, child): self.do_mouse = 1
  828. X    def no_mouse(self, child): self.do_mouse = 0
  829. X    #
  830. X    def need_timer(self, child): self.do_timer = 1
  831. X    def no_timer(self, child): self.do_timer = 0
  832. X    #
  833. X    def realize(self):
  834. X        if self.win:
  835. X            raise Error, 'realize(): called twice'
  836. X        if not self.child:
  837. X            raise Error, 'realize(): no child'
  838. X        size = self.child.minsize(self.beginmeasuring())
  839. X        self.size = max(self.size[0], size[0]), \
  840. X                        max(self.size[1], size[1])
  841. X        #stdwin.setdefwinsize(self.size)
  842. X        # XXX Compensate stdwin bug:
  843. X        stdwin.setdefwinsize(self.size[0]+4, self.size[1]+2)
  844. X        self.win = stdwin.open(self.title)
  845. X        if self.itimer:
  846. X            self.win.settimer(self.itimer)
  847. X        bounds = (0, 0), self.win.getwinsize()
  848. X        self.child.setbounds(bounds)
  849. X    #
  850. X    def beginmeasuring(self):
  851. X        # Return something with which a child can measure text
  852. X        if self.win:
  853. X            return self.win.begindrawing()
  854. X        else:
  855. X            return stdwin
  856. X    #
  857. X    def begindrawing(self):
  858. X        if self.win:
  859. X            return self.win.begindrawing()
  860. X        else:
  861. X            raise Error, 'begindrawing(): not realized yet'
  862. X    #
  863. X    def change(self, area):
  864. X        if self.win:
  865. X            self.win.change(area)
  866. X    #
  867. X    def scroll(self, args):
  868. X        if self.win:
  869. X            self.win.scroll(args)
  870. X    #
  871. X    def settimer(self, itimer):
  872. X        if self.win:
  873. X            self.win.settimer(itimer)
  874. X        else:
  875. X            self.itimer = itimer
  876. X    #
  877. X    # Only call dispatch if we have a child
  878. X    #
  879. X    def dispatch(self, (type, win, detail)):
  880. X        if win <> self.win:
  881. X            return
  882. X        elif type = WE_DRAW:
  883. X            d = self.win.begindrawing()
  884. X            self.child.draw(d, detail)
  885. X        elif type = WE_MOUSE_DOWN:
  886. X            if self.do_mouse: self.child.mouse_down(detail)
  887. X        elif type = WE_MOUSE_MOVE:
  888. X            if self.do_mouse: self.child.mouse_move(detail)
  889. X        elif type = WE_MOUSE_UP:
  890. X            if self.do_mouse: self.child.mouse_up(detail)
  891. X        elif type = WE_TIMER:
  892. X            if self.do_timer: self.child.timer()
  893. X        elif type = WE_SIZE:
  894. X            self.win.change((0, 0), (10000, 10000)) # XXX
  895. X            bounds = (0, 0), self.win.getwinsize()
  896. X            self.child.setbounds(bounds)
  897. X    #
  898. EOF
  899. fi
  900. if test -s 'lib/gwin.py'
  901. then echo '*** I will not over-write existing file lib/gwin.py'
  902. else
  903. echo 'x - lib/gwin.py'
  904. sed 's/^X//' > 'lib/gwin.py' << 'EOF'
  905. X# Module 'gwin'
  906. X# Generic stdwin windows
  907. X
  908. X# This is used as a base class from which to derive other window types.
  909. X# The mainloop() function here is an event dispatcher for all window types.
  910. X
  911. Ximport stdwin
  912. Xfrom stdwinevents import *
  913. X
  914. X# XXX Old version of stdwinevents, should go
  915. Ximport stdwinsupport
  916. XS = stdwinsupport            # Shorthand
  917. X
  918. Xwindows = []                # List of open windows
  919. X
  920. X
  921. X# Open a window
  922. X
  923. Xdef open(title):            # Open a generic window
  924. X    w = stdwin.open(title)
  925. X    stdwin.setdefwinsize(0, 0)
  926. X    # Set default event handlers
  927. X    w.draw = nop
  928. X    w.char = nop
  929. X    w.mdown = nop
  930. X    w.mmove = nop
  931. X    w.mup = nop
  932. X    w.m2down = m2down
  933. X    w.m2up = m2up
  934. X    w.size = nop
  935. X    w.move = nop
  936. X    w.activate = w.deactivate = nop
  937. X    w.timer = nop
  938. X    # default command handlers
  939. X    w.close = close
  940. X    w.tab = tab
  941. X    w.enter = enter
  942. X    w.backspace = backspace
  943. X    w.arrow = arrow
  944. X    w.kleft = w.kup = w.kright = w.kdown = nop
  945. X    windows.append(w)
  946. X    return w
  947. X
  948. X
  949. X# Generic event dispatching
  950. X
  951. Xdef mainloop():                # Handle events until no windows left
  952. X    while windows:
  953. X        treatevent(stdwin.getevent())
  954. X
  955. Xdef treatevent(e):            # Handle a stdwin event
  956. X    type, w, detail = e
  957. X    if type = S.we_draw:
  958. X        w.draw(w, detail)
  959. X    elif type = S.we_menu:
  960. X        m, item = detail
  961. X        m.action[item](w, m, item)
  962. X    elif type = S.we_command:
  963. X        treatcommand(w, detail)
  964. X    elif type = S.we_char:
  965. X        w.char(w, detail)
  966. X    elif type = S.we_mouse_down:
  967. X        if detail[1] > 1: w.m2down(w, detail)
  968. X        else: w.mdown(w, detail)
  969. X    elif type = S.we_mouse_move:
  970. X        w.mmove(w, detail)
  971. X    elif type = S.we_mouse_up:
  972. X        if detail[1] > 1: w.m2up(w, detail)
  973. X        else: w.mup(w, detail)
  974. X    elif type = S.we_size:
  975. X        w.size(w, w.getwinsize())
  976. X    elif type = S.we_activate:
  977. X        w.activate(w)
  978. X    elif type = S.we_deactivate:
  979. X        w.deactivate(w)
  980. X    elif type = S.we_move:
  981. X        w.move(w)
  982. X    elif type = S.we_timer:
  983. X        w.timer(w)
  984. X    elif type = WE_CLOSE:
  985. X        w.close(w)
  986. X
  987. Xdef treatcommand(w, type):        # Handle a we_command event
  988. X    if type = S.wc_close:
  989. X        w.close(w)
  990. X    elif type = S.wc_return:
  991. X        w.enter(w)
  992. X    elif type = S.wc_tab:
  993. X        w.tab(w)
  994. X    elif type = S.wc_backspace:
  995. X        w.backspace(w)
  996. X    elif type in (S.wc_left, S.wc_up, S.wc_right, S.wc_down):
  997. X        w.arrow(w, type)
  998. X
  999. X
  1000. X# Methods
  1001. X
  1002. Xdef close(w):                # Close method
  1003. X    for i in range(len(windows)):
  1004. X        if windows[i] is w:
  1005. X            del windows[i]
  1006. X            break
  1007. X
  1008. Xdef arrow(w, detail):            # Arrow key method
  1009. X    if detail = S.wc_left:
  1010. X        w.kleft(w)
  1011. X    elif detail = S.wc_up:
  1012. X        w.kup(w)
  1013. X    elif detail = S.wc_right:
  1014. X        w.kright(w)
  1015. X    elif detail = S.wc_down:
  1016. X        w.kdown(w)
  1017. X
  1018. X
  1019. X# Trivial methods
  1020. X
  1021. Xdef tab(w): w.char(w, '\t')
  1022. Xdef enter(w): w.char(w, '\n')        # 'return' is a Python reserved word
  1023. Xdef backspace(w): w.char(w, '\b')
  1024. Xdef m2down(w, detail): w.mdown(w, detail)
  1025. Xdef m2up(w, detail): w.mup(w, detail)
  1026. Xdef nop(args): pass
  1027. EOF
  1028. fi
  1029. if test -s 'lib/panelparser.py'
  1030. then echo '*** I will not over-write existing file lib/panelparser.py'
  1031. else
  1032. echo 'x - lib/panelparser.py'
  1033. sed 's/^X//' > 'lib/panelparser.py' << 'EOF'
  1034. X# Module 'parser'
  1035. X#
  1036. X# Parse S-expressions output by the Panel Editor
  1037. X# (which is written in Scheme so it can't help writing S-expressions).
  1038. X#
  1039. X# See notes at end of file.
  1040. X
  1041. X
  1042. Xwhitespace = ' \t\n'
  1043. Xoperators = '()\''
  1044. Xseparators = operators + whitespace + ';' + '"'
  1045. X
  1046. X
  1047. X# Tokenize a string.
  1048. X# Return a list of tokens (strings).
  1049. X#
  1050. Xdef tokenize_string(s):
  1051. X    tokens = []
  1052. X    while s:
  1053. X        c = s[:1]
  1054. X        if c in whitespace:
  1055. X            s = s[1:]
  1056. X        elif c = ';':
  1057. X            s = ''
  1058. X        elif c = '"':
  1059. X            n = len(s)
  1060. X            i = 1
  1061. X            while i < n:
  1062. X                c = s[i]
  1063. X                i = i+1
  1064. X                if c = '"': break
  1065. X                if c = '\\': i = i+1
  1066. X            tokens.append(s[:i])
  1067. X            s = s[i:]
  1068. X        elif c in operators:
  1069. X            tokens.append(c)
  1070. X            s = s[1:]
  1071. X        else:
  1072. X            n = len(s)
  1073. X            i = 1
  1074. X            while i < n:
  1075. X                if s[i] in separators: break
  1076. X                i = i+1
  1077. X            tokens.append(s[:i])
  1078. X            s = s[i:]
  1079. X    return tokens
  1080. X
  1081. X
  1082. X# Tokenize a whole file (given as file object, not as file name).
  1083. X# Return a list of tokens (strings).
  1084. X#
  1085. Xdef tokenize_file(fp):
  1086. X    tokens = []
  1087. X    while 1:
  1088. X        line = fp.readline()
  1089. X        if not line: break
  1090. X        tokens = tokens + tokenize_string(line)
  1091. X    return tokens
  1092. X
  1093. X
  1094. X# Exception raised by parse_exr.
  1095. X#
  1096. Xsyntax_error = 'syntax error'
  1097. X
  1098. X
  1099. X# Parse an S-expression.
  1100. X# Input is a list of tokens as returned by tokenize_*().
  1101. X# Return a pair (expr, tokens)
  1102. X# where expr is a list representing the s-expression,
  1103. X# and tokens contains the remaining tokens.
  1104. X# May raise syntax_error.
  1105. X#
  1106. Xdef parse_expr(tokens):
  1107. X    if (not tokens) or tokens[0] <> '(':
  1108. X        raise syntax_error, 'expected "("'
  1109. X    tokens = tokens[1:]
  1110. X    expr = []
  1111. X    while 1:
  1112. X        if not tokens:
  1113. X            raise syntax_error, 'missing ")"'
  1114. X        if tokens[0] = ')':
  1115. X            return expr, tokens[1:]
  1116. X        elif tokens[0] = '(':
  1117. X            subexpr, tokens = parse_expr(tokens)
  1118. X            expr.append(subexpr)
  1119. X        else:
  1120. X            expr.append(tokens[0])
  1121. X            tokens = tokens[1:]
  1122. X
  1123. X
  1124. X# Parse a file (given as file object, not as file name).
  1125. X# Return a list of parsed S-expressions found at the top level.
  1126. X#
  1127. Xdef parse_file(fp):
  1128. X    tokens = tokenize_file(fp)
  1129. X    exprlist = []
  1130. X    while tokens:
  1131. X        expr, tokens = parse_expr(tokens)
  1132. X        exprlist.append(expr)
  1133. X    return exprlist
  1134. X
  1135. X
  1136. X# EXAMPLE:
  1137. X#
  1138. X# The input
  1139. X#    '(hip (hop hur-ray))'
  1140. X#
  1141. X# passed to tokenize_string() returns the token list
  1142. X#    ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')']
  1143. X#
  1144. X# When this is passed to parse_expr() it returns the expression
  1145. X#    ['hip', ['hop', 'hur-ray']]
  1146. X# plus an empty token list (because there are no tokens left.
  1147. X#
  1148. X# When a file containing the example is passed to parse_file() it returns
  1149. X# a list whose only element is the output of parse_expr() above:
  1150. X#    [['hip', ['hop', 'hur-ray']]]
  1151. X
  1152. X
  1153. X# TOKENIZING:
  1154. X#
  1155. X# Comments start with semicolon (;) and continue till the end of the line.
  1156. X#
  1157. X# Tokens are separated by whitespace, except the following characters
  1158. X# always form a separate token (outside strings):
  1159. X#    ( ) '
  1160. X# Strings are enclosed in double quotes (") and backslash (\) is used
  1161. X# as escape character in strings.
  1162. EOF
  1163. fi
  1164. if test -s 'lib/path.py'
  1165. then echo '*** I will not over-write existing file lib/path.py'
  1166. else
  1167. echo 'x - lib/path.py'
  1168. sed 's/^X//' > 'lib/path.py' << 'EOF'
  1169. X# Module 'path' -- common operations on POSIX pathnames
  1170. X
  1171. Ximport posix
  1172. Ximport stat
  1173. X
  1174. X
  1175. X# Intelligent pathname concatenation.
  1176. X# Inserts a '/' unless the first part is empty or already ends in '/'.
  1177. X# Ignores the first part altogether if the second part is absolute
  1178. X# (begins with '/').
  1179. X#
  1180. Xdef cat(a, b):
  1181. X    if b[:1] = '/': return b
  1182. X    if a = '' or a[-1:] = '/': return a + b
  1183. X    return a + '/' + b
  1184. X
  1185. X
  1186. X# Split a path in head (empty or ending in '/') and tail (no '/').
  1187. X# The tail will be empty if the path ends in '/'.
  1188. X#
  1189. Xdef split(p):
  1190. X    head, tail = '', ''
  1191. X    for c in p:
  1192. X        tail = tail + c
  1193. X        if c = '/':
  1194. X            head, tail = head + tail, ''
  1195. X    return head, tail
  1196. X
  1197. X
  1198. X# Return the tail (basename) part of a path.
  1199. X#
  1200. Xdef basename(p):
  1201. X    return split(p)[1]
  1202. X
  1203. X
  1204. X# Return the longest prefix of all list elements.
  1205. X#
  1206. Xdef commonprefix(m):
  1207. X    if not m: return ''
  1208. X    prefix = m[0]
  1209. X    for item in m:
  1210. X        for i in range(len(prefix)):
  1211. X            if prefix[:i+1] <> item[:i+1]:
  1212. X                prefix = prefix[:i]
  1213. X                if i = 0: return ''
  1214. X                break
  1215. X    return prefix
  1216. X
  1217. X
  1218. X# Does a file/directory exist?
  1219. X#
  1220. Xdef exists(path):
  1221. X    try:
  1222. X        st = posix.stat(path)
  1223. X    except posix.error:
  1224. X        return 0
  1225. X    return 1
  1226. X
  1227. X
  1228. X# Is a path a posix directory?
  1229. X#
  1230. Xdef isdir(path):
  1231. X    try:
  1232. X        st = posix.stat(path)
  1233. X    except posix.error:
  1234. X        return 0
  1235. X    return stat.S_ISDIR(st[stat.ST_MODE])
  1236. X
  1237. X
  1238. X# Is a path a symbolic link?
  1239. X# This will always return false on systems where posix.lstat doesn't exist.
  1240. X#
  1241. Xdef islink(path):
  1242. X    try:
  1243. X        st = posix.lstat(path)
  1244. X    except (posix.error, NameError):
  1245. X        return 0
  1246. X    return stat.S_ISLNK(st[stat.ST_MODE])
  1247. X
  1248. X
  1249. X_mounts = []
  1250. X
  1251. Xdef _getmounts():
  1252. X    import commands, string
  1253. X    mounts = []
  1254. X    data = commands.getoutput('/etc/mount')
  1255. X    lines = string.splitfields(data, '\n')
  1256. X    for line in lines:
  1257. X        words = string.split(line)
  1258. X        if len(words) >= 3 and words[1] = 'on':
  1259. X            mounts.append(words[2])
  1260. X    return mounts
  1261. X
  1262. X
  1263. X# Is a path a mount point?
  1264. X# This only works for normalized, absolute paths,
  1265. X# and only if the mount table as printed by /etc/mount is correct.
  1266. X# Sorry.
  1267. X#
  1268. Xdef ismount(path):
  1269. X    if not _mounts:
  1270. X        _mounts[:] = _getmounts()
  1271. X    return path in _mounts
  1272. X
  1273. X
  1274. X# Directory tree walk.
  1275. X# For each directory under top (including top itself),
  1276. X# func(arg, dirname, filenames) is called, where dirname
  1277. X# is the name of the directory and filenames is the list of
  1278. X# files (and subdirectories etc.) in the directory.
  1279. X# func may modify the filenames list, to implement a filter,
  1280. X# or to impose a different order of visiting.
  1281. X#
  1282. Xdef walk(top, func, arg):
  1283. X    try:
  1284. X        names = posix.listdir(top)
  1285. X    except posix.error:
  1286. X        return
  1287. X    func(arg, top, names)
  1288. X    exceptions = ('.', '..')
  1289. X    for name in names:
  1290. X        if name not in exceptions:
  1291. X            name = cat(top, name)
  1292. X            if isdir(name):
  1293. X                walk(name, func, arg)
  1294. EOF
  1295. fi
  1296. if test -s 'lib/string.py'
  1297. then echo '*** I will not over-write existing file lib/string.py'
  1298. else
  1299. echo 'x - lib/string.py'
  1300. sed 's/^X//' > 'lib/string.py' << 'EOF'
  1301. X# module 'string' -- A collection of string operations
  1302. X
  1303. X# XXX Some of these operations are incredibly slow and should be built in
  1304. X
  1305. X# Some strings for ctype-style character classification
  1306. Xwhitespace = ' \t\n'
  1307. Xlowercase = 'abcdefghijklmnopqrstuvwxyz'
  1308. Xuppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  1309. Xletters = lowercase + uppercase
  1310. Xdigits = '0123456789'
  1311. Xhexdigits = digits + 'abcdef' + 'ABCDEF'
  1312. Xoctdigits = '01234567'
  1313. X
  1314. X# Case conversion helpers
  1315. X_caseswap = {}
  1316. Xfor i in range(26):
  1317. X    _caseswap[lowercase[i]] = uppercase[i]
  1318. X    _caseswap[uppercase[i]] = lowercase[i]
  1319. Xdel i
  1320. X
  1321. X# convert UPPER CASE letters to lower case
  1322. Xdef lower(s):
  1323. X    res = ''
  1324. X    for c in s:
  1325. X        if 'A' <= c <= 'Z': c = _caseswap[c]
  1326. X        res = res + c
  1327. X    return res
  1328. X
  1329. X# Convert lower case letters to UPPER CASE
  1330. Xdef upper(s):
  1331. X    res = ''
  1332. X    for c in s:
  1333. X        if 'a' <= c <= 'z': c = _caseswap[c]
  1334. X        res = res + c
  1335. X    return res
  1336. X
  1337. X# Swap lower case letters and UPPER CASE
  1338. Xdef swapcase(s):
  1339. X    res = ''
  1340. X    for c in s:
  1341. X        if 'a' <= c <= 'z' or 'A' <= c <= 'Z': c = _caseswap[c]
  1342. X        res = res + c
  1343. X    return res
  1344. X
  1345. X# Strip leading and trailing tabs and spaces
  1346. Xdef strip(s):
  1347. X    i, j = 0, len(s)
  1348. X    while i < j and s[i] in whitespace: i = i+1
  1349. X    while i < j and s[j-1] in whitespace: j = j-1
  1350. X    return s[i:j]
  1351. X
  1352. X# Split a string into a list of space/tab-separated words
  1353. X# NB: split(s) is NOT the same as splitfields(s, ' ')!
  1354. Xdef split(s):
  1355. X    res = []
  1356. X    i, n = 0, len(s)
  1357. X    while i < n:
  1358. X        while i < n and s[i] in whitespace: i = i+1
  1359. X        if i = n: break
  1360. X        j = i
  1361. X        while j < n and s[j] not in whitespace: j = j+1
  1362. X        res.append(s[i:j])
  1363. X        i = j
  1364. X    return res
  1365. X
  1366. X# Split a list into fields separated by a given string
  1367. X# NB: splitfields(s, ' ') is NOT the same as split(s)!
  1368. Xdef splitfields(s, sep):
  1369. X    res = []
  1370. X    ns = len(s)
  1371. X    nsep = len(sep)
  1372. X    i = j = 0
  1373. X    while j+nsep <= ns:
  1374. X        if s[j:j+nsep] = sep:
  1375. X            res.append(s[i:j])
  1376. X            i = j = j + nsep
  1377. X        else:
  1378. X            j = j + 1
  1379. X    res.append(s[i:])
  1380. X    return res
  1381. X
  1382. X# Find substring
  1383. Xindex_error = 'substring not found in string.index'
  1384. Xdef index(s, sub):
  1385. X    n = len(sub)
  1386. X    for i in range(len(s) + 1 - n):
  1387. X        if sub = s[i:i+n]: return i
  1388. X    raise index_error, (s, sub)
  1389. X
  1390. X# Convert string to integer
  1391. Xatoi_error = 'non-numeric argument to string.atoi'
  1392. Xdef atoi(str):
  1393. X    s = str
  1394. X    if s[:1] in '+-': s = s[1:]
  1395. X    if not s: raise atoi_error, str
  1396. X    for c in s:
  1397. X        if c not in digits: raise atoi_error, str
  1398. X    return eval(str)
  1399. X
  1400. X# Left-justify a string
  1401. Xdef ljust(s, width):
  1402. X    n = len(s)
  1403. X    if n >= width: return s
  1404. X    return s + ' '*(width-n)
  1405. X
  1406. X# Right-justify a string
  1407. Xdef rjust(s, width):
  1408. X    n = len(s)
  1409. X    if n >= width: return s
  1410. X    return ' '*(width-n) + s
  1411. X
  1412. X# Center a string
  1413. Xdef center(s, width):
  1414. X    n = len(s)
  1415. X    if n >= width: return s
  1416. X    return ' '*((width-n)/2) +  s + ' '*(width -(width-n)/2)
  1417. X
  1418. X# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
  1419. X# Decadent feature: the argument may be a string or a number
  1420. X# (Use of this is deprecated; it should be a string as with ljust c.s.)
  1421. Xdef zfill(x, width):
  1422. X    if type(x) = type(''): s = x
  1423. X    else: s = `x`
  1424. X    n = len(s)
  1425. X    if n >= width: return s
  1426. X    sign = ''
  1427. X    if s[0] = '-':
  1428. X        sign, s = '-', s[1:]
  1429. X    return sign + '0'*(width-n) + s
  1430. EOF
  1431. fi
  1432. if test -s 'src/Grammar'
  1433. then echo '*** I will not over-write existing file src/Grammar'
  1434. else
  1435. echo 'x - src/Grammar'
  1436. sed 's/^X//' > 'src/Grammar' << 'EOF'
  1437. X# Grammar for Python, version 4
  1438. X
  1439. X# Changes compared to version 3:
  1440. X#    Removed 'dir' statement.
  1441. X#    Function call argument is a testlist instead of exprlist.
  1442. X
  1443. X# Changes compared to version 2:
  1444. X#    The syntax of Boolean operations is changed to use more
  1445. X#    conventional priorities: or < and < not.
  1446. X
  1447. X# Changes compared to version 1:
  1448. X#    modules and scripts are unified;
  1449. X#    'quit' is gone (use ^D);
  1450. X#    empty_stmt is gone, replaced by explicit NEWLINE where appropriate;
  1451. X#    'import' and 'def' aren't special any more;
  1452. X#    added 'from' NAME option on import clause, and '*' to import all;
  1453. X#    added class definition.
  1454. X
  1455. X# Start symbols for the grammar:
  1456. X#    single_input is a single interactive statement;
  1457. X#    file_input is a module or sequence of commands read from an input file;
  1458. X#    expr_input is the input for the input() function;
  1459. X#    eval_input is the input for the eval() function.
  1460. X
  1461. X# NB: compound_stmt in single_input is followed by extra NEWLINE!
  1462. Xsingle_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
  1463. Xfile_input: (NEWLINE | stmt)* ENDMARKER
  1464. Xexpr_input: testlist NEWLINE
  1465. Xeval_input: testlist ENDMARKER
  1466. X
  1467. Xfuncdef: 'def' NAME parameters ':' suite
  1468. Xparameters: '(' [fplist] ')'
  1469. Xfplist: fpdef (',' fpdef)*
  1470. Xfpdef: NAME | '(' fplist ')'
  1471. X
  1472. Xstmt: simple_stmt | compound_stmt
  1473. Xsimple_stmt: expr_stmt | print_stmt  | pass_stmt | del_stmt | flow_stmt | import_stmt
  1474. Xexpr_stmt: (exprlist '=')* exprlist NEWLINE
  1475. X# For assignments, additional restrictions enforced by the interpreter
  1476. Xprint_stmt: 'print' (test ',')* [test] NEWLINE
  1477. Xdel_stmt: 'del' exprlist NEWLINE
  1478. Xpass_stmt: 'pass' NEWLINE
  1479. Xflow_stmt: break_stmt | return_stmt | raise_stmt
  1480. Xbreak_stmt: 'break' NEWLINE
  1481. Xreturn_stmt: 'return' [testlist] NEWLINE
  1482. Xraise_stmt: 'raise' expr [',' expr] NEWLINE
  1483. Ximport_stmt: 'import' NAME (',' NAME)* NEWLINE | 'from' NAME 'import' ('*' | NAME (',' NAME)*) NEWLINE
  1484. Xcompound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
  1485. Xif_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  1486. Xwhile_stmt: 'while' test ':' suite ['else' ':' suite]
  1487. Xfor_stmt: 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
  1488. Xtry_stmt: 'try' ':' suite (except_clause ':' suite)* ['finally' ':' suite]
  1489. Xexcept_clause: 'except' [expr [',' expr]]
  1490. Xsuite: simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
  1491. X
  1492. Xtest: and_test ('or' and_test)*
  1493. Xand_test: not_test ('and' not_test)*
  1494. Xnot_test: 'not' not_test | comparison
  1495. Xcomparison: expr (comp_op expr)*
  1496. Xcomp_op: '<'|'>'|'='|'>' '='|'<' '='|'<' '>'|'in'|'not' 'in'|'is'|'is' 'not'
  1497. Xexpr: term (('+'|'-') term)*
  1498. Xterm: factor (('*'|'/'|'%') factor)*
  1499. Xfactor: ('+'|'-') factor | atom trailer*
  1500. Xatom: '(' [testlist] ')' | '[' [testlist] ']' | '{' '}' | '`' testlist '`' | NAME | NUMBER | STRING
  1501. Xtrailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
  1502. Xsubscript: expr | [expr] ':' [expr]
  1503. Xexprlist: expr (',' expr)* [',']
  1504. Xtestlist: test (',' test)* [',']
  1505. X
  1506. Xclassdef: 'class' NAME parameters ['=' baselist] ':' suite
  1507. Xbaselist: atom arguments (',' atom arguments)*
  1508. Xarguments: '(' [testlist] ')'
  1509. EOF
  1510. fi
  1511. if test -s 'src/firstsets.c'
  1512. then echo '*** I will not over-write existing file src/firstsets.c'
  1513. else
  1514. echo 'x - src/firstsets.c'
  1515. sed 's/^X//' > 'src/firstsets.c' << 'EOF'
  1516. X/***********************************************************
  1517. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  1518. XNetherlands.
  1519. X
  1520. X                        All Rights Reserved
  1521. X
  1522. XPermission to use, copy, modify, and distribute this software and its 
  1523. Xdocumentation for any purpose and without fee is hereby granted, 
  1524. Xprovided that the above copyright notice appear in all copies and that
  1525. Xboth that copyright notice and this permission notice appear in 
  1526. Xsupporting documentation, and that the names of Stichting Mathematisch
  1527. XCentrum or CWI not be used in advertising or publicity pertaining to
  1528. Xdistribution of the software without specific, written prior permission.
  1529. X
  1530. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  1531. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1532. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  1533. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  1534. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  1535. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  1536. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  1537. X
  1538. X******************************************************************/
  1539. X
  1540. X/* Computation of FIRST stets */
  1541. X
  1542. X#include "pgenheaders.h"
  1543. X#include "grammar.h"
  1544. X#include "token.h"
  1545. X
  1546. Xextern int debugging;
  1547. X
  1548. X/* Forward */
  1549. Xstatic void calcfirstset PROTO((grammar *, dfa *));
  1550. X
  1551. Xvoid
  1552. Xaddfirstsets(g)
  1553. X    grammar *g;
  1554. X{
  1555. X    int i;
  1556. X    dfa *d;
  1557. X    
  1558. X    printf("Adding FIRST sets ...\n");
  1559. X    for (i = 0; i < g->g_ndfas; i++) {
  1560. X        d = &g->g_dfa[i];
  1561. X        if (d->d_first == NULL)
  1562. X            calcfirstset(g, d);
  1563. X    }
  1564. X}
  1565. X
  1566. Xstatic void
  1567. Xcalcfirstset(g, d)
  1568. X    grammar *g;
  1569. X    dfa *d;
  1570. X{
  1571. X    int i, j;
  1572. X    state *s;
  1573. X    arc *a;
  1574. X    int nsyms;
  1575. X    int *sym;
  1576. X    int nbits;
  1577. X    static bitset dummy;
  1578. X    bitset result;
  1579. X    int type;
  1580. X    dfa *d1;
  1581. X    label *l0;
  1582. X    
  1583. X    if (debugging)
  1584. X        printf("Calculate FIRST set for '%s'\n", d->d_name);
  1585. X    
  1586. X    if (dummy == NULL)
  1587. X        dummy = newbitset(1);
  1588. X    if (d->d_first == dummy) {
  1589. X        fprintf(stderr, "Left-recursion for '%s'\n", d->d_name);
  1590. X        return;
  1591. X    }
  1592. X    if (d->d_first != NULL) {
  1593. X        fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n",
  1594. X            d->d_name);
  1595. X    }
  1596. X    d->d_first = dummy;
  1597. X    
  1598. X    l0 = g->g_ll.ll_label;
  1599. X    nbits = g->g_ll.ll_nlabels;
  1600. X    result = newbitset(nbits);
  1601. X    
  1602. X    sym = NEW(int, 1);
  1603. X    if (sym == NULL)
  1604. X        fatal("no mem for new sym in calcfirstset");
  1605. X    nsyms = 1;
  1606. X    sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL);
  1607. X    
  1608. X    s = &d->d_state[d->d_initial];
  1609. X    for (i = 0; i < s->s_narcs; i++) {
  1610. X        a = &s->s_arc[i];
  1611. X        for (j = 0; j < nsyms; j++) {
  1612. X            if (sym[j] == a->a_lbl)
  1613. X                break;
  1614. X        }
  1615. X        if (j >= nsyms) { /* New label */
  1616. X            RESIZE(sym, int, nsyms + 1);
  1617. X            if (sym == NULL)
  1618. X                fatal("no mem to resize sym in calcfirstset");
  1619. X            sym[nsyms++] = a->a_lbl;
  1620. X            type = l0[a->a_lbl].lb_type;
  1621. X            if (ISNONTERMINAL(type)) {
  1622. X                d1 = finddfa(g, type);
  1623. X                if (d1->d_first == dummy) {
  1624. X                    fprintf(stderr,
  1625. X                        "Left-recursion below '%s'\n",
  1626. X                        d->d_name);
  1627. X                }
  1628. X                else {
  1629. X                    if (d1->d_first == NULL)
  1630. X                        calcfirstset(g, d1);
  1631. X                    mergebitset(result, d1->d_first, nbits);
  1632. X                }
  1633. X            }
  1634. X            else if (ISTERMINAL(type)) {
  1635. X                addbit(result, a->a_lbl);
  1636. X            }
  1637. X        }
  1638. X    }
  1639. X    d->d_first = result;
  1640. X    if (debugging) {
  1641. X        printf("FIRST set for '%s': {", d->d_name);
  1642. X        for (i = 0; i < nbits; i++) {
  1643. X            if (testbit(result, i))
  1644. X                printf(" %s", labelrepr(&l0[i]));
  1645. X        }
  1646. X        printf(" }\n");
  1647. X    }
  1648. X}
  1649. EOF
  1650. fi
  1651. if test -s 'src/frameobject.h'
  1652. then echo '*** I will not over-write existing file src/frameobject.h'
  1653. else
  1654. echo 'x - src/frameobject.h'
  1655. sed 's/^X//' > 'src/frameobject.h' << 'EOF'
  1656. X/***********************************************************
  1657. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  1658. XNetherlands.
  1659. X
  1660. X                        All Rights Reserved
  1661. X
  1662. XPermission to use, copy, modify, and distribute this software and its 
  1663. Xdocumentation for any purpose and without fee is hereby granted, 
  1664. Xprovided that the above copyright notice appear in all copies and that
  1665. Xboth that copyright notice and this permission notice appear in 
  1666. Xsupporting documentation, and that the names of Stichting Mathematisch
  1667. XCentrum or CWI not be used in advertising or publicity pertaining to
  1668. Xdistribution of the software without specific, written prior permission.
  1669. X
  1670. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  1671. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1672. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  1673. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  1674. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  1675. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  1676. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  1677. X
  1678. X******************************************************************/
  1679. X
  1680. X/* Frame object interface */
  1681. X
  1682. Xtypedef struct {
  1683. X    int b_type;        /* what kind of block this is */
  1684. X    int b_handler;        /* where to jump to find handler */
  1685. X    int b_level;        /* value stack level to pop to */
  1686. X} block;
  1687. X
  1688. Xtypedef struct _frame {
  1689. X    OB_HEAD
  1690. X    struct _frame *f_back;    /* previous frame, or NULL */
  1691. X    codeobject *f_code;    /* code segment */
  1692. X    object *f_globals;    /* global symbol table (dictobject) */
  1693. X    object *f_locals;    /* local symbol table (dictobject) */
  1694. X    object **f_valuestack;    /* malloc'ed array */
  1695. X    block *f_blockstack;    /* malloc'ed array */
  1696. X    int f_nvalues;        /* size of f_valuestack */
  1697. X    int f_nblocks;        /* size of f_blockstack */
  1698. X    int f_iblock;        /* index in f_blockstack */
  1699. X} frameobject;
  1700. X
  1701. X
  1702. X/* Standard object interface */
  1703. X
  1704. Xextern typeobject Frametype;
  1705. X
  1706. X#define is_frameobject(op) ((op)->ob_type == &Frametype)
  1707. X
  1708. Xframeobject * newframeobject PROTO(
  1709. X    (frameobject *, codeobject *, object *, object *, int, int));
  1710. X
  1711. X
  1712. X/* The rest of the interface is specific for frame objects */
  1713. X
  1714. X/* List access macros */
  1715. X
  1716. X#ifdef NDEBUG
  1717. X#define GETITEM(v, i) GETLISTITEM((listobject *)(v), (i))
  1718. X#define GETITEMNAME(v, i) GETSTRINGVALUE((stringobject *)GETITEM((v), (i)))
  1719. X#else
  1720. X#define GETITEM(v, i) getlistitem((v), (i))
  1721. X#define GETITEMNAME(v, i) getstringvalue(getlistitem((v), (i)))
  1722. X#endif
  1723. X
  1724. X#define GETUSTRINGVALUE(s) ((unsigned char *)GETSTRINGVALUE(s))
  1725. X
  1726. X/* Code access macros */
  1727. X
  1728. X#define Getconst(f, i)    (GETITEM((f)->f_code->co_consts, (i)))
  1729. X#define Getname(f, i)    (GETITEMNAME((f)->f_code->co_names, (i)))
  1730. X
  1731. X
  1732. X/* Block management functions */
  1733. X
  1734. Xvoid setup_block PROTO((frameobject *, int, int, int));
  1735. Xblock *pop_block PROTO((frameobject *));
  1736. EOF
  1737. fi
  1738. if test -s 'src/funcobject.c'
  1739. then echo '*** I will not over-write existing file src/funcobject.c'
  1740. else
  1741. echo 'x - src/funcobject.c'
  1742. sed 's/^X//' > 'src/funcobject.c' << 'EOF'
  1743. X/***********************************************************
  1744. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  1745. XNetherlands.
  1746. X
  1747. X                        All Rights Reserved
  1748. X
  1749. XPermission to use, copy, modify, and distribute this software and its 
  1750. Xdocumentation for any purpose and without fee is hereby granted, 
  1751. Xprovided that the above copyright notice appear in all copies and that
  1752. Xboth that copyright notice and this permission notice appear in 
  1753. Xsupporting documentation, and that the names of Stichting Mathematisch
  1754. XCentrum or CWI not be used in advertising or publicity pertaining to
  1755. Xdistribution of the software without specific, written prior permission.
  1756. X
  1757. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  1758. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1759. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  1760. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  1761. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  1762. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  1763. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  1764. X
  1765. X******************************************************************/
  1766. X
  1767. X/* Function object implementation */
  1768. X
  1769. X#include "allobjects.h"
  1770. X
  1771. X#include "structmember.h"
  1772. X
  1773. Xtypedef struct {
  1774. X    OB_HEAD
  1775. X    object *func_code;
  1776. X    object *func_globals;
  1777. X} funcobject;
  1778. X
  1779. Xobject *
  1780. Xnewfuncobject(code, globals)
  1781. X    object *code;
  1782. X    object *globals;
  1783. X{
  1784. X    funcobject *op = NEWOBJ(funcobject, &Functype);
  1785. X    if (op != NULL) {
  1786. X        INCREF(code);
  1787. X        op->func_code = code;
  1788. X        INCREF(globals);
  1789. X        op->func_globals = globals;
  1790. X    }
  1791. X    return (object *)op;
  1792. X}
  1793. X
  1794. Xobject *
  1795. Xgetfunccode(op)
  1796. X    object *op;
  1797. X{
  1798. X    if (!is_funcobject(op)) {
  1799. X        err_badcall();
  1800. X        return NULL;
  1801. X    }
  1802. X    return ((funcobject *) op) -> func_code;
  1803. X}
  1804. X
  1805. Xobject *
  1806. Xgetfuncglobals(op)
  1807. X    object *op;
  1808. X{
  1809. X    if (!is_funcobject(op)) {
  1810. X        err_badcall();
  1811. X        return NULL;
  1812. X    }
  1813. X    return ((funcobject *) op) -> func_globals;
  1814. X}
  1815. X
  1816. X/* Methods */
  1817. X
  1818. X#define OFF(x) offsetof(funcobject, x)
  1819. X
  1820. Xstatic struct memberlist func_memberlist[] = {
  1821. X    {"func_code",    T_OBJECT,    OFF(func_code)},
  1822. X    {"func_globals",T_OBJECT,    OFF(func_globals)},
  1823. X    {NULL}    /* Sentinel */
  1824. X};
  1825. X
  1826. Xstatic object *
  1827. Xfunc_getattr(op, name)
  1828. X    funcobject *op;
  1829. X    char *name;
  1830. X{
  1831. X    return getmember((char *)op, func_memberlist, name);
  1832. X}
  1833. X
  1834. Xstatic void
  1835. Xfunc_dealloc(op)
  1836. X    funcobject *op;
  1837. X{
  1838. X    DECREF(op->func_code);
  1839. X    DECREF(op->func_globals);
  1840. X    DEL(op);
  1841. X}
  1842. X
  1843. Xtypeobject Functype = {
  1844. X    OB_HEAD_INIT(&Typetype)
  1845. X    0,
  1846. X    "function",
  1847. X    sizeof(funcobject),
  1848. X    0,
  1849. X    func_dealloc,    /*tp_dealloc*/
  1850. X    0,        /*tp_print*/
  1851. X    func_getattr,    /*tp_getattr*/
  1852. X    0,        /*tp_setattr*/
  1853. X    0,        /*tp_compare*/
  1854. X    0,        /*tp_repr*/
  1855. X};
  1856. EOF
  1857. fi
  1858. if test -s 'src/grammar.h'
  1859. then echo '*** I will not over-write existing file src/grammar.h'
  1860. else
  1861. echo 'x - src/grammar.h'
  1862. sed 's/^X//' > 'src/grammar.h' << 'EOF'
  1863. X/***********************************************************
  1864. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  1865. XNetherlands.
  1866. X
  1867. X                        All Rights Reserved
  1868. X
  1869. XPermission to use, copy, modify, and distribute this software and its 
  1870. Xdocumentation for any purpose and without fee is hereby granted, 
  1871. Xprovided that the above copyright notice appear in all copies and that
  1872. Xboth that copyright notice and this permission notice appear in 
  1873. Xsupporting documentation, and that the names of Stichting Mathematisch
  1874. XCentrum or CWI not be used in advertising or publicity pertaining to
  1875. Xdistribution of the software without specific, written prior permission.
  1876. X
  1877. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  1878. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1879. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  1880. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  1881. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  1882. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  1883. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  1884. X
  1885. X******************************************************************/
  1886. X
  1887. X/* Grammar interface */
  1888. X
  1889. X#include "bitset.h" /* Sigh... */
  1890. X
  1891. X/* A label of an arc */
  1892. X
  1893. Xtypedef struct _label {
  1894. X    int    lb_type;
  1895. X    char    *lb_str;
  1896. X} label;
  1897. X
  1898. X#define EMPTY 0        /* Label number 0 is by definition the empty label */
  1899. X
  1900. X/* A list of labels */
  1901. X
  1902. Xtypedef struct _labellist {
  1903. X    int    ll_nlabels;
  1904. X    label    *ll_label;
  1905. X} labellist;
  1906. X
  1907. X/* An arc from one state to another */
  1908. X
  1909. Xtypedef struct _arc {
  1910. X    short        a_lbl;        /* Label of this arc */
  1911. X    short        a_arrow;    /* State where this arc goes to */
  1912. X} arc;
  1913. X
  1914. X/* A state in a DFA */
  1915. X
  1916. Xtypedef struct _state {
  1917. X    int         s_narcs;
  1918. X    arc        *s_arc;        /* Array of arcs */
  1919. X    
  1920. X    /* Optional accelerators */
  1921. X    int         s_lower;    /* Lowest label index */
  1922. X    int         s_upper;    /* Highest label index */
  1923. X    int        *s_accel;    /* Accelerator */
  1924. X    int         s_accept;    /* Nonzero for accepting state */
  1925. X} state;
  1926. X
  1927. X/* A DFA */
  1928. X
  1929. Xtypedef struct _dfa {
  1930. X    int         d_type;    /* Non-terminal this represents */
  1931. X    char        *d_name;    /* For printing */
  1932. X    int         d_initial;    /* Initial state */
  1933. X    int         d_nstates;
  1934. X    state        *d_state;    /* Array of states */
  1935. X    bitset         d_first;
  1936. X} dfa;
  1937. X
  1938. X/* A grammar */
  1939. X
  1940. Xtypedef struct _grammar {
  1941. X    int         g_ndfas;
  1942. X    dfa        *g_dfa;        /* Array of DFAs */
  1943. X    labellist     g_ll;
  1944. X    int         g_start;    /* Start symbol of the grammar */
  1945. X    int         g_accel;    /* Set if accelerators present */
  1946. X} grammar;
  1947. X
  1948. X/* FUNCTIONS */
  1949. X
  1950. Xgrammar *newgrammar PROTO((int start));
  1951. Xdfa *adddfa PROTO((grammar *g, int type, char *name));
  1952. Xint addstate PROTO((dfa *d));
  1953. Xvoid addarc PROTO((dfa *d, int from, int to, int lbl));
  1954. Xdfa *finddfa PROTO((grammar *g, int type));
  1955. Xchar *typename PROTO((grammar *g, int lbl));
  1956. X
  1957. Xint addlabel PROTO((labellist *ll, int type, char *str));
  1958. Xint findlabel PROTO((labellist *ll, int type, char *str));
  1959. Xchar *labelrepr PROTO((label *lb));
  1960. Xvoid translatelabels PROTO((grammar *g));
  1961. X
  1962. Xvoid addfirstsets PROTO((grammar *g));
  1963. X
  1964. Xvoid addaccellerators PROTO((grammar *g));
  1965. X
  1966. Xvoid printgrammar PROTO((grammar *g, FILE *fp));
  1967. Xvoid printnonterminals PROTO((grammar *g, FILE *fp));
  1968. EOF
  1969. fi
  1970. if test -s 'src/intobject.h'
  1971. then echo '*** I will not over-write existing file src/intobject.h'
  1972. else
  1973. echo 'x - src/intobject.h'
  1974. sed 's/^X//' > 'src/intobject.h' << 'EOF'
  1975. X/***********************************************************
  1976. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  1977. XNetherlands.
  1978. X
  1979. X                        All Rights Reserved
  1980. X
  1981. XPermission to use, copy, modify, and distribute this software and its 
  1982. Xdocumentation for any purpose and without fee is hereby granted, 
  1983. Xprovided that the above copyright notice appear in all copies and that
  1984. Xboth that copyright notice and this permission notice appear in 
  1985. Xsupporting documentation, and that the names of Stichting Mathematisch
  1986. XCentrum or CWI not be used in advertising or publicity pertaining to
  1987. Xdistribution of the software without specific, written prior permission.
  1988. X
  1989. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  1990. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1991. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  1992. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  1993. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  1994. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  1995. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  1996. X
  1997. X******************************************************************/
  1998. X
  1999. X/* Integer object interface */
  2000. X
  2001. X/*
  2002. X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12
  2003. X
  2004. Xintobject represents a (long) integer.  This is an immutable object;
  2005. Xan integer cannot change its value after creation.
  2006. X
  2007. XThere are functions to create new integer objects, to test an object
  2008. Xfor integer-ness, and to get the integer value.  The latter functions
  2009. Xreturns -1 and sets errno to EBADF if the object is not an intobject.
  2010. XNone of the functions should be applied to nil objects.
  2011. X
  2012. XThe type intobject is (unfortunately) exposed bere so we can declare
  2013. XTrueObject and FalseObject below; don't use this.
  2014. X*/
  2015. X
  2016. Xtypedef struct {
  2017. X    OB_HEAD
  2018. X    long ob_ival;
  2019. X} intobject;
  2020. X
  2021. Xextern typeobject Inttype;
  2022. X
  2023. X#define is_intobject(op) ((op)->ob_type == &Inttype)
  2024. X
  2025. Xextern object *newintobject PROTO((long));
  2026. Xextern long getintvalue PROTO((object *));
  2027. X
  2028. X
  2029. X/*
  2030. X123456789-123456789-123456789-123456789-123456789-123456789-123456789-12
  2031. X
  2032. XFalse and True are special intobjects used by Boolean expressions.
  2033. XAll values of type Boolean must point to either of these; but in
  2034. Xcontexts where integers are required they are integers (valued 0 and 1).
  2035. XHope these macros don't conflict with other people's.
  2036. X
  2037. XDon't forget to apply INCREF() when returning True or False!!!
  2038. X*/
  2039. X
  2040. Xextern intobject FalseObject, TrueObject; /* Don't use these directly */
  2041. X
  2042. X#define False ((object *) &FalseObject)
  2043. X#define True ((object *) &TrueObject)
  2044. X
  2045. X/* Macro, trading safety for speed */
  2046. X#define GETINTVALUE(op) ((op)->ob_ival)
  2047. EOF
  2048. fi
  2049. if test -s 'src/intrcheck.c'
  2050. then echo '*** I will not over-write existing file src/intrcheck.c'
  2051. else
  2052. echo 'x - src/intrcheck.c'
  2053. sed 's/^X//' > 'src/intrcheck.c' << 'EOF'
  2054. X/***********************************************************
  2055. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  2056. XNetherlands.
  2057. X
  2058. X                        All Rights Reserved
  2059. X
  2060. XPermission to use, copy, modify, and distribute this software and its 
  2061. Xdocumentation for any purpose and without fee is hereby granted, 
  2062. Xprovided that the above copyright notice appear in all copies and that
  2063. Xboth that copyright notice and this permission notice appear in 
  2064. Xsupporting documentation, and that the names of Stichting Mathematisch
  2065. XCentrum or CWI not be used in advertising or publicity pertaining to
  2066. Xdistribution of the software without specific, written prior permission.
  2067. X
  2068. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  2069. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2070. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  2071. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  2072. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  2073. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  2074. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  2075. X
  2076. X******************************************************************/
  2077. X
  2078. X/* Check for interrupts */
  2079. X
  2080. X#ifdef MSDOS
  2081. X
  2082. X/* This might work for MS-DOS (untested though): */
  2083. X
  2084. Xvoid
  2085. Xinitintr()
  2086. X{
  2087. X}
  2088. X
  2089. Xint
  2090. Xintrcheck()
  2091. X{
  2092. X    int interrupted = 0;
  2093. X    while (kbhit()) {
  2094. X        if (getch() == '\003')
  2095. X            interrupted = 1;
  2096. X    }
  2097. X    return interrupted;
  2098. X}
  2099. X
  2100. X#define OK
  2101. X
  2102. X#endif
  2103. X
  2104. X
  2105. X#ifdef THINK_C
  2106. X
  2107. X/* This is for THINK C 4.0.
  2108. X   For 3.0, you may have to remove the signal stuff. */
  2109. X
  2110. X#include <MacHeaders>
  2111. X#include <signal.h>
  2112. X#include "sigtype.h"
  2113. X
  2114. Xstatic int interrupted;
  2115. X
  2116. Xstatic SIGTYPE
  2117. Xintcatcher(sig)
  2118. X    int sig;
  2119. X{
  2120. X    interrupted = 1;
  2121. X    signal(SIGINT, intcatcher);
  2122. X}
  2123. X
  2124. Xvoid
  2125. Xinitintr()
  2126. X{
  2127. X    if (signal(SIGINT, SIG_IGN) != SIG_IGN)
  2128. X        signal(SIGINT, intcatcher);
  2129. X}
  2130. X
  2131. Xint
  2132. Xintrcheck()
  2133. X{
  2134. X    register EvQElPtr q;
  2135. X    
  2136. X    /* This is like THINK C 4.0's <console.h>.
  2137. X       I'm not sure why FlushEvents must be called from asm{}. */
  2138. X    for (q = (EvQElPtr)EventQueue.qHead; q; q = (EvQElPtr)q->qLink) {
  2139. X        if (q->evtQWhat == keyDown &&
  2140. X                (char)q->evtQMessage == '.' &&
  2141. X                (q->evtQModifiers & cmdKey) != 0) {
  2142. X            
  2143. X            asm {
  2144. X                moveq    #keyDownMask,d0
  2145. X                _FlushEvents
  2146. X            }
  2147. X            interrupted = 1;
  2148. X            break;
  2149. X        }
  2150. X    }
  2151. X    if (interrupted) {
  2152. X        interrupted = 0;
  2153. X        return 1;
  2154. X    }
  2155. X    return 0;
  2156. X}
  2157. X
  2158. X#define OK
  2159. X
  2160. X#endif /* THINK_C */
  2161. X
  2162. X
  2163. X#ifndef OK
  2164. X
  2165. X/* Default version -- for real operating systems and for Standard C */
  2166. X
  2167. X#include <stdio.h>
  2168. X#include <signal.h>
  2169. X#include "sigtype.h"
  2170. X
  2171. Xstatic int interrupted;
  2172. X
  2173. Xstatic SIGTYPE
  2174. Xintcatcher(sig)
  2175. X    int sig;
  2176. X{
  2177. X    interrupted = 1;
  2178. X    signal(SIGINT, intcatcher);
  2179. X}
  2180. X
  2181. Xvoid
  2182. Xinitintr()
  2183. X{
  2184. X    if (signal(SIGINT, SIG_IGN) != SIG_IGN)
  2185. X        signal(SIGINT, intcatcher);
  2186. X}
  2187. X
  2188. Xint
  2189. Xintrcheck()
  2190. X{
  2191. X    if (!interrupted)
  2192. X        return 0;
  2193. X    interrupted = 0;
  2194. X    return 1;
  2195. X}
  2196. X
  2197. X#endif /* !OK */
  2198. EOF
  2199. fi
  2200. if test -s 'src/profmain.c'
  2201. then echo '*** I will not over-write existing file src/profmain.c'
  2202. else
  2203. echo 'x - src/profmain.c'
  2204. sed 's/^X//' > 'src/profmain.c' << 'EOF'
  2205. X/***********************************************************
  2206. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  2207. XNetherlands.
  2208. X
  2209. X                        All Rights Reserved
  2210. X
  2211. XPermission to use, copy, modify, and distribute this software and its 
  2212. Xdocumentation for any purpose and without fee is hereby granted, 
  2213. Xprovided that the above copyright notice appear in all copies and that
  2214. Xboth that copyright notice and this permission notice appear in 
  2215. Xsupporting documentation, and that the names of Stichting Mathematisch
  2216. XCentrum or CWI not be used in advertising or publicity pertaining to
  2217. Xdistribution of the software without specific, written prior permission.
  2218. X
  2219. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  2220. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2221. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  2222. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  2223. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  2224. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  2225. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  2226. X
  2227. X******************************************************************/
  2228. X
  2229. X#include <stdio.h>
  2230. X#include "string.h"
  2231. X
  2232. X#include "PROTO.h"
  2233. X#include "grammar.h"
  2234. X#include "node.h"
  2235. X#include "parsetok.h"
  2236. X#include "graminit.h"
  2237. X#include "tokenizer.h"
  2238. X#include "errcode.h"
  2239. X#include "malloc.h"
  2240. X
  2241. Xextern int _profile;
  2242. X
  2243. Xextern grammar gram; /* From graminit.c */
  2244. X
  2245. Xint debugging = 1;
  2246. X
  2247. XFILE *getopenfile()
  2248. X{
  2249. X    char buf[256];
  2250. X    char *p;
  2251. X    FILE *fp;
  2252. X    for (;;) {
  2253. X        fprintf(stderr, "File name: ");
  2254. X        if (fgets(buf, sizeof buf, stdin) == NULL) {
  2255. X            fprintf(stderr, "EOF\n");
  2256. X            exit(1);
  2257. X        }
  2258. X        p = strchr(buf, '\n');
  2259. X        if (p != NULL)
  2260. X            *p = '\0';
  2261. X        if ((fp = fopen(buf, "r")) != NULL)
  2262. X            break;
  2263. X        fprintf(stderr, "Sorry, try again.\n");
  2264. X    }
  2265. X    return fp;
  2266. X}
  2267. X
  2268. Xmain()
  2269. X{
  2270. X    FILE *fp;
  2271. X    _profile = 0;
  2272. X    fp = getopenfile();
  2273. X#if 0
  2274. X    askgo("Start tokenizing");
  2275. X    runtokenizer(fp);
  2276. X    fseek(fp, 0L, 0);
  2277. X#endif
  2278. X    if (!gram.g_accel)
  2279. X        addaccelerators(&gram);
  2280. X    askgo("Start parsing");
  2281. X    _profile = 1;
  2282. X    runparser(fp);
  2283. X    _profile = 0;
  2284. X    freopen("prof.out", "w", stdout);
  2285. X    DumpProfile();
  2286. X    fflush(stdout);
  2287. X    exit(0);
  2288. X}
  2289. X
  2290. Xstatic int
  2291. Xruntokenizer(fp)
  2292. X    FILE *fp;
  2293. X{
  2294. X    struct tok_state *tok;
  2295. X    tok = tok_setupf(fp, "Tokenizing", ".");
  2296. X    for (;;) {
  2297. X        char *a, *b;
  2298. X        register char *str;
  2299. X        register int len;
  2300. X        (void) tok_get(tok, &a, &b);
  2301. X        if (tok->done != E_OK)
  2302. X            break;
  2303. X        len = b - a;
  2304. X        str = NEW(char, len + 1);
  2305. X        if (str == NULL) {
  2306. X            fprintf(stderr, "no mem for next token");
  2307. X            break;
  2308. X        }
  2309. X        strncpy(str, a, len);
  2310. X        str[len] = '\0';
  2311. X    }
  2312. X    fprintf(stderr, "done (%d)\n", tok->done);
  2313. X}
  2314. X
  2315. Xstatic
  2316. Xrunparser(fp, start)
  2317. X    FILE *fp;
  2318. X{
  2319. X    node *n;
  2320. X    int ret;
  2321. X    ret = parsefile(fp, &gram, module_input, "Parsing", ".", &n);
  2322. X    fprintf(stderr, "done (%d)\n", ret);
  2323. X#if 0
  2324. X    _profile = 0;
  2325. X    if (ret == E_DONE)
  2326. X        listtree(n);
  2327. X#endif
  2328. X}
  2329. X
  2330. Xstatic int
  2331. Xaskgo(prompt)
  2332. X    char *prompt;
  2333. X{
  2334. X    char buf[256];
  2335. X    fprintf(stderr, "%s: hit return when ready: ", prompt);
  2336. X    fgets(buf, sizeof buf, stdin);
  2337. X}
  2338. EOF
  2339. fi
  2340. if test -s 'src/strtol.c'
  2341. then echo '*** I will not over-write existing file src/strtol.c'
  2342. else
  2343. echo 'x - src/strtol.c'
  2344. sed 's/^X//' > 'src/strtol.c' << 'EOF'
  2345. X/***********************************************************
  2346. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  2347. XNetherlands.
  2348. X
  2349. X                        All Rights Reserved
  2350. X
  2351. XPermission to use, copy, modify, and distribute this software and its 
  2352. Xdocumentation for any purpose and without fee is hereby granted, 
  2353. Xprovided that the above copyright notice appear in all copies and that
  2354. Xboth that copyright notice and this permission notice appear in 
  2355. Xsupporting documentation, and that the names of Stichting Mathematisch
  2356. XCentrum or CWI not be used in advertising or publicity pertaining to
  2357. Xdistribution of the software without specific, written prior permission.
  2358. X
  2359. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  2360. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2361. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  2362. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  2363. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  2364. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  2365. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  2366. X
  2367. X******************************************************************/
  2368. X
  2369. X/*
  2370. X**    strtol
  2371. X**        This is a general purpose routine for converting
  2372. X**        an ascii string to an integer in an arbitrary base.
  2373. X**        Leading white space is ignored, if 'base' is zero
  2374. X**        it looks for a leading 0, 0x or 0X to tell which
  2375. X**        base.  If these are absent it defaults to 10.
  2376. X**        Base must be between 0 and 36.
  2377. X**        If 'ptr' is non-NULL it will contain a pointer to
  2378. X**        the end of the scan.
  2379. X**        Errors due to bad pointers will probably result in
  2380. X**        exceptions - we don't check for them.
  2381. X*/
  2382. X
  2383. X#include "ctype.h"
  2384. X
  2385. Xlong
  2386. Xstrtol(str, ptr, base)
  2387. Xregister char *    str;
  2388. Xchar **        ptr;
  2389. Xint        base;
  2390. X{
  2391. X    register long    result;    /* return value of the function */
  2392. X    register int    c;    /* current input character */
  2393. X    int            minus;    /* true if a leading minus was found */
  2394. X
  2395. X    result = 0;
  2396. X    minus = 0;
  2397. X
  2398. X/* catch silly bases */
  2399. X    if (base < 0 || base > 36)
  2400. X    {
  2401. X    if (ptr)
  2402. X        *ptr = str;
  2403. X    return result;
  2404. X    }
  2405. X
  2406. X/* skip leading white space */
  2407. X    while (*str && isspace(*str))
  2408. X    str++;
  2409. X
  2410. X/* check for optional leading minus sign */
  2411. X    if (*str == '-')
  2412. X    {
  2413. X    minus = 1;
  2414. X    str++;
  2415. X    }
  2416. X
  2417. X/* check for leading 0 or 0x for auto-base or base 16 */
  2418. X    switch (base)
  2419. X    {
  2420. X    case 0:        /* look for leading 0, 0x or 0X */
  2421. X    if (*str == '0')
  2422. X    {
  2423. X        str++;
  2424. X        if (*str == 'x' || *str == 'X')
  2425. X        {
  2426. X        str++;
  2427. X        base = 16;
  2428. X        }
  2429. X        else
  2430. X        base = 8;
  2431. X    }
  2432. X    else
  2433. X        base = 10;
  2434. X    break;
  2435. X
  2436. X    case 16:    /* skip leading 0x or 0X */
  2437. X    if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
  2438. X        str += 2;
  2439. X    break;
  2440. X    }
  2441. X
  2442. X/* do the conversion */
  2443. X    while (c = *str)
  2444. X    {
  2445. X    if (isdigit(c) && c - '0' < base)
  2446. X        c -= '0';
  2447. X    else
  2448. X    {
  2449. X        if (isupper(c))
  2450. X        c = tolower(c);
  2451. X        if (c >= 'a' && c <= 'z')
  2452. X        c -= 'a' - 10;
  2453. X        else    /* non-"digit" character */
  2454. X        break;
  2455. X        if (c >= base)    /* non-"digit" character */
  2456. X        break;
  2457. X    }
  2458. X    result = result * base + c;
  2459. X    str++;
  2460. X    }
  2461. X
  2462. X/* set pointer to point to the last character scanned */
  2463. X    if (ptr)
  2464. X    *ptr = str;
  2465. X    return minus ? -result : result;
  2466. X}
  2467. EOF
  2468. fi
  2469. echo 'Part 17 out of 21 of pack.out complete.'
  2470. exit 0
  2471.