home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 2 / 2800 < 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 08/21
  4. Message-ID: <2970@charon.cwi.nl>
  5. Date: 19 Feb 91 17:41:48 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 08 out of 21:'
  12. if test -s 'doc/mod1.tex'
  13. then echo '*** I will not over-write existing file doc/mod1.tex'
  14. else
  15. echo 'x - doc/mod1.tex'
  16. sed 's/^X//' > 'doc/mod1.tex' << 'EOF'
  17. X\section{Introduction}
  18. X
  19. XThe {\Python} library consists of three parts, with different levels of
  20. Xintegration with the interpreter.
  21. XClosest to the interpreter are built-in types, exceptions and functions.
  22. XNext are built-in modules, which are written in C and linked statically
  23. Xwith the interpreter.
  24. XFinally there are standard modules that are implemented entirely in
  25. X{\Python}, but are always available.
  26. XFor efficiency, some standard modules may become built-in modules in
  27. Xfuture versions of the interpreter.
  28. X
  29. X\section{Built-in Types, Exceptions and Functions}
  30. X
  31. XNames for built-in exceptions and functions are found in a separate
  32. Xread-only symbol table which cannot be modified.
  33. XThis table is searched last, so local and global user-defined names can
  34. Xoverride built-in names.
  35. XBuilt-in types have no names but are created by syntactic constructs
  36. X(such as constants) or built-in functions.
  37. XThey are described together here for easy reference.%
  38. X\footnote{
  39. XThe descriptions sorely lack explanations of the exceptions that
  40. Xmay be raised---this will be fixed in a future version of this
  41. Xdocument.
  42. X}
  43. X
  44. X\subsection{Built-in Types}
  45. X
  46. XThe following sections describe the standard types that are built into the
  47. Xinterpreter.
  48. X\subsubsection{Numeric Types}
  49. X
  50. XThere are two numeric types: integers and floating point numbers.
  51. XIntegers are implemented using {\tt long} in C, so they have at least 32
  52. Xbits of precision.
  53. XFloating point numbers are implemented using {\tt double} in C.
  54. XAll bets on precision are off.
  55. XNumbers are created by numeric constants or as the result of built-in
  56. Xfunctions and operators.
  57. X
  58. XNumeric types support the following operations:
  59. X
  60. X\begin{center}
  61. X\begin{tabular}{|c|l|c|}
  62. X\hline
  63. XOperation & Result & Notes \\
  64. X\hline
  65. X{\tt abs}({\em x}) & absolute value of {\em x} & \\
  66. X{\tt int}({\em x}) & {\em x} converted to integer & (1) \\
  67. X{\tt float}({\em x}) & {\em x} converted to floating point & \\
  68. X{\tt -}{\em x} & {\em x} negated & \\
  69. X{\tt +}{\em x} & {\em x} unchanged & \\
  70. X{\em x}{\tt +}{\em y} & sum of {\em x} and {\em y} & \\
  71. X{\em x}{\tt -}{\em y} & difference of {\em x} and {\em y} & \\
  72. X{\em x}{\tt *}{\em y} & product of {\em x} and {\em y} & \\
  73. X{\em x}{\tt /}{\em y} & quotient of {\em x} and {\em y} & (2) \\
  74. X{\em x}{\tt \%}{\em y} & remainder of {\em x}{\tt /}{\em y} & (3) \\
  75. X\hline
  76. X\end{tabular}
  77. X\end{center}
  78. X
  79. X\noindent
  80. XNotes:
  81. X\begin{description}
  82. X\item[(1)]
  83. XThis may round or truncate as in C; see functions {\tt floor} and
  84. X{\tt ceil} in module {\tt math}.
  85. X\item[(2)]
  86. XInteger division is defined as in C: the result is an integer; with
  87. Xpositive operands, it truncates towards zero; with a negative operand,
  88. Xthe result is unspecified.
  89. X\item[(3)]
  90. XOnly defined for integers.
  91. X\end{description}
  92. X
  93. XMixed arithmetic is not supported; both operands must have the same type.
  94. XMixed comparisons return the wrong result (floats always compare smaller
  95. Xthan integers).%
  96. X\footnote{
  97. XThese restrictions are bugs in the language definitions and will be
  98. Xfixed in the future.
  99. X}
  100. X\subsubsection{Sequence Types}
  101. X
  102. XThere are three sequence types: strings, lists and tuples.
  103. XStrings constants are written in single quotes: {\tt 'xyzzy'}.
  104. XLists are constructed with square brackets: {\tt [a,~b,~c]}.
  105. XTuples are constructed by the comma operator or with an empty set of
  106. Xparentheses: {\tt a,~b,~c} or {\tt ()}.
  107. X
  108. XSequence types support the following operations ({\em s} and {\em t} are
  109. Xsequences of the same type; {\em n}, {\em i} and {\em j} are integers):
  110. X
  111. X\begin{center}
  112. X\begin{tabular}{|c|l|c|}
  113. X\hline
  114. XOperation & Result & Notes \\
  115. X\hline
  116. X{\tt len}({\em s}) & length of {\em s} & \\
  117. X{\tt min}({\em s}) & smallest item of {\em s} & \\
  118. X{\tt max}({\em s}) & largest item of {\em s} & \\
  119. X{\em x} {\tt in} {\em s} &
  120. X    true if an item of {\em s} is equal to {\em x} & \\
  121. X{\em x} {\tt not} {\tt in} {\em s} &
  122. X    false if an item of {\em s} is equal to {\em x} & \\
  123. X{\em s}{\tt +}{\em t} & the concatenation of {\em s} and {\em t} & \\
  124. X{\em s}{\tt *}{\em n}, {\em n}*{\em s} &
  125. X    {\em n} copies of {\em s} concatenated & (1) \\
  126. X{\em s}[{\em i}] & {\em i}'th item of {\em s} & \\
  127. X{\em s}[{\em i}:{\em j}] &
  128. X    slice of {\em s} from {\em i} to {\em j} & (2) \\
  129. X\hline
  130. X\end{tabular}
  131. X\end{center}
  132. X
  133. X\noindent
  134. XNotes:
  135. X\begin{description}
  136. X\item[(1)]
  137. XSequence repetition is only supported for strings.
  138. X\item[(2)]
  139. XThe slice of $s$ from $i$ to $j$ is defined as the sequence
  140. Xof items with index $k$ such that $i \leq k < j$.
  141. XSpecial rules apply for negative and omitted indices; see the Tutorial
  142. Xor the Reference Manual.
  143. X\end{description}
  144. X
  145. X\paragraph{Mutable Sequence Types.}
  146. X
  147. XList objects support additional operations that allow in-place
  148. Xmodification of the object.
  149. XThese operations would be supported by other mutable sequence types
  150. X(when added to the language) as well.
  151. XStrings and tuples are immutable sequence types and such objects cannot
  152. Xbe modified once created.
  153. XThe following operations are defined on mutable sequence types (where
  154. X{\em x} is an arbitrary object):
  155. X
  156. X\begin{center}
  157. X\begin{tabular}{|c|l|}
  158. X\hline
  159. XOperation & Result \\
  160. X\hline
  161. X{\em s}[{\em i}] = {\em x} &
  162. X    item {\em i} of {\em s} is replaced by {\em x} \\
  163. X{\em s}[{\em i}:{\em j}] = {\em t} &
  164. X    slice of {\em s} from {\em i} to {\em j} is replaced by {\em t} \\
  165. X{\tt del} {\em s}[{\em i}:{\em j}] &
  166. X    same as {\em s}[{\em i}:{\em j}] = [] \\
  167. X{\em s}.{\tt append}({\em x}) &
  168. X    same as {\em s}[{\tt len}({\em x}):{\tt len}({\em x})] = [{\em x}] \\
  169. X{\em s}.{\tt insert}({\em i}, {\em x}) &
  170. X    same as {\em s}[{\em i}:{\em i}] = [{\em x}] \\
  171. X{\em s}.{\tt sort}() &
  172. X    the items of {\em s} are permuted to satisfy \\
  173. X    &
  174. X    $s[i] \leq s[j]$ for $i < j$\\
  175. X\hline
  176. X\end{tabular}
  177. X\end{center}
  178. X
  179. X\subsubsection{Mapping Types}
  180. X
  181. XA
  182. X{\em mapping}
  183. Xobject maps values of one type (the key type) to arbitrary objects.
  184. XMappings are mutable objects.
  185. XThere is currently only one mapping type, the
  186. X{\em dictionary}.
  187. XA dictionary's keys are strings.
  188. XAn empty dictionary is created by the expression \verb"{}".
  189. XAn extension of this notation is used to display dictionaries when
  190. Xwritten (see the example below).
  191. X
  192. XThe following operations are defined on mappings (where {\em a} is a
  193. Xmapping, {\em k} is a key and {\em x} is an arbitrary object):
  194. X
  195. X\begin{center}
  196. X\begin{tabular}{|c|l|c|}
  197. X\hline
  198. XOperation & Result & Notes\\
  199. X\hline
  200. X{\tt len}({\em a}) & the number of elements in {\em a} & \\
  201. X{\em a}[{\em k}] & the item of {\em a} with key {\em k} & \\
  202. X{\em a}[{\em k}] = {\em x} & set {\em a}[{\em k}] to {\em x} & \\
  203. X{\tt del} {\em a}[{\em k}] & remove {\em a}[{\em k}] from {\em a} & \\
  204. X{\em a}.{\tt keys}() & a copy of {\em a}'s list of keys & (1) \\
  205. X{\em a}.{\tt has\_key}({\em k}) & true if {\em a} has a key {\em k} & \\
  206. X\hline
  207. X\end{tabular}
  208. X\end{center}
  209. X
  210. X\noindent
  211. XNotes:
  212. X\begin{description}
  213. X\item[(1)]
  214. XKeys are listed in random order.
  215. X\end{description}
  216. X
  217. XA small example using a dictionary:
  218. X\bcode\begin{verbatim}
  219. X>>> tel = {}
  220. X>>> tel['jack'] = 4098
  221. X>>> tel['sape'] = 4139
  222. X>>> tel['guido'] = 4127
  223. X>>> tel['jack']
  224. X4098
  225. X>>> tel
  226. X{'sape': 4139; 'guido': 4127; 'jack': 4098}
  227. X>>> del tel['sape']
  228. X>>> tel['irv'] = 4127
  229. X>>> tel
  230. X{'guido': 4127; 'irv': 4127; 'jack': 4098}
  231. X>>> tel.keys()
  232. X['guido', 'irv', 'jack']
  233. X>>> tel.has_key('guido')
  234. X1
  235. X>>> 
  236. X\end{verbatim}\ecode
  237. X\subsubsection{Other Built-in Types}
  238. X
  239. XThe interpreter supports several other kinds of objects.
  240. XMost of these support only one or two operations.
  241. X
  242. X\paragraph{Modules.}
  243. X
  244. XThe only operation on a module is member acces: {\em m}{\tt .}{\em name},
  245. Xwhere {\em m} is a module and {\em name} accesses a name defined in
  246. X{\em m}'s symbol table.
  247. XModule members can be assigned to.
  248. X
  249. X\paragraph{Classes and Class Objects.}
  250. X
  251. XXXX Classes will be explained at length in a later version of this
  252. Xdocument.
  253. X
  254. X\paragraph{Functions.}
  255. X
  256. XFunction objects are created by function definitions.
  257. XThe only operation on a function object is to call it:
  258. X{\em func}({\em optional-arguments}).
  259. X
  260. XBuilt-in functions have a different type than user-defined functions,
  261. Xbut they support the same operation.
  262. X
  263. X\paragraph{Methods.}
  264. X
  265. XMethods are functions that are called using the member acces notation.
  266. XThere are two flavors: built-in methods (such as {\tt append()} on
  267. Xlists) and class member methods.
  268. XBuilt-in methods are described with the types that support them.
  269. XXXX Class member methods will be described in a later version of this
  270. Xdocument.
  271. X
  272. X\paragraph{Type Objects.}
  273. X
  274. XType objects represent the various object types.
  275. XAn object's type is accessed by the built-in function
  276. X{\tt type()}.
  277. XThere are no operations on type objects.
  278. X
  279. X\paragraph{The Null Object.}
  280. X
  281. XThis object is returned by functions that don't explicitly return a
  282. Xvalue.
  283. XIt supports no operations.
  284. XThere is exactly one null object, named {\tt None}
  285. X(a built-in name).
  286. X
  287. X\paragraph{File Objects.}
  288. X
  289. XFile objects are implemented using C's
  290. X{\em stdio}
  291. Xpackage and can be created with the built-in function
  292. X{\tt open()}.
  293. XThey have the following methods:
  294. X\begin{description}
  295. X\funcitem{close}{}
  296. XCloses the file.
  297. XA closed file cannot be read or written anymore.
  298. X\funcitem{read}{size}
  299. XReads at most
  300. X{\tt size}
  301. Xbytes from the file (less if the read hits EOF).
  302. XThe bytes are returned as a string object.
  303. XAn empty string is returned when EOF is hit immediately.
  304. X(For certain files, like ttys, it makes sense to continue reading after
  305. Xan EOF is hit.)
  306. X\funcitem{readline}{size}
  307. XReads a line of at most
  308. X{\tt size}
  309. Xbytes from the file.
  310. XA trailing newline character, if present, is kept in the string.
  311. XThe size is optional and defaults to a large number (but not infinity).
  312. XEOF is reported as by
  313. X{\tt read().}
  314. X\funcitem{write}{str}
  315. XWrites a string to the file.
  316. XReturns no value.
  317. X\end{description}
  318. X
  319. X\subsection{Built-in Exceptions}
  320. X
  321. XThe following exceptions can be generated by the interpreter or
  322. Xbuilt-in functions.
  323. XExcept where mentioned, they have a string argument (also known as the
  324. X`associated value' of an exception) indicating the detailed cause of the
  325. Xerror.
  326. XThe strings listed with the exception names are their values when used
  327. Xin an expression or printed.
  328. X\begin{description}
  329. X\excitem{EOFError}{end-of-file read}
  330. X(No argument.)
  331. XRaised when a built-in function ({\tt input()} or {\tt raw\_input()})
  332. Xhits an end-of-file condition (EOF) without reading any data.
  333. X(N.B.: the {\tt read()} and {\tt readline()} methods of file objects
  334. Xreturn an empty string when they hit EOF.)
  335. X\excitem{KeyboardInterrupt}{end-of-file read}
  336. X(No argument.)
  337. XRaised when the user hits the interrupt key (normally Control-C or DEL).
  338. XDuring execution, a check for interrupts is made regularly.
  339. XInterrupts typed when a built-in function ({\tt input()} or
  340. X{\tt raw\_input()}) is waiting for input also raise this exception.
  341. X\excitem{MemoryError}{out of memory}
  342. X%.br
  343. XRaised when an operation runs out of memory but the situation
  344. Xmay still be rescued (by deleting some objects).
  345. X\excitem{NameError}{undefined name}
  346. X%.br
  347. XRaised when a name is not found.
  348. XThis applies to unqualified names, module names (on {\tt import}),
  349. Xmodule members and object methods.
  350. XThe string argument is the name that could not be found.
  351. X\excitem{RuntimeError}{run-time error}
  352. X%.br
  353. XRaised for a variety of reasons, e.g., division by zero or index out of
  354. Xrange.
  355. X\excitem{SystemError}{system error}
  356. X%.br
  357. XRaised when the interpreter finds an internal error, but the situation
  358. Xdoes not look so serious to cause it to abandon all hope.
  359. X\excitem{TypeError}{type error}
  360. X%.br
  361. XRaised when an operation or built-in function is applied to an object of
  362. Xinappropriate type.
  363. X\end{description}
  364. X
  365. X\subsection{Built-in Functions}
  366. X
  367. XThe {\Python} interpreter has a small number of functions built into it that
  368. Xare always available.
  369. XThey are listed here in alphabetical order.
  370. X\begin{description}
  371. X\funcitem{abs}{x}
  372. XReturns the absolute value of a number.
  373. XThe argument may be an integer or floating point number.
  374. X\funcitem{chr}{i}
  375. XReturns a string of one character
  376. Xwhose ASCII code is the integer {\tt i},
  377. Xe.g., {\tt chr(97)} returns the string {\tt 'a'}.
  378. XThis is the inverse of {\tt ord()}.
  379. X\funcitem{dir}{}
  380. XWithout arguments, this function returns the list of names in the
  381. Xcurrent local symbol table, sorted alphabetically.
  382. XWith a module object as argument, it returns the sorted list of names in
  383. Xthat module's global symbol table.
  384. XFor example:
  385. X\bcode\begin{verbatim}
  386. X>>> import sys
  387. X>>> dir()
  388. X['sys']
  389. X>>> dir(sys)
  390. X['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
  391. X>>> 
  392. X\end{verbatim}\ecode
  393. X\funcitem{divmod}{a, b}
  394. X%.br
  395. XTakes two integers as arguments and returns a pair of integers
  396. Xconsisting of their quotient and remainder.
  397. XFor
  398. X\bcode\begin{verbatim}
  399. Xq, r = divmod(a, b)
  400. X\end{verbatim}\ecode
  401. Xthe invariants are:
  402. X\bcode\begin{verbatim}
  403. Xa = q*b + r
  404. Xabs(r) < abs(b)
  405. Xr has the same sign as b
  406. X\end{verbatim}\ecode
  407. XFor example:
  408. X\bcode\begin{verbatim}
  409. X>>> divmod(100, 7)
  410. X(14, 2)
  411. X>>> divmod(-100, 7)
  412. X(-15, 5)
  413. X>>> divmod(100, -7)
  414. X(-15, -5)
  415. X>>> divmod(-100, -7)
  416. X(14, -2)
  417. X>>> 
  418. X\end{verbatim}\ecode
  419. X\funcitem{eval}{s}
  420. XTakes a string as argument and parses and evaluates it as a {\Python}
  421. Xexpression.
  422. XThe expression is executed using the current local and global symbol
  423. Xtables.
  424. XSyntax errors are reported as exceptions.
  425. XFor example:
  426. X\bcode\begin{verbatim}
  427. X>>> x = 1
  428. X>>> eval('x+1')
  429. X2
  430. X>>> 
  431. X\end{verbatim}\ecode
  432. X\funcitem{exec}{s}
  433. XTakes a string as argument and parses and evaluates it as a sequence of
  434. X{\Python} statements.
  435. XThe string should end with a newline (\verb"'\n'").
  436. XThe statement is executed using the current local and global symbol
  437. Xtables.
  438. XSyntax errors are reported as exceptions.
  439. XFor example:
  440. X\bcode\begin{verbatim}
  441. X>>> x = 1
  442. X>>> exec('x = x+1\n')
  443. X>>> x
  444. X2
  445. X>>> 
  446. X\end{verbatim}\ecode
  447. X\funcitem{float}{x}
  448. XConverts a number to floating point.
  449. XThe argument may be an integer or floating point number.
  450. X\funcitem{input}{s}
  451. XEquivalent to
  452. X{\tt eval(raw\_input(s))}.
  453. XAs for
  454. X{\tt raw\_input()},
  455. Xthe argument is optional.
  456. X\funcitem{int}{x}
  457. XConverts a number to integer.
  458. XThe argument may be an integer or floating point number.
  459. X\funcitem{len}{s}
  460. XReturns the length (the number of items) of an object.
  461. XThe argument may be a sequence (string, tuple or list) or a mapping
  462. X(dictionary).
  463. X\funcitem{max}{s}
  464. XReturns the largest item of a non-empty sequence (string, tuple or list).
  465. X\funcitem{min}{s}
  466. XReturns the smallest item of a non-empty sequence (string, tuple or list).
  467. X\funcitem{open}{name, mode}
  468. X%.br
  469. XReturns a file object (described earlier under Built-in Types).
  470. XThe string arguments are the same as for stdio's
  471. X{\tt fopen()}:
  472. X{\tt 'r'}
  473. Xopens the file for reading,
  474. X{\tt 'w'}
  475. Xopens it for writing (truncating an existing file),
  476. X{\tt 'a'}
  477. Xopens it for appending.%
  478. X\footnote{
  479. XThis function should go into a built-in module
  480. X{\tt io}.
  481. X}
  482. X\funcitem{ord}{c}
  483. XTakes a string of one character and returns its
  484. XASCII value, e.g., {\tt ord('a')} returns the integer {\tt 97}.
  485. XThis is the inverse of {\tt chr()}.
  486. X\funcitem{range}{}
  487. XThis is a versatile function to create lists containing arithmetic
  488. Xprogressions of integers.
  489. XWith two integer arguments, it returns the ascending sequence of
  490. Xintegers starting at the first and ending one before the second
  491. Xargument.
  492. XA single argument is used as the end point of the sequence, with 0 used
  493. Xas the starting point.
  494. XA third argument specifies the step size; negative steps are allowed and
  495. Xwork as expected, but don't specify a zero step.
  496. XThe resulting list may be empty.
  497. XFor example:
  498. X\bcode\begin{verbatim}
  499. X>>> range(10)
  500. X[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  501. X>>> range(1, 1+10)
  502. X[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  503. X>>> range(0, 30, 5)
  504. X[0, 5, 10, 15, 20, 25]
  505. X>>> range(0, 10, 3)
  506. X[0, 3, 6, 9]
  507. X>>> range(0, -10, -1)
  508. X[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  509. X>>> range(0)
  510. X[]
  511. X>>> range(1, 0)
  512. X[]
  513. X>>> 
  514. X\end{verbatim}\ecode
  515. X\funcitem{raw\_input}{s}
  516. X%.br
  517. XThe argument is optional; if present, it is written to standard output
  518. Xwithout a trailing newline.
  519. XThe function then reads a line from input, converts it to a string
  520. X(stripping a trailing newline), and returns that.
  521. XEOF is reported as an exception.
  522. XFor example:
  523. X\bcode\begin{verbatim}
  524. X>>> raw_input('Type anything: ')
  525. XType anything: Mutant Teenage Ninja Turtles
  526. X'Mutant Teenage Ninja Turtles'
  527. X>>> 
  528. X\end{verbatim}\ecode
  529. X\funcitem{reload}{module}
  530. XCauses an already imported module to be re-parsed and re-initialized.
  531. XThis is useful if you have edited the module source file and want to
  532. Xtry out the new version without leaving {\Python}.
  533. X\funcitem{type}{x}
  534. XReturns the type of an object.
  535. XTypes are objects themselves:
  536. Xthe type of a type object is its own type.
  537. X\end{description}
  538. EOF
  539. fi
  540. if test -s 'src/Makefile'
  541. then echo '*** I will not over-write existing file src/Makefile'
  542. else
  543. echo 'x - src/Makefile'
  544. sed 's/^X//' > 'src/Makefile' << 'EOF'
  545. X# /***********************************************************
  546. X# Copyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  547. X# Netherlands.
  548. X# 
  549. X#                         All Rights Reserved
  550. X# 
  551. X# Permission to use, copy, modify, and distribute this software and its 
  552. X# documentation for any purpose and without fee is hereby granted, 
  553. X# provided that the above copyright notice appear in all copies and that
  554. X# both that copyright notice and this permission notice appear in 
  555. X# supporting documentation, and that the names of Stichting Mathematisch
  556. X# Centrum or CWI not be used in advertising or publicity pertaining to
  557. X# distribution of the software without specific, written prior permission.
  558. X# 
  559. X# STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  560. X# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  561. X# FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  562. X# FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  563. X# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  564. X# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  565. X# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  566. X# 
  567. X# ******************************************************************/
  568. X
  569. X# Makefile for Python
  570. X# ===================
  571. X#
  572. X# If you are in a hurry, you can just edit this Makefile to choose the
  573. X# correct settings for SYSV and RANLIB below, and type "make" in this
  574. X# directory.  If you are using a recent version of SunOS (or Ultrix?)
  575. X# you don't even have to edit: the Makefile comes pre-configured for
  576. X# such systems with all configurable options turned off, building the
  577. X# minimal portable version of the Python interpreter.
  578. X#
  579. X# If have more time, read the section on configurable options below.
  580. X# It may still be wise to begin building the minimal portable Python,
  581. X# to see if it works at all, and select options later.  You don't have
  582. X# to rebuild all objects when you turn on options; all dependencies
  583. X# are concentrated in the file "config.c" which is rebuilt whenever
  584. X# the Makefile changes.  (Except if you turn on the GNU Readline option
  585. X# you may have to toss out the tokenizer.o object.)
  586. X
  587. X
  588. X# Operating System Defines (ALWAYS READ THIS)
  589. X# ===========================================
  590. X
  591. X# Uncomment the following line if you are using a System V derivative.
  592. X# This must be used, for instance, on an SGI IRIS.  Don't use it for
  593. X# SunOS.  (This is only needed by posixmodule.c...)
  594. X
  595. X#SYSVDEF=    -DSYSV
  596. X
  597. X# Choose one of the following two lines depending on whether your system
  598. X# requires the use of 'ranlib' after creating a library, or not.
  599. X
  600. X#RANLIB =    true    # For System V
  601. XRANLIB =    ranlib    # For BSD
  602. X
  603. X# If your system doesn't have symbolic links, uncomment the following
  604. X# line.
  605. X
  606. X#NOSYMLINKDEF=    -DNO_LSTAT
  607. X
  608. X
  609. X# Installation Options
  610. X# ====================
  611. X
  612. X# You may want to change PYTHONPATH to reflect where you install the
  613. X# Python module library.
  614. X
  615. XPYTHONPATH=    .:/usr/local/lib/python:/ufs/guido/lib/python
  616. X
  617. X
  618. X# For "Pure" BSD Systems
  619. X# ======================
  620. X#
  621. X# "Pure" BSD systems (as opposed to enhanced BSD derivatives like SunOS)
  622. X# often miss certain standard library functions.  Source for
  623. X# these is provided, you just have to turn it on.  This may work for
  624. X# other systems as well, where these things are needed.
  625. X
  626. X# If your system does not have a strerror() function in the library,
  627. X# uncomment the following two lines to use one I wrote.  (Actually, this
  628. X# is missing in most systems I have encountered, so it is turned on
  629. X# in the Makefile.  Turn it off if your system doesn't have sys_errlist.)
  630. X
  631. XSTRERROR_SRC=  strerror.c
  632. XSTRERROR_OBJ=  strerror.o
  633. X
  634. X# If your BSD system does not have a fmod() function in the library,
  635. X# uncomment the following two lines to use one I wrote.
  636. X
  637. X#FMOD_SRC=  fmod.c
  638. X#FMOD_OBJ=  fmod.o
  639. X
  640. X# If your BSD system does not have a strtol() function in the library,
  641. X# uncomment the following two lines to use one I wrote.
  642. X
  643. X#STRTOL_SRC=  strtol.c
  644. X#STRTOL_OBJ=  strtol.o
  645. X
  646. X# If your BSD system does not have a getcwd() function in the library,
  647. X# but it does have a getwd() function, uncomment the following two lines
  648. X# to use one I wrote.  (If you don't have getwd() either, turn on the
  649. X# NO_GETWD #define in getcwd.c.)
  650. X
  651. X#GETCWD_SRC=  getcwd.c
  652. X#GETCWD_OBJ=  getcwd.o
  653. X
  654. X# If your signal() function believes signal handlers return int,
  655. X# uncomment the following line.
  656. X
  657. X#SIGTYPEDEF=    -DSIGTYPE=int
  658. X
  659. X
  660. X# Further porting hints
  661. X# =====================
  662. X#
  663. X# If you don't have the header file <string.h>, but you do have
  664. X# <strings.h>, create a file "string.h" in this directory which contains
  665. X# the single line "#include <strings.h>", and add "-I." to CFLAGS.
  666. X# If you don't have the functions strchr and strrchr, add definitions
  667. X# "-Dstrchr=index -Dstrrchr=rindex" to CFLAGS.  (NB: CFLAGS is not
  668. X# defined in this Makefile.)
  669. X
  670. X
  671. X# Configurable Options
  672. X# ====================
  673. X#
  674. X# Python can be configured to interface to various system libraries that
  675. X# are not available on all systems.  It is also possible to configure
  676. X# the input module to use the GNU Readline library for interactive
  677. X# input.  For each configuration choice you must uncomment the relevant
  678. X# section of the Makefile below.  Note: you may also have to change a
  679. X# pathname and/or an architecture identifier that is hardcoded in the
  680. X# Makefile.
  681. X#
  682. X# Read the comments to determine if you can use the option.  (You can
  683. X# always leave all options off and build a minimal portable version of
  684. X# Python.)
  685. X
  686. X
  687. X# BSD Time Option
  688. X# ===============
  689. X#
  690. X# This option does not add a new module but adds two functions to
  691. X# an existing module.
  692. X#
  693. X# It implements time.millisleep() and time.millitimer()
  694. X# using the BSD system calls select() and gettimeofday().
  695. X#
  696. X# Uncomment the following line to select this option.
  697. X
  698. X#BSDTIMEDEF=    -DBSD_TIME
  699. X
  700. X
  701. X# GNU Readline Option
  702. X# ===================
  703. X#
  704. X# If you have the sources of the GNU Readline library you can have
  705. X# full interactive command line editing and history in Python.
  706. X# The GNU Readline library is distributed with the BASH shell
  707. X# (I only know of version 1.05).  You must build the GNU Readline
  708. X# library and the alloca routine it needs in their own source
  709. X# directories (which are subdirectories of the basg source directory),
  710. X# and plant a pointer to the BASH source directory in this Makefile.
  711. X#
  712. X# Uncomment and edit the following block to use the GNU Readline option.
  713. X# - Edit the definition of BASHDIR to point to the bash source tree.
  714. X# You may have to fix the definition of LIBTERMCAP; leave the LIBALLOCA
  715. X# definition commented if alloca() is in your C library.
  716. X
  717. X#BASHDIR=    ../../bash-1.05
  718. X#LIBREADLINE=    $(BASHDIR)/readline/libreadline.a
  719. X#LIBALLOCA=    $(BASHDIR)/alloc-files/alloca.o
  720. X#LIBTERMCAP=    -ltermcap
  721. X#RL_USE =    -DUSE_READLINE
  722. X#RL_LIBS=    $(LIBREADLINE) $(LIBALLOCA) $(LIBTERMCAP)
  723. X#RL_LIBDEPS=    $(LIBREADLINE) $(LIBALLOCA)
  724. X
  725. X
  726. X# STDWIN Option
  727. X# =============
  728. X#
  729. X# If you have the sources of STDWIN (by the same author) you can
  730. X# configure Python to incorporate the built-in module 'stdwin'.
  731. X# This requires a fairly recent version of STDWIN (dated late 1990).
  732. X#
  733. X# Uncomment and edit the following block to use the STDWIN option.
  734. X# - Edit the STDWINDIR defition to reflect the top of the STDWIN source
  735. X#   tree.
  736. X# - Edit the ARCH definition to reflect your system's architecture
  737. X#   (usually the program 'arch' or 'machine' returns this).
  738. X# You may have to edit the LIBX11 defition to reflect the location of
  739. X# the X11 runtime library if it is non-standard.
  740. X
  741. X#STDWINDIR=    ../../stdwin
  742. X#ARCH=        sgi
  743. X#LIBSTDWIN=    $(STDWINDIR)/Build/$(ARCH)/x11/lib/lib.a
  744. X#LIBX11 =    -lX11
  745. X#STDW_INCL=    -I$(STDWINDIR)/H
  746. X#STDW_USE=    -DUSE_STDWIN
  747. X#STDW_LIBS=    $(LIBSTDWIN) $(LIBX11)
  748. X#STDW_LIBDEPS=    $(LIBSTDWIN)
  749. X#STDW_SRC=    stdwinmodule.c
  750. X#STDW_OBJ=    stdwinmodule.o
  751. X
  752. X
  753. X# Amoeba Option
  754. X# =============
  755. X#
  756. X# If you have the Amoeba 4.0 distribution (Beta or otherwise) you can
  757. X# configure Python to incorporate the built-in module 'amoeba'.
  758. X# (Python can also be built for native Amoeba, but it requires more
  759. X# work and thought.  Contact the author.)
  760. X#
  761. X# Uncomment and edit the following block to use the Amoeba option.
  762. X# - Edit the AMOEBADIR defition to reflect the top of the Amoeba source
  763. X#   tree.
  764. X# - Edit the AM_CONF definition to reflect the machine/operating system
  765. X#   configuration needed by Amoeba (this is the name of a subdirectory
  766. X#   of $(AMOEBADIR)/conf/unix, e.g., vax.ultrix).
  767. X
  768. X#AMOEBADIR=    /usr/amoeba
  769. X#AM_CONF=    mipseb.irix
  770. X#LIBAMUNIX=    $(AMOEBADIR)/conf/unix/$(AM_CONF)/lib/amunix/libamunix.a
  771. X#AM_INCL=    -I$(AMOEBADIR)/src/h
  772. X#AM_USE =    -DUSE_AMOEBA
  773. X#AM_LIBDEPS=    $(LIBAMUNIX)
  774. X#AM_LIBS=    $(LIBAMUNIX)
  775. X#AM_SRC =    amoebamodule.c sc_interpr.c sc_errors.c
  776. X#AM_OBJ =    amoebamodule.o sc_interpr.o sc_errors.o
  777. X
  778. X
  779. X# Silicon Graphics IRIS Options
  780. X# =============================
  781. X#
  782. X# The following three options are only relevant if you are using a
  783. X# Silicon Graphics IRIS machine.  These have been tested with IRIX 3.3.1
  784. X# on a 4D/25.
  785. X
  786. X
  787. X# GL Option
  788. X# =========
  789. X#
  790. X# This option incorporates the built-in module 'gl', which provides a
  791. X# complete interface to the Silicon Graphics GL library.  It adds
  792. X# about 70K to the Python text size and about 260K to the unstripped
  793. X# binary size.
  794. X#
  795. X# Note: the file 'glmodule.c' is created by a Python script.  If you
  796. X# lost the file and have no working Python interpreter, turn off the GL
  797. X# and Panel options, rebuild the Python interpreter, use it to create
  798. X# glmodule.c, and then turn the options back on.
  799. X#
  800. X# Uncomment the following block to use the GL option.
  801. X
  802. X#GL_USE =    -DUSE_GL
  803. X#GL_LIBDEPS=    
  804. X#GL_LIBS=    -lgl_s
  805. X#GL_SRC =    glmodule.c cgensupport.c
  806. X#GL_OBJ =    glmodule.o cgensupport.o
  807. X
  808. X
  809. X# Panel Option
  810. X# ============
  811. X#
  812. X# If you have source to the NASA Ames Panel Library, you can configure
  813. X# Python to incorporate the built-in module 'pnl', which is used byu
  814. X# the standard module 'panel' to provide an interface to most features
  815. X# of the Panel Library.  This option requires that you also turn on the
  816. X# GL option.  It adds about 100K to the Python text size and about 160K
  817. X# to the unstripped binary size.
  818. X#
  819. X# Uncomment and edit the following block to use the Panel option.
  820. X# - Edit the PANELDIR definition to point to the top-level directory
  821. X#   of the Panel distribution tree.
  822. X
  823. X#PANELDIR=    /usr/people/guido/src/pl
  824. X#PANELLIBDIR=    $(PANELDIR)/library
  825. X#LIBPANEL=    $(PANELLIBDIR)/lib/libpanel.a
  826. X#PANEL_USE=    -DUSE_PANEL
  827. X#PANEL_INCL=    -I$(PANELLIBDIR)/include
  828. X#PANEL_LIBDEPS=    $(LIBPANEL)
  829. X#PANEL_LIBS=    $(LIBPANEL)
  830. X#PANEL_SRC=    panelmodule.c
  831. X#PANEL_OBJ=    panelmodule.o
  832. X
  833. X
  834. X# Audio Option
  835. X# ============
  836. X#
  837. X# This option lets you play with /dev/audio on the IRIS 4D/25.
  838. X# It incorporates the built-in module 'audio'.
  839. X# Warning: using the asynchronous I/O facilities of this module can
  840. X# create a second 'thread', which looks in the listings of 'ps' like a
  841. X# forked child.  However, it shares its address space with the parent.
  842. X#
  843. X# Uncomment the following block to use the Audio option.
  844. X
  845. X#AUDIO_USE=    -DUSE_AUDIO
  846. X#AUDIO_SRC=    audiomodule.c asa.c
  847. X#AUDIO_OBJ=    audiomodule.o asa.o
  848. X
  849. X
  850. X# Major Definitions
  851. X# =================
  852. X
  853. XSTANDARD_OBJ=    acceler.o bltinmodule.o ceval.o classobject.o \
  854. X        compile.o dictobject.o errors.o fgetsintr.o \
  855. X        fileobject.o floatobject.o $(FMOD_OBJ) frameobject.o \
  856. X        funcobject.o $(GETCWD_OBJ) \
  857. X        graminit.o grammar1.o import.o \
  858. X        intobject.o intrcheck.o listnode.o listobject.o \
  859. X        mathmodule.o methodobject.o modsupport.o \
  860. X        moduleobject.o node.o object.o parser.o \
  861. X        parsetok.o posixmodule.o regexp.o regexpmodule.o \
  862. X        strdup.o $(STRERROR_OBJ) \
  863. X        stringobject.o $(STRTOL_OBJ) structmember.o \
  864. X        sysmodule.o timemodule.o tokenizer.o traceback.o \
  865. X        tupleobject.o typeobject.o
  866. X
  867. XSTANDARD_SRC=    acceler.c bltinmodule.c ceval.c classobject.c \
  868. X        compile.c dictobject.c errors.c fgetsintr.c \
  869. X        fileobject.c floatobject.c $(FMOD_SRC) frameobject.c \
  870. X        funcobject.c $(GETCWD_SRC) \
  871. X        graminit.c grammar1.c import.c \
  872. X        intobject.c intrcheck.c listnode.c listobject.c \
  873. X        mathmodule.c methodobject.c modsupport.c \
  874. X        moduleobject.c node.c object.c parser.c \
  875. X        parsetok.c posixmodule.c regexp.c regexpmodule.c \
  876. X        strdup.c $(STRERROR_SRC) \
  877. X        stringobject.c $(STRTOL_SRC) structmember.c \
  878. X        sysmodule.c timemodule.c tokenizer.c traceback.c \
  879. X        tupleobject.c typeobject.c
  880. X
  881. XCONFIGDEFS=    $(STDW_USE) $(AM_USE) $(AUDIO_USE) $(GL_USE) $(PANEL_USE) \
  882. X        '-DPYTHONPATH="$(PYTHONPATH)"'
  883. X
  884. XCONFIGINCLS=    $(STDW_INCL)
  885. X
  886. XLIBDEPS=    libpython.a $(STDW_LIBDEPS) $(AM_LIBDEPS) \
  887. X        $(GL_LIBDEPS) $(PANEL_LIBSDEP) $(RL_LIBDEPS)
  888. X
  889. X# NB: the ordering of items in LIBS is significant!
  890. XLIBS=        libpython.a $(STDW_LIBS) $(AM_LIBS) \
  891. X        $(PANEL_LIBS) $(GL_LIBS) $(RL_LIBS) -lm
  892. X
  893. XLIBOBJECTS=    $(STANDARD_OBJ) $(STDW_OBJ) $(AM_OBJ) $(AUDIO_OBJ) \
  894. X        $(GL_OBJ) $(PANEL_OBJ)
  895. X
  896. XLIBSOURCES=    $(STANDARD_SRC) $(STDW_SRC) $(AM_SRC) $(AUDIO_SRC) \
  897. X        $(GL_SRC) $(PANEL_SRC)
  898. X
  899. XOBJECTS=    pythonmain.o config.o
  900. X
  901. XSOURCES=    $(LIBSOURCES) pythonmain.c config.c
  902. X
  903. XGENOBJECTS=    acceler.o fgetsintr.o grammar1.o \
  904. X        intrcheck.o listnode.o node.o parser.o \
  905. X        parsetok.o strdup.o tokenizer.o bitset.o \
  906. X        firstsets.o grammar.o metagrammar.o pgen.o \
  907. X        pgenmain.o printgrammar.o
  908. X
  909. XGENSOURCES=    acceler.c fgetsintr.c grammar1.c \
  910. X        intrcheck.c listnode.c node.c parser.c \
  911. X        parsetok.c strdup.c tokenizer.c bitset.c \
  912. X        firstsets.c grammar.c metagrammar.c pgen.c \
  913. X        pgenmain.c printgrammar.c
  914. X
  915. X
  916. X# Main Targets
  917. X# ============
  918. X
  919. Xpython:        libpython.a $(OBJECTS) $(LIBDEPS) Makefile
  920. X        $(CC) $(CFLAGS) $(OBJECTS) $(LIBS) -o @python
  921. X        mv @python python
  922. X
  923. Xlibpython.a:    $(LIBOBJECTS)
  924. X        -rm -f @lib
  925. X        ar cr @lib $(LIBOBJECTS)
  926. X        $(RANLIB) @lib
  927. X        mv @lib libpython.a
  928. X
  929. Xpython_gen:    $(GENOBJECTS) $(RL_LIBDEPS)
  930. X        $(CC) $(CFLAGS) $(GENOBJECTS) $(RL_LIBS) -o python_gen
  931. X
  932. X
  933. X# Utility Targets
  934. X# ===============
  935. X
  936. X# Don't take the output from lint too seriously.  I have not attempted
  937. X# to make Python lint-free.  But I use function prototypes.
  938. X
  939. XLINTFLAGS=    -h
  940. X
  941. XLINTCPPFLAGS=    $(CONFIGDEFS) $(CONFIGINCLS) $(SYSVDEF) \
  942. X        $(AM_INCL) $(PANEL_INCL)
  943. X
  944. XLINT=        lint
  945. X
  946. Xlint::        $(SOURCES)
  947. X        $(LINT) $(LINTFLAGS) $(LINTCPPFLAGS) $(SOURCES)
  948. X
  949. Xlint::        $(GENSOURCES)
  950. X        $(LINT) $(LINTFLAGS) $(GENSOURCES)
  951. X
  952. X# Generating dependencies is only necessary if you intend to hack Python.
  953. X# You may change $(MKDEP) to your favorite dependency generator (it should
  954. X# edit the Makefile in place).
  955. X
  956. XMKDEP=        mkdep
  957. X
  958. Xdepend::
  959. X        $(MKDEP) $(LINTCPPFLAGS) $(SOURCES) $(GENSOURCES)
  960. X
  961. X# You may change $(CTAGS) to suit your taste...
  962. X
  963. XCTAGS=        ctags -t -w
  964. X
  965. XHEADERS=    *.h
  966. X
  967. Xtags:        $(SOURCES) $(GENSOURCES) $(HEADERS)
  968. X        $(CTAGS) $(SOURCES) $(GENSOURCES) $(HEADERS)
  969. X
  970. Xclean::
  971. X        -rm -f *.o core [,#@]*
  972. X
  973. Xclobber::    clean
  974. X        -rm -f python python_gen libpython.a tags
  975. X
  976. X
  977. X# Build Special Objects
  978. X# =====================
  979. X
  980. X# You may change $(COMPILE) to reflect the default .c.o rule...
  981. X
  982. XCOMPILE=    $(CC) -c $(CFLAGS)
  983. X
  984. Xamoebamodule.o:    amoebamodule.c
  985. X        $(COMPILE) $(AM_INCL) $*.c
  986. X
  987. Xconfig.o:    config.c Makefile
  988. X        $(COMPILE) $(CONFIGDEFS) $(CONFIGINCLS) $*.c
  989. X
  990. Xfgetsintr.o:    fgetsintr.c
  991. X        $(COMPILE) $(SIGTYPEDEF) $*.c
  992. X
  993. Xintrcheck.o:    intrcheck.c
  994. X        $(COMPILE) $(SIGTYPEDEF) $*.c
  995. X
  996. Xpanelmodule.o:    panelmodule.c
  997. X        $(COMPILE) $(PANEL_INCL) $*.c
  998. X
  999. Xposixmodule.o:    posixmodule.c
  1000. X        $(COMPILE) $(SYSVDEF) $(NOSYMLINKDEF) $*.c
  1001. X
  1002. Xsc_interpr.o:    sc_interpr.c
  1003. X        $(COMPILE) $(AM_INCL) $*.c
  1004. X
  1005. Xsc_error.o:    sc_error.c
  1006. X        $(COMPILE) $(AM_INCL) $*.c
  1007. X
  1008. Xstdwinmodule.o:    stdwinmodule.c
  1009. X        $(COMPILE) $(STDW_INCL) $*.c
  1010. X
  1011. Xtimemodule.o:    timemodule.c
  1012. X        $(COMPILE) $(SIGTYPEDEF) $(BSDTIMEDEF) $*.c
  1013. X
  1014. Xtokenizer.o:    tokenizer.c
  1015. X        $(COMPILE) $(RL_USE) $*.c
  1016. X
  1017. X.PRECIOUS:    python libpython.a glmodule.c graminit.c graminit.h
  1018. X
  1019. X
  1020. X# Generated Sources
  1021. X# =================
  1022. X#
  1023. X# Some source files are (or may be) generated.
  1024. X# The rules for doing so are given here.
  1025. X
  1026. X# Build "glmodule.c", the GL interface.
  1027. X# Ignore the messages emitted by the cgen script.
  1028. X# Also ignore the warnings emitted while compiling glmodule.c; it works.
  1029. X
  1030. Xglmodule.c:    cstubs cgen
  1031. X        python cgen <cstubs >@glmodule.c
  1032. X        mv @glmodule.c glmodule.c
  1033. X
  1034. X# The dependencies for graminit.[ch] are not turned on in the
  1035. X# distributed Makefile because the files themselves are distributed.
  1036. X# Turn them on if you want to hack the grammar.
  1037. X
  1038. X#graminit.c graminit.h:    Grammar python_gen
  1039. X#        python_gen Grammar
  1040. X
  1041. EOF
  1042. fi
  1043. if test -s 'src/amoebamodule.c'
  1044. then echo '*** I will not over-write existing file src/amoebamodule.c'
  1045. else
  1046. echo 'x - src/amoebamodule.c'
  1047. sed 's/^X//' > 'src/amoebamodule.c' << 'EOF'
  1048. X/***********************************************************
  1049. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  1050. XNetherlands.
  1051. X
  1052. X                        All Rights Reserved
  1053. X
  1054. XPermission to use, copy, modify, and distribute this software and its 
  1055. Xdocumentation for any purpose and without fee is hereby granted, 
  1056. Xprovided that the above copyright notice appear in all copies and that
  1057. Xboth that copyright notice and this permission notice appear in 
  1058. Xsupporting documentation, and that the names of Stichting Mathematisch
  1059. XCentrum or CWI not be used in advertising or publicity pertaining to
  1060. Xdistribution of the software without specific, written prior permission.
  1061. X
  1062. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  1063. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1064. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  1065. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  1066. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  1067. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  1068. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  1069. X
  1070. X******************************************************************/
  1071. X
  1072. X/* Amoeba module implementation */
  1073. X
  1074. X/* Amoeba includes */
  1075. X#include <amoeba.h>
  1076. X#include <cmdreg.h>
  1077. X#include <stdcom.h>
  1078. X#include <stderr.h>
  1079. X#include <caplist.h>
  1080. X#include <server/bullet/bullet.h>
  1081. X#include <server/tod/tod.h>
  1082. X#include <module/name.h>
  1083. X#include <module/direct.h>
  1084. X#include <module/mutex.h>
  1085. X#include <module/prv.h>
  1086. X#include <module/stdcmd.h>
  1087. X
  1088. X/* C includes */
  1089. X#include <stdlib.h>
  1090. X#include <ctype.h>
  1091. X
  1092. X/* POSIX includes */
  1093. X#include <fcntl.h>
  1094. X#include <sys/types.h>
  1095. X#include <sys/stat.h>
  1096. X
  1097. X/* Python includes */
  1098. X#include "allobjects.h"
  1099. X#include "modsupport.h"
  1100. X#include "sc_global.h"
  1101. X#include "stubcode.h"
  1102. X
  1103. Xextern char *err_why();
  1104. Xextern char *ar_cap();
  1105. X
  1106. X#define STUBCODE    "+stubcode"
  1107. X
  1108. Xstatic object *AmoebaError;
  1109. Xobject *StubcodeError;
  1110. X
  1111. Xstatic object *sc_dict;
  1112. X
  1113. X/* Module initialization */
  1114. X
  1115. Xextern struct methodlist amoeba_methods[]; /* Forward */
  1116. Xextern object *convertcapv(); /* Forward */
  1117. X
  1118. Xstatic void
  1119. Xins(d, name, v)
  1120. X    object *d;
  1121. X    char *name;
  1122. X    object *v;
  1123. X{
  1124. X    if (v == NULL || dictinsert(d, name, v) != 0)
  1125. X        fatal("can't initialize amoeba module");
  1126. X}
  1127. X
  1128. Xvoid
  1129. Xinitamoeba()
  1130. X{
  1131. X    object *m, *d, *v;
  1132. X    
  1133. X    m = initmodule("amoeba", amoeba_methods);
  1134. X    d = getmoduledict(m);
  1135. X    
  1136. X    /* Define capv */
  1137. X    v = convertcapv();
  1138. X    ins(d, "capv", v);
  1139. X    DECREF(v);
  1140. X    
  1141. X    /* Set timeout */
  1142. X    timeout((interval)2000);
  1143. X    
  1144. X    /* Initialize amoeba.error exception */
  1145. X    AmoebaError = newstringobject("amoeba.error");
  1146. X    ins(d, "error", AmoebaError);
  1147. X    StubcodeError = newstringobject("amoeba.stubcode_error");
  1148. X    ins(d, "stubcode_error", StubcodeError);
  1149. X    sc_dict = newdictobject();
  1150. X}
  1151. X
  1152. X
  1153. X/* Set an Amoeba-specific error, and return NULL */
  1154. X
  1155. Xobject *
  1156. Xamoeba_error(err)
  1157. X    errstat err;
  1158. X{
  1159. X    object *v = newtupleobject(2);
  1160. X    if (v != NULL) {
  1161. X        settupleitem(v, 0, newintobject((long)err));
  1162. X        settupleitem(v, 1, newstringobject(err_why(err)));
  1163. X    }
  1164. X    err_setval(AmoebaError, v);
  1165. X    if (v != NULL)
  1166. X        DECREF(v);
  1167. X    return NULL;
  1168. X}
  1169. X
  1170. X
  1171. X/* Capability object implementation */
  1172. X
  1173. Xextern typeobject Captype; /* Forward */
  1174. X
  1175. X#define is_capobject(v) ((v)->ob_type == &Captype)
  1176. X
  1177. Xtypedef struct {
  1178. X    OB_HEAD
  1179. X    capability ob_cap;
  1180. X} capobject;
  1181. X
  1182. Xobject *
  1183. Xnewcapobject(cap)
  1184. X    capability *cap;
  1185. X{
  1186. X    capobject *v = NEWOBJ(capobject, &Captype);
  1187. X    if (v == NULL)
  1188. X        return NULL;
  1189. X    v->ob_cap = *cap;
  1190. X    return (object *)v;
  1191. X}
  1192. X
  1193. Xgetcapability(v, cap)
  1194. X    object *v;
  1195. X    capability *cap;
  1196. X{
  1197. X
  1198. X    if (!is_capobject(v))
  1199. X        return err_badarg();
  1200. X    *cap = ((capobject *)v)->ob_cap;
  1201. X    return 0;
  1202. X}
  1203. X
  1204. X/*
  1205. X *    is_capobj exports the is_capobject macro to the stubcode modules
  1206. X */
  1207. X
  1208. Xint
  1209. Xis_capobj(v)
  1210. X    object *v;
  1211. X{
  1212. X
  1213. X    return is_capobject(v);
  1214. X}
  1215. X
  1216. X/* Methods */
  1217. X
  1218. Xstatic void
  1219. Xcapprint(v, fp, flags)
  1220. X    capobject *v;
  1221. X    FILE *fp;
  1222. X    int flags;
  1223. X{
  1224. X    /* XXX needs lock when multi-threading */
  1225. X    fputs(ar_cap(&v->ob_cap), fp);
  1226. X}
  1227. X
  1228. Xstatic object *
  1229. Xcaprepr(v)
  1230. X    capobject *v;
  1231. X{
  1232. X    /* XXX needs lock when multi-threading */
  1233. X    return newstringobject(ar_cap(&v->ob_cap));
  1234. X}
  1235. X
  1236. Xextern object *sc_interpreter();
  1237. X
  1238. Xextern struct methodlist cap_methods[]; /* Forward */
  1239. X
  1240. Xobject *
  1241. Xsc_makeself(cap, stubcode, name)
  1242. X    object *cap, *stubcode;
  1243. X    char *name;
  1244. X{
  1245. X    object *sc_name, *sc_self;
  1246. X
  1247. X    sc_name = newstringobject(name);
  1248. X    if (sc_name == NULL)
  1249. X        return NULL;
  1250. X    sc_self = newtupleobject(3);
  1251. X    if (sc_self == NULL) {
  1252. X        DECREF(sc_name);
  1253. X        return NULL;
  1254. X    }
  1255. X    if (settupleitem(sc_self, NAME, sc_name) != 0) {
  1256. X        DECREF(sc_self);
  1257. X        return NULL;
  1258. X    }
  1259. X    INCREF(cap);
  1260. X    if (settupleitem(sc_self, CAP, cap) != 0) {
  1261. X        DECREF(sc_self);
  1262. X        return NULL;
  1263. X    }
  1264. X    INCREF(stubcode);
  1265. X    if (settupleitem(sc_self, STUBC, stubcode) != 0) {
  1266. X        DECREF(sc_self);
  1267. X        return NULL;
  1268. X    }
  1269. X    return sc_self;
  1270. X}
  1271. X
  1272. X
  1273. Xstatic void
  1274. Xswapcode(code, len)
  1275. X    char *code;
  1276. X    int len;
  1277. X{
  1278. X    int i = sizeof(TscOperand);
  1279. X    TscOpcode opcode;
  1280. X    TscOperand operand;
  1281. X
  1282. X    while (i < len) {
  1283. X        memcpy(&opcode, &code[i], sizeof(TscOpcode));
  1284. X        SwapOpcode(opcode);
  1285. X        memcpy(&code[i], &opcode, sizeof(TscOpcode));
  1286. X        i += sizeof(TscOpcode);
  1287. X        if (opcode & OPERAND) {
  1288. X            memcpy(&operand, &code[i], sizeof(TscOperand));
  1289. X            SwapOperand(operand);
  1290. X            memcpy(&code[i], &operand, sizeof(TscOperand));
  1291. X            i += sizeof(TscOperand);
  1292. X        }
  1293. X    }
  1294. X}
  1295. X
  1296. Xobject *
  1297. Xsc_findstubcode(v, name)
  1298. X    object *v;
  1299. X    char *name;
  1300. X{
  1301. X    int fd, fsize;
  1302. X    char *fname, *buffer;
  1303. X    struct stat statbuf;
  1304. X    object *sc_stubcode, *ret;
  1305. X    TscOperand sc_magic;
  1306. X
  1307. X    /*
  1308. X     *   Only look in the current directory for now.
  1309. X     */
  1310. X    fname = malloc(strlen(name) + 4);
  1311. X    if (fname == NULL) {
  1312. X        return err_nomem();
  1313. X    }
  1314. X    sprintf(fname, "%s.sc", name);
  1315. X    if ((fd = open(fname, O_RDONLY)) == -1) {
  1316. X        extern int errno;
  1317. X
  1318. X        if (errno == 2) {
  1319. X            /*
  1320. X            **    errno == 2 is file not found.
  1321. X            */
  1322. X            err_setstr(NameError, fname);
  1323. X            return NULL;
  1324. X        }
  1325. X        free(fname);
  1326. X        return err_errno(newstringobject(name));
  1327. X    }
  1328. X    fstat(fd, &statbuf);
  1329. X    fsize = (int)statbuf.st_size;
  1330. X    buffer = malloc(fsize);
  1331. X    if (buffer == NULL) {
  1332. X        free(fname);
  1333. X        close(fd);
  1334. X        return err_nomem();
  1335. X    }
  1336. X    if (read(fd, buffer, fsize) != fsize) {
  1337. X        close(fd);
  1338. X        free(fname);
  1339. X        return err_errno(newstringobject(name));
  1340. X    }
  1341. X    close(fd);
  1342. X    free(fname);
  1343. X    memcpy(&sc_magic, buffer, sizeof(TscOperand));
  1344. X    if (sc_magic != SC_MAGIC) {
  1345. X        SwapOperand(sc_magic);
  1346. X        if (sc_magic != SC_MAGIC) {
  1347. X            free(buffer);
  1348. X            return NULL;
  1349. X        } else {
  1350. X            swapcode(buffer, fsize);
  1351. X        }
  1352. X    }
  1353. X    sc_stubcode = newsizedstringobject(    &buffer[sizeof(TscOperand)], 
  1354. X                        fsize - sizeof(TscOperand));
  1355. X    free(buffer);
  1356. X    if (sc_stubcode == NULL) {
  1357. X        return NULL;
  1358. X    }
  1359. X    if (dictinsert(sc_dict, name, sc_stubcode) != 0) {
  1360. X        DECREF(sc_stubcode);
  1361. X        return NULL;
  1362. X    }
  1363. X    DECREF(sc_stubcode); /* XXXX */
  1364. X    sc_stubcode = sc_makeself(v, sc_stubcode, name);
  1365. X    if (sc_stubcode == NULL) {
  1366. X        return NULL;
  1367. X    }
  1368. X    return sc_stubcode;
  1369. X}
  1370. X
  1371. Xobject *
  1372. Xcapgetattr(v, name)
  1373. X    capobject *v;
  1374. X    char *name;
  1375. X{
  1376. X    object *sc_method, *sc_stubcodemethod;
  1377. X
  1378. X    if (sc_dict == NULL) {
  1379. X        /*
  1380. X        **    For some reason the dictionary has not been
  1381. X        **    initialized.  Try to find one of the built in
  1382. X        **    methods.
  1383. X        */
  1384. X        return findmethod(cap_methods, (object *)v, name);
  1385. X    }
  1386. X    sc_stubcodemethod = dictlookup(sc_dict, name);
  1387. X    if (sc_stubcodemethod != NULL) {
  1388. X        /*
  1389. X        **    There is a stubcode method in the dictionary.
  1390. X        **    Execute the stubcode interpreter with the right
  1391. X        **    arguments.
  1392. X        */
  1393. X        object *self, *ret;
  1394. X
  1395. X        self = sc_makeself((object *)v, sc_stubcodemethod, name);
  1396. X        if (self == NULL) {
  1397. X            return NULL;
  1398. X        }
  1399. X        ret = findmethod(cap_methods, self, STUBCODE);
  1400. X        DECREF(self);
  1401. X        return ret;
  1402. X    }
  1403. X    err_clear();
  1404. X    sc_method = findmethod(cap_methods, (object *)v, name);
  1405. X    if (sc_method == NULL) {
  1406. X        /*
  1407. X        **    The method is not built in and not in the
  1408. X        **    dictionary. Try to find it as a stubcode file.
  1409. X        */
  1410. X        object *self, *ret;
  1411. X
  1412. X        err_clear();
  1413. X        self = sc_findstubcode((object *)v, name);
  1414. X        if (self == NULL) {
  1415. X            return NULL;
  1416. X        }
  1417. X        ret = findmethod(cap_methods, self, STUBCODE);
  1418. X        DECREF(self);
  1419. X        return ret;
  1420. X    }
  1421. X    return sc_method;
  1422. X}
  1423. X
  1424. Xint
  1425. Xcapcompare(v, w)
  1426. X    capobject *v, *w;
  1427. X{
  1428. X    int cmp = bcmp((char *)&v->ob_cap.cap_port,
  1429. X                    (char *)&w->ob_cap, PORTSIZE);
  1430. X    if (cmp != 0)
  1431. X        return cmp;
  1432. X    return prv_number(&v->ob_cap.cap_priv) -
  1433. X                    prv_number(&w->ob_cap.cap_priv);
  1434. X}
  1435. X
  1436. Xstatic typeobject Captype = {
  1437. X    OB_HEAD_INIT(&Typetype)
  1438. X    0,
  1439. X    "capability",
  1440. X    sizeof(capobject),
  1441. X    0,
  1442. X    free,        /*tp_dealloc*/
  1443. X    capprint,    /*tp_print*/
  1444. X    capgetattr,    /*tp_getattr*/
  1445. X    0,        /*tp_setattr*/
  1446. X    capcompare,    /*tp_compare*/
  1447. X    caprepr,    /*tp_repr*/
  1448. X    0,        /*tp_as_number*/
  1449. X    0,        /*tp_as_sequence*/
  1450. X    0,        /*tp_as_mapping*/
  1451. X};
  1452. X
  1453. X
  1454. X/* Return a dictionary corresponding to capv */
  1455. X
  1456. Xextern struct caplist *capv;
  1457. X
  1458. Xstatic object *
  1459. Xconvertcapv()
  1460. X{
  1461. X    object *d;
  1462. X    struct caplist *c;
  1463. X    d = newdictobject();
  1464. X    if (d == NULL)
  1465. X        return NULL;
  1466. X    if (capv == NULL)
  1467. X        return d;
  1468. X    for (c = capv; c->cl_name != NULL; c++) {
  1469. X        object *v = newcapobject(c->cl_cap);
  1470. X        if (v == NULL || dictinsert(d, c->cl_name, v) != 0) {
  1471. X            DECREF(d);
  1472. X            return NULL;
  1473. X        }
  1474. X        DECREF(v);
  1475. X    }
  1476. X    return d;
  1477. X}
  1478. X
  1479. X
  1480. X/* Strongly Amoeba-specific argument handlers */
  1481. X
  1482. Xstatic int
  1483. Xgetcaparg(v, a)
  1484. X    object *v;
  1485. X    capability *a;
  1486. X{
  1487. X    if (v == NULL || !is_capobject(v))
  1488. X        return err_badarg();
  1489. X    *a = ((capobject *)v) -> ob_cap;
  1490. X    return 1;
  1491. X}
  1492. X
  1493. Xstatic int
  1494. Xgetstrcapargs(v, a, b)
  1495. X    object *v;
  1496. X    object **a;
  1497. X    capability *b;
  1498. X{
  1499. X    if (v == NULL || !is_tupleobject(v) || gettuplesize(v) != 2)
  1500. X        return err_badarg();
  1501. X    return getstrarg(gettupleitem(v, 0), a) &&
  1502. X        getcaparg(gettupleitem(v, 1), b);
  1503. X}
  1504. X
  1505. X
  1506. X/* Amoeba methods */
  1507. X
  1508. Xstatic object *
  1509. Xamoeba_name_lookup(self, args)
  1510. X    object *self;
  1511. X    object *args;
  1512. X{
  1513. X    object *name;
  1514. X    capability cap;
  1515. X    errstat err;
  1516. X    if (!getstrarg(args, &name))
  1517. X        return NULL;
  1518. X    err = name_lookup(getstringvalue(name), &cap);
  1519. X    if (err != STD_OK)
  1520. X        return amoeba_error(err);
  1521. X    return newcapobject(&cap);
  1522. X}
  1523. X
  1524. Xstatic object *
  1525. Xamoeba_name_append(self, args)
  1526. X    object *self;
  1527. X    object *args;
  1528. X{
  1529. X    object *name;
  1530. X    capability cap;
  1531. X    errstat err;
  1532. X    if (!getstrcapargs(args, &name, &cap))
  1533. X        return NULL;
  1534. X    err = name_append(getstringvalue(name), &cap);
  1535. X    if (err != STD_OK)
  1536. X        return amoeba_error(err);
  1537. X    INCREF(None);
  1538. X    return None;
  1539. X}
  1540. X
  1541. Xstatic object *
  1542. Xamoeba_name_replace(self, args)
  1543. X    object *self;
  1544. X    object *args;
  1545. X{
  1546. X    object *name;
  1547. X    capability cap;
  1548. X    errstat err;
  1549. X    if (!getstrcapargs(args, &name, &cap))
  1550. X        return NULL;
  1551. X    err = name_replace(getstringvalue(name), &cap);
  1552. X    if (err != STD_OK)
  1553. X        return amoeba_error(err);
  1554. X    INCREF(None);
  1555. X    return None;
  1556. X}
  1557. X
  1558. Xstatic object *
  1559. Xamoeba_name_delete(self, args)
  1560. X    object *self;
  1561. X    object *args;
  1562. X{
  1563. X    object *name;
  1564. X    errstat err;
  1565. X    if (!getstrarg(args, &name))
  1566. X        return NULL;
  1567. X    err = name_delete(getstringvalue(name));
  1568. X    if (err != STD_OK)
  1569. X        return amoeba_error(err);
  1570. X    INCREF(None);
  1571. X    return None;
  1572. X}
  1573. X
  1574. Xstatic object *
  1575. Xamoeba_timeout(self, args)
  1576. X    object *self;
  1577. X    object *args;
  1578. X{
  1579. X    int i;
  1580. X    object *v;
  1581. X    interval tout;
  1582. X    if (!getintarg(args, &i))
  1583. X        return NULL;
  1584. X    tout = timeout((interval)i);
  1585. X    v = newintobject((long)tout);
  1586. X    if (v == NULL)
  1587. X        timeout(tout);
  1588. X    return v;
  1589. X}
  1590. X
  1591. Xstatic struct methodlist amoeba_methods[] = {
  1592. X    {"name_append",        amoeba_name_append},
  1593. X    {"name_delete",        amoeba_name_delete},
  1594. X    {"name_lookup",        amoeba_name_lookup},
  1595. X    {"name_replace",    amoeba_name_replace},
  1596. X    {"timeout",        amoeba_timeout},
  1597. X    {NULL,            NULL}             /* Sentinel */
  1598. X};
  1599. X
  1600. X/* Capability methods */
  1601. X
  1602. Xstatic object *
  1603. Xcap_b_size(self, args)
  1604. X    capobject *self;
  1605. X    object *args;
  1606. X{
  1607. X    errstat err;
  1608. X    b_fsize size;
  1609. X    if (!getnoarg(args))
  1610. X        return NULL;
  1611. X    err = b_size(&self->ob_cap, &size);
  1612. X    if (err != STD_OK)
  1613. X        return amoeba_error(err);
  1614. X    return newintobject((long)size);
  1615. X}
  1616. X
  1617. Xstatic object *
  1618. Xcap_b_read(self, args)
  1619. X    capobject *self;
  1620. X    object *args;
  1621. X{
  1622. X    errstat err;
  1623. X    char *buf;
  1624. X    object *v;
  1625. X    long offset, size;
  1626. X    b_fsize nread;
  1627. X    if (!getlonglongargs(args, &offset, &size))
  1628. X        return NULL;
  1629. X    buf = malloc((unsigned int)size);
  1630. X    if (buf == NULL) {
  1631. X        return err_nomem();
  1632. X    }
  1633. X    err = b_read(&self->ob_cap, (b_fsize)offset, buf, (b_fsize)size,
  1634. X                                &nread);
  1635. X    if (err != STD_OK) {
  1636. X        free(buf);
  1637. X        return amoeba_error(err);
  1638. X    }
  1639. X    v = newsizedstringobject(buf, (int)nread);
  1640. X    free(buf);
  1641. X    return v;
  1642. X}
  1643. X
  1644. Xstatic object *
  1645. Xcap_dir_lookup(self, args)
  1646. X    capobject *self;
  1647. X    object *args;
  1648. X{
  1649. X    object *name;
  1650. X    capability cap;
  1651. X    errstat err;
  1652. X    if (!getstrarg(args, &name))
  1653. X        return NULL;
  1654. X    err = dir_lookup(&self->ob_cap, getstringvalue(name), &cap);
  1655. X    if (err != STD_OK)
  1656. X        return amoeba_error(err);
  1657. X    return newcapobject(&cap);
  1658. X}
  1659. X
  1660. Xstatic object *
  1661. Xcap_dir_append(self, args)
  1662. X    capobject *self;
  1663. X    object *args;
  1664. X{
  1665. X    object *name;
  1666. X    capability cap;
  1667. X    errstat err;
  1668. X    if (!getstrcapargs(args, &name, &cap))
  1669. X        return NULL;
  1670. X    err = dir_append(&self->ob_cap, getstringvalue(name), &cap);
  1671. X    if (err != STD_OK)
  1672. X        return amoeba_error(err);
  1673. X    INCREF(None);
  1674. X    return None;
  1675. X}
  1676. X
  1677. Xstatic object *
  1678. Xcap_dir_delete(self, args)
  1679. X    capobject *self;
  1680. X    object *args;
  1681. X{
  1682. X    object *name;
  1683. X    errstat err;
  1684. X    if (!getstrarg(args, &name))
  1685. X        return NULL;
  1686. X    err = dir_delete(&self->ob_cap, getstringvalue(name));
  1687. X    if (err != STD_OK)
  1688. X        return amoeba_error(err);
  1689. X    INCREF(None);
  1690. X    return None;
  1691. X}
  1692. X
  1693. Xstatic object *
  1694. Xcap_dir_replace(self, args)
  1695. X    capobject *self;
  1696. X    object *args;
  1697. X{
  1698. X    object *name;
  1699. X    capability cap;
  1700. X    errstat err;
  1701. X    if (!getstrcapargs(args, &name, &cap))
  1702. X        return NULL;
  1703. X    err = dir_replace(&self->ob_cap, getstringvalue(name), &cap);
  1704. X    if (err != STD_OK)
  1705. X        return amoeba_error(err);
  1706. X    INCREF(None);
  1707. X    return None;
  1708. X}
  1709. X
  1710. Xstatic object *
  1711. Xcap_dir_list(self, args)
  1712. X    capobject *self;
  1713. X    object *args;
  1714. X{
  1715. X    errstat err;
  1716. X    struct dir_open *dd;
  1717. X    object *d;
  1718. X    char *name;
  1719. X    if (!getnoarg(args))
  1720. X        return NULL;
  1721. X    if ((dd = dir_open(&self->ob_cap)) == NULL)
  1722. X        return amoeba_error(STD_COMBAD);
  1723. X    if ((d = newlistobject(0)) == NULL) {
  1724. X        dir_close(dd);
  1725. X        return NULL;
  1726. X    }
  1727. X    while ((name = dir_next(dd)) != NULL) {
  1728. X        object *v;
  1729. X        v = newstringobject(name);
  1730. X        if (v == NULL) {
  1731. X            DECREF(d);
  1732. X            d = NULL;
  1733. X            break;
  1734. X        }
  1735. X        if (addlistitem(d, v) != 0) {
  1736. X            DECREF(v);
  1737. X            DECREF(d);
  1738. X            d = NULL;
  1739. X            break;
  1740. X        }
  1741. X        DECREF(v);
  1742. X    }
  1743. X    dir_close(dd);
  1744. X    return d;
  1745. X}
  1746. X
  1747. Xobject *
  1748. Xcap_std_info(self, args)
  1749. X    capobject *self;
  1750. X    object *args;
  1751. X{
  1752. X    char buf[256];
  1753. X    errstat err;
  1754. X    int n;
  1755. X    if (!getnoarg(args))
  1756. X        return NULL;
  1757. X    err = std_info(&self->ob_cap, buf, sizeof buf, &n);
  1758. X    if (err != STD_OK)
  1759. X        return amoeba_error(err);
  1760. X    return newsizedstringobject(buf, n);
  1761. X}
  1762. X
  1763. Xobject *
  1764. Xcap_tod_gettime(self, args)
  1765. X    capobject *self;
  1766. X    object *args;
  1767. X{
  1768. X    header h;
  1769. X    errstat err;
  1770. X    bufsize n;
  1771. X    long sec;
  1772. X    int msec, tz, dst;
  1773. X    if (!getnoarg(args))
  1774. X        return NULL;
  1775. X    h.h_port = self->ob_cap.cap_port;
  1776. X    h.h_priv = self->ob_cap.cap_priv;
  1777. X    h.h_command = TOD_GETTIME;
  1778. X    n = trans(&h, NILBUF, 0, &h, NILBUF, 0);
  1779. X    if (ERR_STATUS(n))
  1780. X        return amoeba_error(ERR_CONVERT(n));
  1781. X    tod_decode(&h, &sec, &msec, &tz, &dst);
  1782. X    return newintobject(sec);
  1783. X}
  1784. X
  1785. Xobject *
  1786. Xcap_tod_settime(self, args)
  1787. X    capobject *self;
  1788. X    object *args;
  1789. X{
  1790. X    header h;
  1791. X    errstat err;
  1792. X    bufsize n;
  1793. X    long sec;
  1794. X    if (!getlongarg(args, &sec))
  1795. X        return NULL;
  1796. X    h.h_port = self->ob_cap.cap_port;
  1797. X    h.h_priv = self->ob_cap.cap_priv;
  1798. X    h.h_command = TOD_SETTIME;
  1799. X    tod_encode(&h, sec, 0, 0, 0);
  1800. X    n = trans(&h, NILBUF, 0, &h, NILBUF, 0);
  1801. X    if (ERR_STATUS(n))
  1802. X        return amoeba_error(ERR_CONVERT(n));
  1803. X    INCREF(None);
  1804. X    return None;
  1805. X}
  1806. X
  1807. Xstatic struct methodlist cap_methods[] = {
  1808. X    { STUBCODE,        sc_interpreter},
  1809. X    {"b_read",        cap_b_read},
  1810. X    {"b_size",        cap_b_size},
  1811. X    {"dir_append",        cap_dir_append},
  1812. X    {"dir_delete",        cap_dir_delete},
  1813. X    {"dir_list",        cap_dir_list},
  1814. X    {"dir_lookup",        cap_dir_lookup},
  1815. X    {"dir_replace",        cap_dir_replace},
  1816. X    {"std_info",        cap_std_info},
  1817. X    {"tod_gettime",        cap_tod_gettime},
  1818. X    {"tod_settime",        cap_tod_settime},
  1819. X    {NULL,            NULL}             /* Sentinel */
  1820. X};
  1821. EOF
  1822. fi
  1823. if test -s 'src/tokenizer.c'
  1824. then echo '*** I will not over-write existing file src/tokenizer.c'
  1825. else
  1826. echo 'x - src/tokenizer.c'
  1827. sed 's/^X//' > 'src/tokenizer.c' << 'EOF'
  1828. X/***********************************************************
  1829. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  1830. XNetherlands.
  1831. X
  1832. X                        All Rights Reserved
  1833. X
  1834. XPermission to use, copy, modify, and distribute this software and its 
  1835. Xdocumentation for any purpose and without fee is hereby granted, 
  1836. Xprovided that the above copyright notice appear in all copies and that
  1837. Xboth that copyright notice and this permission notice appear in 
  1838. Xsupporting documentation, and that the names of Stichting Mathematisch
  1839. XCentrum or CWI not be used in advertising or publicity pertaining to
  1840. Xdistribution of the software without specific, written prior permission.
  1841. X
  1842. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  1843. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1844. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  1845. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  1846. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  1847. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  1848. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  1849. X
  1850. X******************************************************************/
  1851. X
  1852. X/* Tokenizer implementation */
  1853. X
  1854. X/* XXX This is rather old, should be restructured perhaps */
  1855. X/* XXX Need a better interface to report errors than writing to stderr */
  1856. X/* XXX Should use editor resource to fetch true tab size on Macintosh */
  1857. X
  1858. X#include "pgenheaders.h"
  1859. X
  1860. X#include <ctype.h>
  1861. X#include "string.h"
  1862. X
  1863. X#include "fgetsintr.h"
  1864. X#include "tokenizer.h"
  1865. X#include "errcode.h"
  1866. X
  1867. X#ifdef THINK_C
  1868. X#define TABSIZE 4
  1869. X#endif
  1870. X
  1871. X#ifndef TABSIZE
  1872. X#define TABSIZE 8
  1873. X#endif
  1874. X
  1875. X/* Forward */
  1876. Xstatic struct tok_state *tok_new PROTO((void));
  1877. Xstatic int tok_nextc PROTO((struct tok_state *tok));
  1878. Xstatic void tok_backup PROTO((struct tok_state *tok, int c));
  1879. X
  1880. X/* Token names */
  1881. X
  1882. Xchar *tok_name[] = {
  1883. X    "ENDMARKER",
  1884. X    "NAME",
  1885. X    "NUMBER",
  1886. X    "STRING",
  1887. X    "NEWLINE",
  1888. X    "INDENT",
  1889. X    "DEDENT",
  1890. X    "LPAR",
  1891. X    "RPAR",
  1892. X    "LSQB",
  1893. X    "RSQB",
  1894. X    "COLON",
  1895. X    "COMMA",
  1896. X    "SEMI",
  1897. X    "PLUS",
  1898. X    "MINUS",
  1899. X    "STAR",
  1900. X    "SLASH",
  1901. X    "VBAR",
  1902. X    "AMPER",
  1903. X    "LESS",
  1904. X    "GREATER",
  1905. X    "EQUAL",
  1906. X    "DOT",
  1907. X    "PERCENT",
  1908. X    "BACKQUOTE",
  1909. X    "LBRACE",
  1910. X    "RBRACE",
  1911. X    "OP",
  1912. X    "<ERRORTOKEN>",
  1913. X    "<N_TOKENS>"
  1914. X};
  1915. X
  1916. X
  1917. X/* Create and initialize a new tok_state structure */
  1918. X
  1919. Xstatic struct tok_state *
  1920. Xtok_new()
  1921. X{
  1922. X    struct tok_state *tok = NEW(struct tok_state, 1);
  1923. X    if (tok == NULL)
  1924. X        return NULL;
  1925. X    tok->buf = tok->cur = tok->end = tok->inp = NULL;
  1926. X    tok->done = E_OK;
  1927. X    tok->fp = NULL;
  1928. X    tok->tabsize = TABSIZE;
  1929. X    tok->indent = 0;
  1930. X    tok->indstack[0] = 0;
  1931. X    tok->atbol = 1;
  1932. X    tok->pendin = 0;
  1933. X    tok->prompt = tok->nextprompt = NULL;
  1934. X    tok->lineno = 0;
  1935. X    return tok;
  1936. X}
  1937. X
  1938. X
  1939. X/* Set up tokenizer for string */
  1940. X
  1941. Xstruct tok_state *
  1942. Xtok_setups(str)
  1943. X    char *str;
  1944. X{
  1945. X    struct tok_state *tok = tok_new();
  1946. X    if (tok == NULL)
  1947. X        return NULL;
  1948. X    tok->buf = tok->cur = str;
  1949. X    tok->end = tok->inp = strchr(str, '\0');
  1950. X    return tok;
  1951. X}
  1952. X
  1953. X
  1954. X/* Set up tokenizer for string */
  1955. X
  1956. Xstruct tok_state *
  1957. Xtok_setupf(fp, ps1, ps2)
  1958. X    FILE *fp;
  1959. X    char *ps1, *ps2;
  1960. X{
  1961. X    struct tok_state *tok = tok_new();
  1962. X    if (tok == NULL)
  1963. X        return NULL;
  1964. X    if ((tok->buf = NEW(char, BUFSIZ)) == NULL) {
  1965. X        DEL(tok);
  1966. X        return NULL;
  1967. X    }
  1968. X    tok->cur = tok->inp = tok->buf;
  1969. X    tok->end = tok->buf + BUFSIZ;
  1970. X    tok->fp = fp;
  1971. X    tok->prompt = ps1;
  1972. X    tok->nextprompt = ps2;
  1973. X    return tok;
  1974. X}
  1975. X
  1976. X
  1977. X/* Free a tok_state structure */
  1978. X
  1979. Xvoid
  1980. Xtok_free(tok)
  1981. X    struct tok_state *tok;
  1982. X{
  1983. X    /* XXX really need a separate flag to say 'my buffer' */
  1984. X    if (tok->fp != NULL && tok->buf != NULL)
  1985. X        DEL(tok->buf);
  1986. X    DEL(tok);
  1987. X}
  1988. X
  1989. X
  1990. X/* Get next char, updating state; error code goes into tok->done */
  1991. X
  1992. Xstatic int
  1993. Xtok_nextc(tok)
  1994. X    register struct tok_state *tok;
  1995. X{
  1996. X    if (tok->done != E_OK)
  1997. X        return EOF;
  1998. X    
  1999. X    for (;;) {
  2000. X        if (tok->cur < tok->inp)
  2001. X            return *tok->cur++;
  2002. X        if (tok->fp == NULL) {
  2003. X            tok->done = E_EOF;
  2004. X            return EOF;
  2005. X        }
  2006. X        if (tok->inp > tok->buf && tok->inp[-1] == '\n')
  2007. X            tok->inp = tok->buf;
  2008. X        if (tok->inp == tok->end) {
  2009. X            int n = tok->end - tok->buf;
  2010. X            char *new = tok->buf;
  2011. X            RESIZE(new, char, n+n);
  2012. X            if (new == NULL) {
  2013. X                fprintf(stderr, "tokenizer out of mem\n");
  2014. X                tok->done = E_NOMEM;
  2015. X                return EOF;
  2016. X            }
  2017. X            tok->buf = new;
  2018. X            tok->inp = tok->buf + n;
  2019. X            tok->end = tok->inp + n;
  2020. X        }
  2021. X#ifdef USE_READLINE
  2022. X        if (tok->prompt != NULL) {
  2023. X            extern char *readline PROTO((char *prompt));
  2024. X            static int been_here;
  2025. X            if (!been_here) {
  2026. X                /* Force rebind of TAB to insert-tab */
  2027. X                extern int rl_insert();
  2028. X                rl_bind_key('\t', rl_insert);
  2029. X                been_here++;
  2030. X            }
  2031. X            if (tok->buf != NULL)
  2032. X                free(tok->buf);
  2033. X            tok->buf = readline(tok->prompt);
  2034. X            (void) intrcheck(); /* Clear pending interrupt */
  2035. X            if (tok->nextprompt != NULL)
  2036. X                tok->prompt = tok->nextprompt;
  2037. X                /* XXX different semantics w/o readline()! */
  2038. X            if (tok->buf == NULL) {
  2039. X                tok->done = E_EOF;
  2040. X            }
  2041. X            else {
  2042. X                unsigned int n = strlen(tok->buf);
  2043. X                if (n > 0)
  2044. X                    add_history(tok->buf);
  2045. X                /* Append the '\n' that readline()
  2046. X                   doesn't give us, for the tokenizer... */
  2047. X                tok->buf = realloc(tok->buf, n+2);
  2048. X                if (tok->buf == NULL)
  2049. X                    tok->done = E_NOMEM;
  2050. X                else {
  2051. X                    tok->end = tok->buf + n;
  2052. X                    *tok->end++ = '\n';
  2053. X                    *tok->end = '\0';
  2054. X                    tok->inp = tok->end;
  2055. X                    tok->cur = tok->buf;
  2056. X                }
  2057. X            }
  2058. X        }
  2059. X        else
  2060. X#endif
  2061. X        {
  2062. X            tok->cur = tok->inp;
  2063. X            if (tok->prompt != NULL && tok->inp == tok->buf) {
  2064. X                fprintf(stderr, "%s", tok->prompt);
  2065. X                tok->prompt = tok->nextprompt;
  2066. X            }
  2067. X            tok->done = fgets_intr(tok->inp,
  2068. X                (int)(tok->end - tok->inp), tok->fp);
  2069. X        }
  2070. X        if (tok->done != E_OK) {
  2071. X            if (tok->prompt != NULL)
  2072. X                fprintf(stderr, "\n");
  2073. X            return EOF;
  2074. X        }
  2075. X        tok->inp = strchr(tok->inp, '\0');
  2076. X    }
  2077. X}
  2078. X
  2079. X
  2080. X/* Back-up one character */
  2081. X
  2082. Xstatic void
  2083. Xtok_backup(tok, c)
  2084. X    register struct tok_state *tok;
  2085. X    register int c;
  2086. X{
  2087. X    if (c != EOF) {
  2088. X        if (--tok->cur < tok->buf) {
  2089. X            fprintf(stderr, "tok_backup: begin of buffer\n");
  2090. X            abort();
  2091. X        }
  2092. X        if (*tok->cur != c)
  2093. X            *tok->cur = c;
  2094. X    }
  2095. X}
  2096. X
  2097. X
  2098. X/* Return the token corresponding to a single character */
  2099. X
  2100. Xint
  2101. Xtok_1char(c)
  2102. X    int c;
  2103. X{
  2104. X    switch (c) {
  2105. X    case '(':    return LPAR;
  2106. X    case ')':    return RPAR;
  2107. X    case '[':    return LSQB;
  2108. X    case ']':    return RSQB;
  2109. X    case ':':    return COLON;
  2110. X    case ',':    return COMMA;
  2111. X    case ';':    return SEMI;
  2112. X    case '+':    return PLUS;
  2113. X    case '-':    return MINUS;
  2114. X    case '*':    return STAR;
  2115. X    case '/':    return SLASH;
  2116. X    case '|':    return VBAR;
  2117. X    case '&':    return AMPER;
  2118. X    case '<':    return LESS;
  2119. X    case '>':    return GREATER;
  2120. X    case '=':    return EQUAL;
  2121. X    case '.':    return DOT;
  2122. X    case '%':    return PERCENT;
  2123. X    case '`':    return BACKQUOTE;
  2124. X    case '{':    return LBRACE;
  2125. X    case '}':    return RBRACE;
  2126. X    default:    return OP;
  2127. X    }
  2128. X}
  2129. X
  2130. X
  2131. X/* Get next token, after space stripping etc. */
  2132. X
  2133. Xint
  2134. Xtok_get(tok, p_start, p_end)
  2135. X    register struct tok_state *tok; /* In/out: tokenizer state */
  2136. X    char **p_start, **p_end; /* Out: point to start/end of token */
  2137. X{
  2138. X    register int c;
  2139. X    
  2140. X    /* Get indentation level */
  2141. X    if (tok->atbol) {
  2142. X        register int col = 0;
  2143. X        tok->atbol = 0;
  2144. X        tok->lineno++;
  2145. X        for (;;) {
  2146. X            c = tok_nextc(tok);
  2147. X            if (c == ' ')
  2148. X                col++;
  2149. X            else if (c == '\t')
  2150. X                col = (col/tok->tabsize + 1) * tok->tabsize;
  2151. X            else
  2152. X                break;
  2153. X        }
  2154. X        tok_backup(tok, c);
  2155. X        if (col == tok->indstack[tok->indent]) {
  2156. X            /* No change */
  2157. X        }
  2158. X        else if (col > tok->indstack[tok->indent]) {
  2159. X            /* Indent -- always one */
  2160. X            if (tok->indent+1 >= MAXINDENT) {
  2161. X                fprintf(stderr, "excessive indent\n");
  2162. X                tok->done = E_TOKEN;
  2163. X                return ERRORTOKEN;
  2164. X            }
  2165. X            tok->pendin++;
  2166. X            tok->indstack[++tok->indent] = col;
  2167. X        }
  2168. X        else /* col < tok->indstack[tok->indent] */ {
  2169. X            /* Dedent -- any number, must be consistent */
  2170. X            while (tok->indent > 0 &&
  2171. X                col < tok->indstack[tok->indent]) {
  2172. X                tok->indent--;
  2173. X                tok->pendin--;
  2174. X            }
  2175. X            if (col != tok->indstack[tok->indent]) {
  2176. X                fprintf(stderr, "inconsistent dedent\n");
  2177. X                tok->done = E_TOKEN;
  2178. X                return ERRORTOKEN;
  2179. X            }
  2180. X        }
  2181. X    }
  2182. X    
  2183. X    *p_start = *p_end = tok->cur;
  2184. X    
  2185. X    /* Return pending indents/dedents */
  2186. X    if (tok->pendin != 0) {
  2187. X        if (tok->pendin < 0) {
  2188. X            tok->pendin++;
  2189. X            return DEDENT;
  2190. X        }
  2191. X        else {
  2192. X            tok->pendin--;
  2193. X            return INDENT;
  2194. X        }
  2195. X    }
  2196. X    
  2197. X again:
  2198. X    /* Skip spaces */
  2199. X    do {
  2200. X        c = tok_nextc(tok);
  2201. X    } while (c == ' ' || c == '\t');
  2202. X    
  2203. X    /* Set start of current token */
  2204. X    *p_start = tok->cur - 1;
  2205. X    
  2206. X    /* Skip comment */
  2207. X    if (c == '#') {
  2208. X        /* Hack to allow overriding the tabsize in the file.
  2209. X           This is also recognized by vi, when it occurs near the
  2210. X           beginning or end of the file.  (Will vi never die...?) */
  2211. X        int x;
  2212. X        /* XXX The case to (unsigned char *) is needed by THINK C 3.0 */
  2213. X        if (sscanf(/*(unsigned char *)*/tok->cur,
  2214. X                " vi:set tabsize=%d:", &x) == 1 &&
  2215. X                        x >= 1 && x <= 40) {
  2216. X            fprintf(stderr, "# vi:set tabsize=%d:\n", x);
  2217. X            tok->tabsize = x;
  2218. X        }
  2219. X        do {
  2220. X            c = tok_nextc(tok);
  2221. X        } while (c != EOF && c != '\n');
  2222. X    }
  2223. X    
  2224. X    /* Check for EOF and errors now */
  2225. X    if (c == EOF)
  2226. X        return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN;
  2227. X    
  2228. X    /* Identifier (most frequent token!) */
  2229. X    if (isalpha(c) || c == '_') {
  2230. X        do {
  2231. X            c = tok_nextc(tok);
  2232. X        } while (isalnum(c) || c == '_');
  2233. X        tok_backup(tok, c);
  2234. X        *p_end = tok->cur;
  2235. X        return NAME;
  2236. X    }
  2237. X    
  2238. X    /* Newline */
  2239. X    if (c == '\n') {
  2240. X        tok->atbol = 1;
  2241. X        *p_end = tok->cur - 1; /* Leave '\n' out of the string */
  2242. X        return NEWLINE;
  2243. X    }
  2244. X    
  2245. X    /* Number */
  2246. X    if (isdigit(c)) {
  2247. X        if (c == '0') {
  2248. X            /* Hex or octal */
  2249. X            c = tok_nextc(tok);
  2250. X            if (c == '.')
  2251. X                goto fraction;
  2252. X            if (c == 'x' || c == 'X') {
  2253. X                /* Hex */
  2254. X                do {
  2255. X                    c = tok_nextc(tok);
  2256. X                } while (isxdigit(c));
  2257. X            }
  2258. X            else {
  2259. X                /* Octal; c is first char of it */
  2260. X                /* There's no 'isoctdigit' macro, sigh */
  2261. X                while ('0' <= c && c < '8') {
  2262. X                    c = tok_nextc(tok);
  2263. X                }
  2264. X            }
  2265. X        }
  2266. X        else {
  2267. X            /* Decimal */
  2268. X            do {
  2269. X                c = tok_nextc(tok);
  2270. X            } while (isdigit(c));
  2271. X            /* Accept floating point numbers.
  2272. X               XXX This accepts incomplete things like 12e or 1e+;
  2273. X                   worry about that at run-time.
  2274. X               XXX Doesn't accept numbers starting with a dot */
  2275. X            if (c == '.') {
  2276. X    fraction:
  2277. X                /* Fraction */
  2278. X                do {
  2279. X                    c = tok_nextc(tok);
  2280. X                } while (isdigit(c));
  2281. X            }
  2282. X            if (c == 'e' || c == 'E') {
  2283. X                /* Exponent part */
  2284. X                c = tok_nextc(tok);
  2285. X                if (c == '+' || c == '-')
  2286. X                    c = tok_nextc(tok);
  2287. X                while (isdigit(c)) {
  2288. X                    c = tok_nextc(tok);
  2289. X                }
  2290. X            }
  2291. X        }
  2292. X        tok_backup(tok, c);
  2293. X        *p_end = tok->cur;
  2294. X        return NUMBER;
  2295. X    }
  2296. X    
  2297. X    /* String */
  2298. X    if (c == '\'') {
  2299. X        for (;;) {
  2300. X            c = tok_nextc(tok);
  2301. X            if (c == '\n' || c == EOF) {
  2302. X                tok->done = E_TOKEN;
  2303. X                return ERRORTOKEN;
  2304. X            }
  2305. X            if (c == '\\') {
  2306. X                c = tok_nextc(tok);
  2307. X                *p_end = tok->cur;
  2308. X                if (c == '\n' || c == EOF) {
  2309. X                    tok->done = E_TOKEN;
  2310. X                    return ERRORTOKEN;
  2311. X                }
  2312. X                continue;
  2313. X            }
  2314. X            if (c == '\'')
  2315. X                break;
  2316. X        }
  2317. X        *p_end = tok->cur;
  2318. X        return STRING;
  2319. X    }
  2320. X    
  2321. X    /* Line continuation */
  2322. X    if (c == '\\') {
  2323. X        c = tok_nextc(tok);
  2324. X        if (c != '\n') {
  2325. X            tok->done = E_TOKEN;
  2326. X            return ERRORTOKEN;
  2327. X        }
  2328. X        tok->lineno++;
  2329. X        goto again; /* Read next line */
  2330. X    }
  2331. X    
  2332. X    /* Punctuation character */
  2333. X    *p_end = tok->cur;
  2334. X    return tok_1char(c);
  2335. X}
  2336. X
  2337. X
  2338. X#ifdef DEBUG
  2339. X
  2340. Xvoid
  2341. Xtok_dump(type, start, end)
  2342. X    int type;
  2343. X    char *start, *end;
  2344. X{
  2345. X    printf("%s", tok_name[type]);
  2346. X    if (type == NAME || type == NUMBER || type == STRING || type == OP)
  2347. X        printf("(%.*s)", (int)(end - start), start);
  2348. X}
  2349. X
  2350. X#endif
  2351. EOF
  2352. fi
  2353. echo 'Part 08 out of 21 of pack.out complete.'
  2354. exit 0
  2355.