home *** CD-ROM | disk | FTP | other *** search
/ Simtel MSDOS - Coast to Coast / simteldosarchivecoasttocoast2.iso / xlisp / xl21freq.zip / XLISPINS.DOC < prev   
Text File  |  1993-12-17  |  40KB  |  943 lines

  1. I've just finished reading the xlisp 2.1 source code for the first
  2. time.  The tutorial and reference material included with the winterp
  3. distribution are well done, but I would have liked an overview of the
  4. interpreter internals.  Here's a first cut at such a document.
  5. Comments welcome...
  6.  
  7. Jeff Prothero
  8.  
  9. I've modified Jeff's overview to match current XLISP-PLUS 2.1f
  10. practice, and describe initialization and save/restore.
  11.  
  12. Tom Almy
  13.  
  14.  
  15. ---------------------------cut here-------------------------------
  16.  
  17. 90Nov13 jsp@milton.u.washington.edu       Public Domain.
  18.  
  19.                    +---------------------+
  20.                    | xlisp 2.1 internals |
  21.                    +---------------------+
  22.  
  23.  
  24.  Who should read this?
  25.  ---------------------
  26.  
  27. Anyone poking through the C implementation of xlisp for the first
  28. time.  This is intended to provide a rough roadmap of the global
  29. xlisp structures and algorithms.  If you just want to write lisp code
  30. in xlisp, you don't need to read this file -- go read cldoc.txt.  If
  31. you want to tinker with the xlisp implementation code, you should
  32. *still* read that before reading this.  The following isn't intended
  33. to be exhaustively precise -- that's what the source code is for!  It
  34. is intended only to give you sufficient orientation give you a
  35. fighting chance to understand the code the first time through,
  36. instead of the third time.
  37.  
  38. At the bottom of the file you'll find an example of how to add new
  39. primitive functions to xlisp.
  40.  
  41.  
  42.  
  43.  General note on MS-DOS Memory Models
  44.  ------------------------------------
  45.  
  46. If you are not using MS-DOS ignore all the "FAR" and "NEAR" keywords.
  47. Also ignore MEDMEM, and most uppercase macros default to the lowercase
  48. library functions.
  49.  
  50. For MS-DOS, originally XLISP used Large memory model. However in
  51. order to allow for a clean MS Windows port (never completed :-() and
  52. to improve performance, the code was overhauled to use Medium memory
  53. model. Every xlisp object is is allocated from FAR memory, so
  54. pointers need to be cast to FAR. Local variables, and statically
  55. allocated global variables are NEAR, however. Since FAR strings cannot be
  56. handled by Medium model library string routines, they must be moded
  57. into a NEAR buffer first.
  58.  
  59.  
  60.  Other added confusions
  61.  ______________________
  62.  
  63.  
  64. There are two separate sets of memory allocation/garbage collection
  65. routines. One pair, xldmem/xlimage, was the traditional xlisp
  66. allocator. The second pair, dldmem/dlimage, additionally manages
  67. arrays and strings. In the original version, malloc and free are
  68. used, which can cause memory fragmentation problems. The dl pair 
  69. compresses array memory segments to eliminate fragmentation.
  70.  
  71. There are many compilation options. Thank goodness many more have
  72. been eliminated.
  73.  
  74.  
  75.  What is an LVAL?
  76.  ----------------
  77.  
  78. An "LVAL" is the C type for a generic pointer to an xlisp
  79. garbage-collectable something.  (Cons cell, object, string, closure,
  80. symbol, vector, whatever.)  Virtually every variable in the
  81. interpreter is an LVAL.  Cons cells contain two LVAL slots,
  82. symbols contains four LVAL slots, etc.
  83.  
  84.  
  85.  
  86.  What is the obarray?
  87.  --------------------
  88.  
  89. The obarray is the xlisp symbol table.  More precisely, it is is a
  90. hashtable mapping ascii strings (symbol names) to symbols.  ("obarray"
  91. is a misnomer, since it contains only xlisp SYMBOLs, and in particular
  92. contains no xlisp OBJECTs.)  It is used when converting lisp
  93. expressions from text to internal form. Since it is a root for the
  94. garbage collector, it also serves to distinguish permanent
  95. global-variable symbols from other symbols -- you can permanently
  96. protect a symbol from the garbage collector by entering it into the
  97. obarray.  This is called "interning" the symbol.  The obarray is
  98. called "obarray" in C and "*OBARRAY*" in xlisp.
  99.  
  100. When the package facility is compiled, *OBARRAY* no longer exists,
  101. and obarray is a list of packages. A package is a structure (an
  102. array) of six elements. The first is an obarray for the internal
  103. symbols in the package, the second is an obarry for the external
  104. symbols, the third is a list of shadowing symbols, the fourth is a
  105. list of packages this package uses, the fifth is a list of packages
  106. which use this package, and the sixth is a list of the package's
  107. names with all but the first being the nicknames. In addition,
  108. symbols have an additional attribute in their structure which is the
  109. home package of the symbol.
  110.  
  111.  
  112.  The Interpreter Stacks
  113.  ----------------------
  114.  
  115. xlisp uses two stacks, an "evaluation stack" and an "argument stack".
  116. Both are roots for the garbage collector.  The evaluation stack is
  117. largely private to the interpreter and protects internal values from
  118. garbage collection, while the argument stack holds the conventional
  119. user-visible stackframes.
  120.  
  121.  
  122. The evaluation stack is an EDEPTH-long array of "LVAL" statically
  123. allocated.  It grows zeroward.
  124.  
  125. xlstkbase points to the zero-near end of the evaluation stack.
  126.  
  127. xlstktop points to the zero-far end of the evaluation stack: the
  128. occupied part of the stack lies between xlstack and xlstktop.  NOTE
  129. that xlstktop is *NOT* the top of the stack in the conventional sense
  130. of indicating the most recent entry on the stack: xlstktop is a static
  131. bounds pointer which never changes.
  132.  
  133. xlstack starts at the zero-far end of the evaluation stack.  *xlstack
  134. is the most recent LVAL on the stack.  The garbage collector MARKs
  135. everything reachable from the evaluation stack (among other things),
  136. so we frequently push things on this stack while C code is
  137. manipulating them. (Via xlsave(), xlprotect(), xlsave1(), xlprot1().)
  138.  
  139.  
  140. The argument stack is an ADEPTH-long array of "LVAL".  It also grows
  141. zeroward.  The evaluator pushes arguments on the argument stack at the
  142. start of a function call (form evaluation).  Built-in functions
  143. usually eat them directly off the stack.  For user-lisp functions
  144. xleval.c:evfun() pops them off the stack and binds them to the
  145. appropriate symbols before beginning execution of the function body
  146. proper.
  147.  
  148. xlargstkbase is the zero-near end of argument stack.
  149. xlargstktop is the zero-far end of argument stack.  Like xlstktop,
  150. xlargstktop is a static bounds pointer.
  151.  
  152. *xlsp ("sp"=="stack pointer") is the most recent item on the argument stack.
  153.  
  154. xlfp ("fp"=="frame pointer") is the base of the current stackframe.
  155.  
  156.  
  157.  
  158.   What is a context?
  159.   ------------------
  160.  
  161. An xlisp "context" is something like a checkpoint, recording a
  162. particular point buried in the execution history so that we can
  163. abort/return back to it.  Contexts are used to implement call/return,
  164. catch/throw, signals, gotos, and breaks.  xlcontext points to the
  165. chain of active contexts, the top one being the second-newest active
  166. context.  (The newest -- that is, current -- active context is
  167. implemented by the variables xlstack xlenv xlfenv xldenv xlcontext
  168. xlargv xlargc xlfp xlsp.)  Context records are written by
  169. xljump.c:xlbegin() and read by xljump.c:xljump().  Context records are
  170. C structures on the C program stack; They are not in the dynamic
  171. memory pool or on the lisp execution or argument stacks.
  172.  
  173.  
  174.  
  175.   What is an environment?
  176.   -----------------------
  177.  
  178. An environment is basically a store of symbol-value pairs, used to
  179. resolve variable references by the lisp program.  xlisp maintains
  180. three environments, in the global variables xlenv, xlfenv and xldenv.
  181.  
  182. xlenv and xlfenv are linked-list stacks which are pushed when we
  183. enter a function and popped when we exit it.  We also switch
  184. xlenv+xlfenf environments entirely when we begin executing a new
  185. closure (user-fn written in lisp). The xlenv environment is enlarged
  186. during a LET function (or other special form with value bindings),
  187. while the xlfenv environment is enlarged with FLET/MACROLET/LABELS.
  188.  
  189. The xlenv environment is the most heavily used environment.  It is
  190. used to resolve everyday data references to local variables.  It
  191. consists of a list of frames (and objects).  Each frame is a list of
  192. sym-val pairs.  In the case of an object, we check all the instance
  193. and class variables of the object, then do the same for its
  194. superclass, until we run out of superclasses. If the symbol is not
  195. found it has not been bound and its global value is used.
  196.  
  197. The xlfenv environment is used to find function values instead of
  198. variable values. 
  199.  
  200. When we send a message, we set xlenv to the value it had when the
  201. message CLOSURE was built, then push on (obj msg-class), where
  202. msg-class is the [super]class defining the method.  (We also set
  203. xlfenv to the value xlfenv had when the method was built.)  This makes
  204. the object instance variables part of the environment, and saves the
  205. information needed to correctly resolve references to class variables,
  206. and to implement SEND-SUPER.
  207.  
  208. The xldenv environment tracks the old values of global variables
  209. which we have changed but intend to restore later to their original
  210. values, particularly for variables (symbols) marked as F_SPECIAL, but
  211. also for progv. This is also used internally when we bind and unbind
  212. s_evalhook and s_applyhook (*EVALHOOK* and *APPLYHOOK*). It is a
  213. simple list of sym-val pairs, treated as a stack.
  214.  
  215. These environments are manipulated in C via the xlisp.h macros
  216. xlframe(e), xlbind(s,v), xlfbind(s,v), xlpbind(s,v,e), xldbind(s,v),
  217. xlunbind(e).
  218.  
  219.  
  220.   How are multiple return values handled?
  221.   ---------------------------------------
  222.  
  223. The first value is always returned via the C function mechanism.
  224. All return values are passed back in an array xlresults[]. The
  225. number of return values are specified in xlnumresults. In order to
  226. avoid having to repeat the multiple value code in every function, a
  227. flag in the SUBR or FSUBR cell indicates if multiple values are used,
  228. and code in xleval.c mimics multiple value functions for single value
  229. functions. The function VALUES, defined in xvalues() allows closures
  230. to return multiple values.
  231.  
  232.  
  233.   How are xlisp entities stored and identified?
  234.   ---------------------------------------------
  235.  
  236. Conceptually, xlisp manages memory as a single array of fixed-size
  237. objects.  Keeping all objects the same size simplifies memory
  238. management enormously, since any object can be allocated anywhere, and
  239. complex compacting schemes aren't needed.  Every LVAL pointer points
  240. somewhere in this array.  Every xlisp object has the basic format
  241. (xldmem.h:typdef struct node)
  242.  
  243.  struct node {
  244.      char n_type;
  245.      char n_flags;
  246.      LVAL car;
  247.      LVAL cdr;
  248.  }
  249.  
  250. where n_type is one of:
  251.  
  252.  FREE     A node on the freelist.
  253.  SUBR     A function implemented in C. (Needs evalutated arguments.)
  254.  FSUBR    A special function implemented in C. (Needs unevaluated arguments).
  255.  CONS     A regular lisp cons cell.
  256.  FIXNUM   An integer.
  257.  FLONUM   A floating-point number.
  258.  STRING   A string.
  259.  STREAM   An input or output file.
  260.  CHAR      An ascii character.
  261.  USTREAM  An internal stream.
  262.  RATIO    A ratio.
  263.  SYMBOL   A symbol.
  264.  OBJECT   Any object, including class objects.
  265.  VECTOR      A variable-size array of LVALs.
  266.  CLOSURE  Result of DEFUN or LAMBDA -- a function written in lisp.
  267.  STRUCT      A structure.
  268.  COMPLEX  A complex number
  269.  PACKAGE  A package
  270.  
  271. Messages may be sent only to nodes with n_type == OBJECT.
  272.  
  273. Obviously, several of the above types won't fit in a fixed-size
  274. two-slot node.  The escape is to have them malloc() some memory and
  275. have one of the slots point to it -- VECTOR is the archetype.  For
  276. example, see xldmem.c:newvector().  To some extent, this malloc()
  277. hack simply exports the memory- fragmentation problem to the C
  278. malloc()/free() routines.  However, it helps keep xlisp simple, and
  279. it has the happy side-effect of unpinning the body of the vector, so
  280. that vectors can easily be expanded and contracted.  When the
  281. dldmem.c version of the memory manager is used, this memory is
  282. managed by xlisp.
  283.  
  284. The garbage collector has special-case code for each of the above node
  285. types, so it can find all LVAL slots and recycle any malloc()ed ram
  286. when a node is garbage-collected. If the collected node is a STREAM,
  287. then it's associated file is closed.
  288.  
  289. Xlisp pre-allocates nodes for all ascii characters, and for small
  290. integers.  These nodes are never garbage-collected.
  291.  
  292. As a practical matter, allocating all nodes in a single array is not
  293. very sensible.  Instead, nodes are allocated as needed, in segments of
  294. one or two thousand nodes, and the segments linked by a pointer chain
  295. rooted at xldmem.c:segs.
  296.  
  297.  
  298.  
  299.   How are vectors implemented?
  300.   ----------------------------
  301.  
  302. An xlisp vector is a generic array of LVAL slots.  Vectors are also
  303. the canonical illustration of xlisp's escape mechanism for node types
  304. which need more than two LVAL slots (the maximum possible in the
  305. fixed-size nodes in the dynamic memory pool).  The node CAR/CDR slots
  306. for a vector hold a size field plus a pointer to a malloc()ed ram
  307. chunk, which is automatically free()ed when the vector is
  308. garbage-collected.
  309.  
  310. xldmem.h defines macros for reading and writing vector fields and
  311. slots: getsize(), getelement() and setelement().  It also defines
  312. macros for accessing each of the other types of xlisp nodes.
  313.  
  314.  
  315.  
  316.   How are strings implemented?
  317.   ---------------------------- 
  318.  
  319. Strings work much like vectors: The node has a pointer to a malloc()ed
  320. ram chunk which is automatically free()ed when the string gets
  321. garbage-collected.
  322.  
  323.  
  324.  
  325.  How are symbols implemented?
  326.  ----------------------------
  327.  
  328. A symbol is a generic user-visible lisp variable, with separate slots
  329. for print name, value, function, and property list.  Any or all of
  330. these slots (including name) may be NIL.  You create a symbol in C by
  331. calling "xlmakesym(name)" or "xlenter(name)" (to make a symbol and
  332. enter it in the obarray). You create a symbol in xlisp with the READ
  333. function, or by calling "(gensym)", or indirectly in various ways.
  334. Most of the symbol-specific code in the interpreter is in xlsym.c.
  335.  
  336. Physically, a symbol is implemented like a four- or five-slot vector.
  337. A couple of free bits in the node structure are used as flags for
  338. F_SPECIAL (special variables) and F_CONSTANT (constants).
  339.  
  340. A symbol is marked as unbound (no value) or undefined (no function)
  341. by placing a pointer to symbol s_unbound in the value or function
  342. field, respectively. The symbol s_unbound is not interned and is not
  343. used other than to set and check for unbound variables and undefined
  344. functions.
  345.  
  346. The symbol NIL is statically allocated so its address is a constant.
  347. This makes the frequent comparision of a pointer to NIL faster and
  348. more compact (in some cases).
  349.  
  350. Random musing: Abstractly, the LISP symbols plus cons cells (etc)
  351. constitute a single directed graph, and the symbols mark spots where
  352. normal recursive evaluation should stop.  Normal lisp programming
  353. practice is to have a symbol in every cycle in the graph, so that
  354. recursive traversal can be done without MARK bits.
  355.  
  356.  
  357.  
  358.   How are closures implemented?
  359.   -----------------------------
  360.  
  361. A closure, the return value from a lambda, is a regular coded-in-lisp
  362. fn.  Physically, it it implemented like an eleven-slot vector, with the
  363. node n_type field hacked to contain CLOSURE instead of VECTOR. The
  364. vector slots contain:
  365.  
  366.  name   symbol -- 1st arg of DEFUN.  NIL for LAMBDA closures.
  367.  type   (s_lambda or s_macro).
  368.  args   List of "required" formal arguments (as symbols)
  369.  oargs  List of "optional" args, each like: (name (default specified-p))
  370.  rest   Name of "&rest" formal arg, else NIL.
  371.  kargs  keyword args, each like: ((':foo 'bar default specified-p))
  372.  aargs  &aux vars, each like: (('arg default))
  373.  body   actual code (as lisp list) for fn.
  374.  env    value of xlenv when the closure was built.  NIL for macros.
  375.  fenv   value of xlfenv when the closure was built. NIL for macros.
  376.  lambda The original formal args list in the defining form.
  377.  
  378. The lambda field is for printout purposes.  The remaining fields store
  379. a predigested version of the formal args list.  This is a limited form
  380. of compilation: by processing the args list at closure-creation time,
  381. we reduce the work needed during calls to the closure.
  382.  
  383.  
  384.  
  385.   How are objects implemented?
  386.   ----------------------------
  387.  
  388. An object is implemented like a vector, with the size determined by
  389. the number of instance variables.  The first slot in the vector points
  390. to the class of the object; the remaining slots hold the instance
  391. variables for the object.  An object needs enough slots to hold all
  392. the instance variables defined by its class, *plus* all the instance
  393. variables defined by all of its superclasses.
  394.  
  395.  
  396.  
  397.   How are classes implemented?
  398.   ----------------------------
  399.  
  400. A class is a specific kind of object, hence has a class pointer plus
  401. instance variables.  All classes have the following instance variables:
  402.  
  403.  MESSAGES   A list of (interned-symbol method-closure) pairs.
  404.  IVARS        Instance variable names: A list of interned symbols.
  405.  CVARS      Class variable names:    A list of interned symbols.
  406.  CVALS      Class variable values:   A vector of values.
  407.  SUPERCLASS A pointer to the superclass.
  408.  IVARCNT    Number of class instance variables, as a fixnum.
  409.  IVARTOTAL  Total number of instance variables, as a fixnum.
  410.  PNAME      Printname for this class
  411.  
  412. IVARCNT is the count of the number of instance variables defined by
  413. our class.  IVARTOTAL is the total number of instance variables in an
  414. object of this class -- IVARCNT for this class plus the IVARCNTs from
  415. all of our superclasses.
  416.  
  417.  
  418.  
  419.  
  420.   How is the class hierarchy laid out?
  421.   ------------------------------------
  422.  
  423. The fundamental objects are the OBJECT and CLASS class objects.  (Both
  424. are instances of class CLASS, and since CLASSes are a particular kind
  425. of OBJECT, both are also objects, with n_type==OBJECT.  Bear with me!)
  426.  
  427. OBJECT is the root of the class hierarchy: everything you can send a
  428. message to is of type OBJECT.  (Vectors, chars, integers and so forth
  429. stand outside the object hierarchy -- you can't send messages to them.
  430. I'm not sure why Dave did it this way.) OBJECT defines the messages:
  431.  
  432.  :isnew -- Does nothing
  433.  :class -- Returns contents of class-pointer slot.
  434.  :show  -- Prints names of obj, obj->class and instance vars (for debugging).
  435.  :prin1 -- print the object to argument stream
  436.  
  437. A CLASS is a specialized type of OBJECT (with instance variables like
  438. MESSAGES which generic OBJECTs lack), class CLASS hence has class
  439. OBJECT as its superclass.  The CLASS object defines the messages:
  440.  
  441.  :new     -- Create new object with self.IVARTOTAL LVAR slots, plus
  442.             one for the class pointer. Point class slot to self.
  443.             Set new.n_type char to OBJECT.
  444.  :isnew     -- Fill in IVARS, CVARS, CVALS, SUPERCLASS, IVARCNT and
  445.             IVARTOTAL, using parameters from :new call.  (The
  446.             :isnew msg inherits the :new msg parameters because
  447.             the  :isnew msg is generated automatically after
  448.             each :new   msg, courtesy of a special hack in
  449.             xlobj.c:sendmsg().)
  450.  :answer -- Add a (msg closure) pair to self.MESSAGES.
  451.  
  452.  
  453.  
  454. Here's a figure to summarize the above, with a generic object thrown
  455. in for good measure.  Note that all instances of CLASS will have a
  456. SUPERCLASS pointer, but no non-class object will.  Note also that the
  457. messages known to an object are those which can be reached by
  458. following exactly one Class Ptr and then zero or more Superclass Ptrs.
  459. For example, the generic object can respond to :ISNEW, :CLASS and
  460. :SHOW, but not to :NEW or :ANSWER.  (The functions implementing the
  461. given messages are shown in parentheses.)
  462.  
  463.                     NIL
  464.                      ^
  465.                      |
  466.                      |Superclass Ptr
  467.                      |
  468.                 Msg+--------+
  469.  :isnew (xlobj.c:obisnew) <----|  class |Class Ptr
  470.  :class (xlobj.c:obclass) <----| OBJECT |------------+
  471.  :show    (xlobj.c:objshow) <----|        |            |
  472.                    +--------+            |
  473.        +---------+                ^  ^               |
  474.        | generic |Class Ptr       |  |               |
  475.        | object  |----------------+  |Superclass Ptr |
  476.        +---------+             |               |
  477.                 Msg+--------+            |
  478.  :isnew    (xlobj.c:clnew)      <----| class  |Class Ptr   |
  479.  :new    (xlobj.c:clisnew) <----| CLASS  |--------+   |
  480.  :answer(xlobj.c:clanswer)<----|        |        |   |
  481.                    +--------+        |   |
  482.                   ^  ^           |   |
  483.                   |  |           |   |
  484.                   |  +-----------+   |
  485.                   +------------------+
  486.  
  487.  
  488. Thus, class CLASS inherits the :CLASS and :SHOW messages from class
  489. OBJECT, overrides the default :ISNEW message, and provides new the
  490. messages :NEW and :ANSWER.
  491.  
  492. New classes are created by (send CLASS :NEW ...) messages.  Their
  493. Class Ptr will point to CLASS.  By default, they will have OBJECT as
  494. their superclass, but this can be overridden by the second optional
  495. argument to :NEW.
  496.  
  497. The above basic structure is set up by xlobj.c:xloinit().
  498.  
  499.  
  500.  
  501.   How do we look up the value of a variable?
  502.   ------------------------------------------
  503.  
  504. When we're cruising along evaluating an expression and encounter a
  505. symbol, the symbol might refer to a global variable, an instance
  506. variable, or a class variable in any of our superclasses.  Figuring
  507. out which means digging throught the environment.  The canonical place
  508. this happens is in xleval.c:xleval(), which simply passes the buck to
  509. xlsym.c:xlgetvalue(), which in turn passes the buck to
  510. xlxsym.c:xlxgetvalue(), where the fun of scanning down xlenv begins.
  511. The xlenv environment looks something like
  512.  
  513.      Backbone    Environment frame contents
  514.      --------    --------------------------
  515. xlenv --> frame      ((sym val) (sym val) (sym val) ... )
  516.       frame      ...
  517.       object     (obj msg-class)
  518.       frame      ...
  519.       object     ...
  520.       frame      ...
  521.       ...
  522.  
  523. The "frame" lines are due to everyday nested constructs like LET
  524. expressions, while the "object" lines represent an object environment
  525. entered via a message send.  xlxgetvalue scans the enviroment left to
  526. right, and then top to bottom.  It scans down the regular environment
  527. frames itself, and calls xlobj.c:xlobjgetvalue() to search the object
  528. environment frames.
  529.  
  530. xlobjgetvalue() first searches for the symbol in the msg-class, then
  531. in all the successive superclasses of msg-class.  In each class, it
  532. first checks the list of instance-variable names in the IVARS slot,
  533. then the list of class-variables name in the CVARS slot.
  534.  
  535.   
  536.  
  537.   How are function calls implemented?
  538.   -----------------------------------
  539.  
  540. xleval.c contains the central expression-evaluation code.
  541. xleval.c:xleval() is the standard top-level entrypoint.  The two
  542. central functions are xleval.c:xlevform() and xleval.c:evfun().
  543. xlevform() can evaluate four kinds of expression nodes:
  544.  
  545. SUBR: A normal primitive fn coded in C.  We call evpushargs() to
  546. evaluate and push the arguments, then call the primitive.
  547.  
  548. FSUBR: A special primitive fn coded in C, which (like IF) wants its
  549. arguments unevaluated.  We call pushargs() (instead of evpushargs())
  550. and then the C fn.
  551.  
  552. CLOSURE: A preprocessed written-in-lisp fn from a DEFUN or LAMBDA.  We
  553. call evpushargs() and then evfun().
  554.  
  555. CONS: We issue an error if it isn't a LAMBDA, otherwise we call
  556. xleval.c:xlclose() to build a CLOSURE from the LAMBDA, and fall into
  557. the CLOSURE code.
  558.  
  559. The common thread in all the above cases is that we call evpushargs()
  560. or pushargs() to push all the arguments on the evaluation stack,
  561. leaving the number and location of the arguments in the global
  562. variables xlargc and xlargv.  The primitive C functions consume
  563. their arguments directly from the argument stack.
  564.  
  565. xleval.c:evfun() evaluates a CLOSURE by:
  566.  
  567. (1) Switching xlenv and xlfenv to the values they had when
  568. the CLOSURE was built. (These values are recorded in the CLOSURE.)
  569.  
  570. (2) Binding the arguments to the environment.  This involves scanning
  571. through the section of the argument stack indicated by xlargc/xlargv,
  572. using information from the CLOSURE to resolve keyword arguments
  573. correctly and assign appropriate default values to optional arguments,
  574. among other things.
  575.  
  576. (3) Evaluating the body of the function via xleval.c:xleval().
  577.  
  578. (4) Cleaning up and restoring the original environment.
  579.  
  580.  
  581.  
  582.   How are message-sends implemented?
  583.   ----------------------------------
  584.  
  585. We scan the MESSAGES list in the CLASS object of the recipient,
  586. looking for a (message-symbol method) pair that matches our message
  587. symbol.  If necessary, we scan the MESSAGES lists of the recipients
  588. superclasses too.  (xlobj.c:sendmsg().)  Once we find it, we basically
  589. do a normal function evaluation. (xlobjl.c:evmethod().)  Two oddities:
  590. We need to replace the message-symbol by the recipient on the argument
  591. stack to make things look normal, and we need to push an 'object'
  592. stack entry on the xlenv environment so we remember which class is
  593. handling the message.
  594.  
  595.  
  596.  
  597.   How is garbage collection implemented?
  598.   --------------------------------------
  599.  
  600. The dynamic memory pool managed by xlisp consists of a chain of memory
  601. *segments* rooted at global C variable "segs".  Each segment contains
  602. an array of "struct node"s plus a pointer to the next segment.  Each
  603. node contains a n_type field and a MARK bit, which is zero except
  604. during garbage collection.
  605.  
  606. Xlisp uses a simple, classical mark-and-sweep garbage collector.  When
  607. it runs out of memory (fnodes==NIL), it does a recursive traversal
  608. setting the MARK flag on all nodes reachable from the obarray, the
  609. three environments xlenv/xlfenv/xldenv, and the evaluation and
  610. argument stacks.  (A "switch" on the n_type field tells us how to find
  611. all the LVAL slots in the node (plus associated storage), and a
  612. pointer-reversal trick lets us avoid using too much stack space during
  613. the traversal.)  sweep() then adds all un-MARKed LVALs to fnodes, and
  614. clears the MARK bit on the remaining nodes.  If this fails to produce
  615. enough free nodes, a new segment is malloc()ed.
  616.  
  617. The code to do this stuff is mostly in xldmem.c.
  618.  
  619.  
  620. How is garbage collection of vectors/strings implemented?
  621. ---------------------------------------------------------
  622.  
  623. In the dldmem.c version, vector/string space is allocated from a
  624. memory pool maintained by xlisp, rather than relying on the C libary
  625. malloc() and free() functions. The pool is a linked list of VSEGMENT
  626. with the root vsegments.
  627.  
  628. When no free memory of a size necessary for an allocation request is
  629. available, a garbage collection is performed. If there is still no
  630. available memory, then a new vector segment is allocated.
  631.  
  632. The garbage collection process compacts the memory in each vector
  633. segment. This is an easy process because each allocated vector area
  634. is pointed to by only one location (in an LVAL), and a backpointer is
  635. maintained from the vector segment to the LVAL. Empty vector segments
  636. are returned to the heap using free() if there greater than 50% of
  637. the vector space is free. This is done to reduce thrashing while
  638. making memory available for allocation to LVALs.
  639.  
  640.  
  641.  How does XLISP initialize?
  642.  --------------------------
  643.  
  644. A major confusing aspect of xlisp is how it initializes, and how
  645. save/restore works. This is a multistep process that must take place
  646. in a specific order. 
  647.  
  648. When xlisp starts, there is no obarray, and in fact no symbols at
  649. all. All initial symbols must be created as part of initialization.
  650. In addition the character and small integer cells must be created,
  651. and all the C variables that point to xlisp symbols must be
  652. initialized. 
  653.  
  654. Initialization is mostly performed in xlinit.c, from the function
  655. xlinit(). This function is called from main() after main parses the
  656. command line, calls osinit() to initialize the OS interface, and sets
  657. the initial top level context. This initial context causes a fatal
  658. error to occur if any error happens during the initialization
  659. process. 
  660.  
  661. The first step of xlinit() is to call xlminit(), which is in xldmem.c
  662. or dldmem.c. This initializes the pointers for the memory manager,
  663. stacks, creates the small integer and character LVAL segments, and
  664. creates the NIL symbol by filling in the statically allocated NIL
  665. LVAL from one that is temporarily created. This first call of
  666. xlmakesym will do the first garbage collection -- all of the roots
  667. used for the mark routine have been set so that marking will not
  668. occur (there is nothing to mark!). It is important, however, that
  669. garbage collection not occur again until initialization is completed.
  670. This can be assured by having the allocation segment size, NNODES, be
  671. large enough for the entire initialization.
  672.  
  673. The second step in xlinit() is to call xldbug.c:xldinit() to turn
  674. debugging off.
  675.  
  676. At this point, if a restore is to occur from a workspace file, then
  677. the restore is attempted. If the restore is sucessful, then
  678. initialization is finished. See "How does save/restore work?" which
  679. is the next question.
  680.  
  681. If the restore fails or there is no file to restore, an initial
  682. workspace must be created. This is done by function initwks(), also
  683. in xlinit.c.
  684.  
  685. Initwks() starts by calling four initialization functions. 
  686.  
  687. xlsym.c:xlsinit() creates the symbol *OBARRAY* (and sets the
  688. variable obarray to point to it), creates the object array as the
  689. value, and enters obarray into the array. 
  690.  
  691. xlsymbols() is called next. It enters all of the symbols referenced
  692. by the interpreter into the obarray, and saves their addresses in C
  693. variables. This function is also called during restores, so it is
  694. important that it does not change the value of any symbols where the
  695. value would be set by restore. If the unbound indicator symbol does
  696. not exist, one is created. Then it puts NIL in the obarray if not
  697. already there (NIL being already created), then all the other symbols 
  698. are added (if they don't exist), and their addresses saved in C
  699. variables. 
  700.  
  701. This function also initializes constants such as NIL, T, and PI.
  702. Because a saved workspace might have a different file stream
  703. environment, xlsymbols always initializes the standard file streams
  704. based on the current xlisp invocation. It builds the structure
  705. property for RANDOM-STATE structures. It then (shudder!) calls two
  706. other initialization functions xlobj.c:obsymbols() and ossymbols (in
  707. the appropriate *stuff.c file) to enter symbols used in the object
  708. feature and operating system specific code, respectively.
  709.  
  710. Returning to initwks(), two aditional initialization routines are
  711. called. Xlread.c:xlrinit() initializes the read-table and installs
  712. the standard read macros. Xlobj.c:xloinit() creates the class and
  713. object objects.
  714.  
  715. Since the NIL and *OBARRAY* symbols were created before the unbound
  716. marker symbol, initwks sets the function values of these symbols, and
  717. of the unbound marker symbol, to be unbound. It then initializes all
  718. the global variables. Finally it creates all the builtin function
  719. bindings from the funtab table. The synonym functions are created
  720. last. 
  721.  
  722.  
  723.  How are workspaces saved and restored?
  724.  --------------------------------------
  725.  
  726. All the work is done in dlimage.c or xlimage.c, depending on the
  727. memory management scheme. The basic trick in a save is that memory
  728. locations upon a restore would be entirely different. Because of
  729. that, addresses written out are converted into offsets from the start
  730. of the segs LVAL segment list. In the restore operation, the offset
  731. is converted back into an address; if the offset is larger than the
  732. allocated segment memory, additional segment memory is allocated
  733. until an address can be calculated.
  734.  
  735. Looking at the save function, xlisave(char *fname), the argument
  736. string is taken as the name of a workspace file, and a binary file is
  737. created of that name. Then a garbage collection is performed since it
  738. would be wasteful to write out garbage.
  739.  
  740. The size of ftab is writen as a validity check, figuring that if the
  741. configuration changed, then this value would be different.
  742.  
  743. The offset of the *obarray* symbol is written next, since obarray is
  744. crucial to doing a restore -- it is used to get the addresses of all
  745. the other symbols used in the interpreter. Since NIL is a statically
  746. allocated symbol, the offsets to its function, property list, and
  747. printname are written. (I bet you didn't know you could define a
  748. function called NIL!)
  749.  
  750. Now the segs are traversed and all nodes are written out. The nodes
  751. are written in the format of a one byte tag followed by information
  752. dependent on the node type. Since many locations in the segment can
  753. be empty, one node type, FREE, has data that sets the next offset in
  754. the file, thus allowing skipping of many locations with a single
  755. command. The function setoffset(), called before writing tags in the
  756. other cases, handles writing the FREE entry. CONS and USTREAM cells
  757. consist of two pointers, which are written after conversion into
  758. offsets. For all other node types, the raw information is written by
  759. writenode(). This could be optimized since not all information is
  760. needed (for instance, the address of arrays won't be needed!)
  761.  
  762. A terminator entry (FREE with length of zero) is written, and the
  763. segs are traversed again, looking for nodes with attached
  764. array/string data and streams. For the types where the attached data
  765. is an array, the array elements (pointers) are converted to offsets
  766. and written out. For a string, the characters are written. For a
  767. stream (assuming FILETABLE is used), the file's name and position are
  768. written if it is other than standard input, output, or error. These
  769. streams cannot be saved or restored.
  770.  
  771.  
  772. Restoring a workspace is somewhat more difficult. The file is opened
  773. and checked for validity. Then the old memory image is deleted.
  774. During the deletion, any open file streams other than standard input,
  775. output, or error are closed. All of the global memory allocation
  776. pointers and stacks are reset, just like in initialization. Since the
  777. fixnum and character segments are of fixed size and need a known
  778. location, there are allocated. Their values, however, will be filled
  779. in from the workspace file. This is another wasteful inefficiency,
  780. but at least these segments are small.
  781.  
  782. The global pointer obarray is read from the file. As mentioned
  783. earlier, the cviptr() function converts the offset in the file into a
  784. physical address, allocating more node segments as necessary. The
  785. array portion of the NIL symbol is allocated, and its function,
  786. property list, and printname pointers are read from the file.
  787.  
  788. Then the node information is read in. For type FREE, the offset is
  789. adjusted. For CONS and USTREAM the car and cdr pointers are read, for
  790. other types, the LVAL data is read raw.
  791.  
  792.  
  793. The LVAL segments are scanned, and now the vector/string components
  794. of nodes are read. Since the order of nodes is unchanged, the data is
  795. read into the correct nodes. For vector types, the size field of the
  796. LVAL is consulted, vector space is allocated, and offsets are read
  797. from the file and converted into pointers. For strings, the string
  798. space is allocated and the string is read. For streams other than
  799. standard input, output, or error, the file name and position is read
  800. and an attempt is made to open the file. If the file can be opened,
  801. then it is positioned.
  802.  
  803. During the scan, for SUBR/FSUBR nodes funtab is consulted and the
  804. correct subroutine address is inserted.
  805.  
  806. During the whole process, if a tag is invalid or the file size is not
  807. correct, a fatal error occurs.
  808.  
  809. A garbage collection is performed to initialize the free space for
  810. future node allocation.
  811.  
  812. Finally xlsymbols() is called, as in the initializaton process, so
  813. that the C pointers in the interpreter can be set. This also sets the
  814. streams for standard input, output, and error to the correct values.
  815.  
  816.  
  817.  How do I add a new primitive fn to xlisp?
  818.  -----------------------------------------
  819.  
  820. Add a line to the end of xlftab.c:funtab[], and a function prototype
  821. to xlftab.h.  This table contains a list of triples:
  822.  
  823. The first element of each triple is the function name as it will
  824. appear to the programmer. Make it all upper case.
  825.  
  826. The second element is S (for SUBR) if (like most fns) your function
  827. wants its arguments pre-evaluated, else F (for FSUBR).
  828.  
  829. The third element is the name of the C function to call.
  830.  
  831. Remember that your arguments arrive on the xlisp argument rather
  832. than via the usual C parameter mechanism.
  833.  
  834. CAUTION: Try to keep your files separate from generic xlisp files, and
  835. to minimize the number of changes you make in the generic xlisp files.
  836. This way, you'll have an easier time re-installing your changes when
  837. new versions of xlisp come out.  It's a good idea to put a marker
  838. (like a comment with your initials) on each line you change or insert
  839. in the generic xlisp fileset.  For example, if you are going to add
  840. many primitive functions to your xlisp, use an #include file rather
  841. than putting them all in xlftab.c.
  842.  
  843. CAUTION: Remember that you usually need to protect the LVAL variables
  844. in your function from the garbage-collector.  It never hurts to do
  845. this, and often produces obscure bugs if you dont.  Generic code for
  846. a new primitive fn:
  847.  
  848. /* xlsamplefun - do useless stuff. */
  849. /* Called like (samplefun '(a c b) 1 2.0) */
  850. LVAL xlsamplefun()
  851. {
  852.     /* Variables to hold the arguments: */
  853.     LVAL    list_arg, integer_arg, float_arg;
  854.  
  855.     /* Get the arguments, with appropriate errors */
  856.     /* if any are of the wrong type.  Look in     */
  857.     /* xlisp.h for macros to read other types of  */
  858.     /* arguments.  Look in xlmath.c for examples  */
  859.     /* of functions which can handle an argument  */
  860.     /* which may be either int or float:          */
  861.     list_arg    = xlgalist()  ;  /* "XLisp Get A LIST"   */
  862.     integer_arg = xlgafixnum();  /* "XLisp Get A FIXNUM" */
  863.     float_arg   = xlgaflonum();  /* "XLisp Get A FLONUM" */
  864.  
  865.     /* Issue an error message if there are any extra arguments: */
  866.     xllastarg();
  867.  
  868.  
  869.  
  870.     /* Call a separate C function to do the actual  */
  871.     /* work.  This way, the main function can       */
  872.     /* be called from both xlisp code and C code.   */
  873.     /* By convention, the name of the xlisp wrapper */
  874.     /* starts with "xl", and the native C function  */
  875.     /* has the same name minus the "xl" prefix:     */
  876.     return samplefun( list_arg, integer_arg, float_arg );
  877. }
  878. LVAL samplefun( list_arg, integer_arg, float_arg )
  879. LVAL            list_arg, integer_arg, float_arg;
  880. {
  881.     FIXTYPE val_of_integer_arg;
  882.     FLOTYPE val_of_float_arg;
  883.  
  884.     /* Variables which will point to LISP objects: */
  885.     LVAL result;
  886.  
  887.     LVAL list_ptr;
  888.     LVAL float_ptr;
  889.     LVAL int_ptr;
  890.  
  891.     /* Protect our internal pointers by */
  892.     /* pushing them on the evaluation   */
  893.     /* stack so the garbage collector   */
  894.     /* can't recycle them in the middle */
  895.     /* of the routine:                  */
  896.     xlstkcheck(3);    /* Make sure following xlsave */
  897.                       /* calls won't overrun stack. */
  898.     xlsave(list_ptr); /* Use xlsave1() if you don't */
  899.     xlsave(float_ptr);/* do an xlstkcheck().        */
  900.     xlsave(int_ptr);
  901.  
  902.     /* Create an internal list structure, protected */
  903.     /* against garbage collection until we exit fn: */
  904.     list_ptr = cons(list_arg,list_arg);
  905.  
  906.     /* Get the actual values of our fixnum and flonum: */
  907.     val_of_integer_arg = getfixnum( integer_arg );
  908.     val_of_float_arg   = getflonum( float_arg   );
  909.  
  910.  
  911.     /*******************************************/
  912.     /* You can have any amount of intermediate */
  913.     /* computations at this point in the fn... */
  914.     /*******************************************/
  915.  
  916.  
  917.     /* Make new numeric values to return: */
  918.     integer_ptr = cvflonum( val_of_integer_arg * 3   );
  919.     float_ptr   = cvflonum( val_of_float_arg   * 3.0 );
  920.  
  921.     /* Cons it all together to produce a return value: */
  922.     result = cons(
  923.         list_ptr,
  924.         cons(
  925.             integer_ptr,
  926.             cons(
  927.                 float_ptr,
  928.                 NIL
  929.             )
  930.         )
  931.     );
  932.  
  933.     /* Restore the stack, cancelling the xlsave()s: */
  934.     xlpopn(3); /* Use xlpop() for a single argument.*/
  935.  
  936.     return result;
  937. }
  938.  
  939.  
  940. - Jeff   (S)
  941.  
  942.  
  943.