home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 2 / 2800 (.txt) < prev    next >
LaTeX Document  |  1991-02-19  |  62KB

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