[BACK]Return to usersch4.tex CVS log [TXT][DIR] Up to [local] / OpenXM_contrib / pari-2.2 / doc

Annotation of OpenXM_contrib/pari-2.2/doc/usersch4.tex, Revision 1.1

1.1     ! noro        1: % $Id: usersch4.tex,v 1.27 2001/09/19 22:00:46 karim Exp $
        !             2: % Copyright (c) 2000  The PARI Group
        !             3: %
        !             4: % This file is part of the PARI/GP documentation
        !             5: %
        !             6: % Permission is granted to copy, distribute and/or modify this document
        !             7: % under the terms of the GNU Free Documentation License
        !             8: \chapter{Programming PARI in Library Mode}
        !             9:
        !            10: \section{Introduction: initializations, universal objects}
        !            11: \label{se:intro4}
        !            12:
        !            13: \noindent
        !            14: To be able to use PARI in \idx{library mode}, you must write a C program and
        !            15: link it to the PARI library. See the installation guide (in Appendix~A)
        !            16: on how to create and install the library and include files. A sample Makefile
        !            17: is presented in Appendix~B.
        !            18:
        !            19: Probably the best way to understand how programming is done is to work
        !            20: through a complete example. We will write such a program in
        !            21: \secref{se:prog}. Before doing this, a few explanations are in order.
        !            22:
        !            23: First, one must explain to the outside world what kind of objects and
        !            24: routines we are going to use. This is done simply with the statement
        !            25:
        !            26: \bprog
        !            27: #include <pari.h>
        !            28: @eprog
        !            29: \noindent
        !            30: This file \tet{pari.h} imports all the necessary constants,
        !            31: variables and functions, defines some important macros, and also defines the
        !            32: fundamental type for all PARI objects: the type \teb{GEN}, which is
        !            33: simply a pointer to \kbd{long}.
        !            34:
        !            35: \misctitle{Technical note}: we would have liked to define a type \kbd{GEN}
        !            36: to be a pointer to itself. This unfortunately is not possible in C, except by
        !            37: using structures, but then the names become unwieldy. The result of this is
        !            38: that when we use a component of a PARI object, it will be a \kbd{long},
        !            39: hence will need to be typecast to a \kbd{GEN} again if we want to avoid
        !            40: warnings from the compiler. This will sometimes be quite tedious, but of
        !            41: course is trivially done. See the discussion on typecasts in the next
        !            42: section.
        !            43:
        !            44: After declaring the use of the file \kbd{pari.h}, the first executable
        !            45: statement of a main program should be to initialize the PARI system, and in
        !            46: particular the PARI stack which will be both a scratchboard and a repository
        !            47: for computed objects. This is done with a call to the function
        !            48:
        !            49: \fun{void}{pari_init}{long size, long maxprime)}
        !            50:
        !            51: \noindent The first argument is the number of bytes given to PARI to work
        !            52: with (it should not reasonably be taken below 500000), and the second is the
        !            53: upper limit on a precomputed prime number table. If you don't want prime
        !            54: numbers, just put $\tet{maxprime} = 2$. Be careful because lots a PARI
        !            55: functions need this table (certainly all the ones of interest to number
        !            56: theorists). If you wind up with the error message ``not enough precomputed
        !            57: primes'', try to increase this value.
        !            58:
        !            59: \noindent We have now at our disposal:
        !            60:
        !            61: $\bullet$ a large PARI \tev{stack} containing nothing. It's a big
        !            62: connected chunk of memory whose size you chose when invoking
        !            63: \tet{pari_init}. All your computations are going to take place here.
        !            64: When doing large computations, unwanted intermediate results clutter up
        !            65: memory very fast so some kind of garbage collecting is needed. Most large
        !            66: systems do garbage collecting when the memory is getting scarce, and this slows
        !            67: down the performance. In PARI we have taken a different approach: you must do
        !            68: your own cleaning up when the intermediate results are not needed anymore.
        !            69: Special purpose routines have been written to do this; we will see later how
        !            70: (and when, if at all) you should use them.
        !            71:
        !            72: $\bullet$ the following {\it universal objects\/} (by definition, objects
        !            73: which do not belong on the stack): the integers 0, 1 and 2 (respectively
        !            74: called \teb{gzero}, \teb{gun}, and \teb{gdeux}), the
        !            75: fraction $\dfrac{1}{2}$ (\teb{ghalf}), the complex number $i$
        !            76: (\teb{gi}). All of these are of type \kbd{GEN}.
        !            77:
        !            78: In addition, space is reserved for the polynomials $x_v$
        !            79: \sidx{variable}
        !            80: (\teb{polx}\kbd{[$v$]}), and the polynomials $1_v$ (\teb{polun}\kbd{[$v$]}).
        !            81: Here, $x_v$ is the name of variable number $v$, where $0\le v\le
        !            82: \tet{MAXVARN}$ (the exact value of which depends on your machine, at least
        !            83: 16383 in any case). Both \kbd{polun} and \kbd{polx} are arrays of
        !            84: \kbd{GEN}s, the index being the polynomial variable number.
        !            85:
        !            86: However, except for the ones corresponding to variables $0$ and \kbd{MAXVARN},
        !            87: these polynomials are {\it not\/} created upon initialization. It
        !            88: is the programmer's responsibility to fill them before use. We'll see how
        !            89: this is done in \secref{se:vars} ({\it never\/} through direct assignment).
        !            90:
        !            91: $\bullet$ a {\it \idx{heap}\/} which is just a linked list of permanent
        !            92: universal objects. For now, it contains exactly the ones listed above. You
        !            93: will probably very rarely use the heap yourself; and if so, only as a
        !            94: collection of individual copies of objects taken from the stack
        !            95: (called \idx{clone}s in the sequel). Thus you need not bother with its
        !            96: internal structure, which may change as PARI evolves. Some complex PARI
        !            97: functions may create clones for special garbage collecting purposes, usually
        !            98: destroying them when returning.
        !            99:
        !           100: $\bullet$ a table of primes (in fact of {\it differences\/} between
        !           101: consecutive primes), called \teb{diffptr}, of type \kbd{byteptr}
        !           102: (pointer to \kbd{unsigned char}). Its use is described in appendix~C.
        !           103:
        !           104: $\bullet$ access to all the built-in functions of the PARI library.
        !           105: These are declared to the outside world when you include \kbd{pari.h}, but
        !           106: need the above things to function properly. So if you forget the call to
        !           107: \tet{pari_init}, you will immediately get a fatal error when running your
        !           108: program (usually a segmentation fault).
        !           109:
        !           110: \section{Important technical notes}
        !           111:
        !           112: \subsec{Typecasts}.\label{se:typecast}\sidx{typecast}
        !           113:
        !           114: \noindent
        !           115: We have seen that, due to the non-recursiveness of the PARI types from the
        !           116: compiler's point of view, many typecasts will be necessary when programming
        !           117: in PARI. To take an example, a vector $V$ of dimension 2 (two components)
        !           118: will be represented by a chunk of memory pointed to by the \kbd{GEN}~\kbd{V}.
        !           119: \kbd{V[0]} contains coded information, in particular about the type of the
        !           120: object, its length, etc. \kbd{V[1]} and \kbd{V[2]} contain pointers to
        !           121: the two components of \kbd{V}. Those coefficients \kbd{V[i]} themselves are in
        !           122: chunks of memory whose complexity depends on their own types, and so on. This
        !           123: is where typecasting will be necessary: a priori, \kbd{V[i]} (for
        !           124: $\kbd{i}=1,2$) is a \kbd{long}, but we will want to use it as a \kbd{GEN}.
        !           125: The following two constructions will be exceedingly frequent (\kbd{x} and
        !           126: \kbd{V} are \kbd{GEN}s):
        !           127: %
        !           128: \bprog
        !           129:   V[i] = (long) x;
        !           130:   x = (GEN) V[i];
        !           131: @eprog
        !           132: \noindent Note that a typecast is not a valid lvalue (cannot be put on the
        !           133: left side of an assignment), so \kbd{(GEN)V[i] = x} would be incorrect, though
        !           134: some compilers may accept it.
        !           135:
        !           136: Due to this annoyance, the PARI functions and variables that occur most
        !           137: frequently have analogues which are macros including the typecast. The complete
        !           138: list can be found in the file \kbd{paricast.h} (which is included by
        !           139: \kbd{pari.h} and can be found at the same place). For instance you can
        !           140: abbreviate:
        !           141: %
        !           142: \bprog
        !           143: (long) gzero     ----->  zero
        !           144: (long) gun       ----->  un
        !           145: (long) polx[v]   ----->  lpolx[v]
        !           146: (long) gadd(x,y) ----->  ladd(x,y)
        !           147: @eprog\noindent%
        !           148: \kbdsidx{zero}%
        !           149: \kbdsidx{un}%
        !           150: \kbdsidx{lpolx}
        !           151: In general, replacing a leading \kbd{g} by an \kbd{l} in the name of a PARI
        !           152: function will typecast the result to \kbd{long}. Note that \kbd{ldiv} is an
        !           153: ANSI C function which is is hidden in PARI by a macro of the same name
        !           154: representing \kbd{(long)gdiv}.
        !           155:
        !           156: The macro $\teb{coeff}(x,m,n)$ exists with exactly the meaning of \kbd{x[m,n]}
        !           157: under GP when \kbd{x} is a matrix. This is a purely syntactical trick
        !           158: to reduce the number of typecasts and thus does not create a copy of the
        !           159: coefficient (contrary to all the library {\it functions\/}). It can be put on
        !           160: the left side of an assignment statement, and its value, of type \kbd{long}
        !           161: integer, is a pointer to the desired coefficient object. The macro
        !           162: \kbd{gcoeff} is a synonym for \kbd{(GEN) coeff}, hence cannot be put on
        !           163: the left side of an assignment.
        !           164:
        !           165: To retrieve the values of elements of lists of \dots\ of
        !           166: lists of vectors, without getting infuriated by gigantic lists of typecasts,
        !           167: we have the \teb{mael} macros (for {\bf m}ultidimensional {\bf a}rray {\bf
        !           168: el}ement). The syntax is $\key{mael}n(x,a_1,\dots,a_n)$, where $x$ is a
        !           169: \kbd{GEN}, the $a_i$ are indexes, and $n$ is an integer between $2$ and $5$
        !           170: (with a standalone \kbd{mael} as a synonym for \kbd{mael2}). This stands
        !           171: for $x[a_1][a_2]\dots[a_n]$ (with all the necessary typecasts), and returns a
        !           172: \kbd{long} (i.e.~they are valid lvalues). The $\kbd{gmael}n$ macros are
        !           173: synonyms for $\kbd{(GEN) mael}n$. Note that due to the implementation of matrix
        !           174: types in PARI (i.e.~as horizontal lists of vertical vectors), \kbd{coeff(x,y)}
        !           175: is actually completely equivalent to \kbd{mael(y,x)}. It is suggested that
        !           176: you use \kbd{coeff} in matrix context, and \kbd{mael} otherwise.
        !           177:
        !           178: \subsec{Variations on basic functions}.\label{se:low_level} In the library
        !           179: syntax descriptions in Chapter~3, we have only given the basic names of the
        !           180: functions. For example \kbd{gadd}$(x,y)$ assumes that $x$ and $y$ are PARI
        !           181: objects (of type \kbd{GEN}), and {\it creates\/} the result $x+y$ on the PARI
        !           182: stack. For most of the basic operators and functions, many other variants
        !           183: are available. We give some examples for \kbd{gadd}, but the same is true for
        !           184: all the basic operators, as well as for some simple common functions (a
        !           185: more complete list is given in Chapter~5):
        !           186:
        !           187: \fun{GEN}{gaddgs}{GEN x, long y}
        !           188:
        !           189: \fun{GEN}{gaddsg}{long x, GEN y}
        !           190:
        !           191: \noindent In the following three, \kbd{z} is a preexisting \kbd{GEN} and the
        !           192: result of the corresponding operation is put into~\kbd{z}. The size of the PARI
        !           193: stack does not change:
        !           194:
        !           195: \fun{void}{gaddz}{GEN x, GEN y, GEN z}
        !           196:
        !           197: \fun{void}{gaddgsz}{GEN x, long y, GEN z}
        !           198:
        !           199: \fun{void}{gaddsgz}{GEN x, GEN y, GEN z}
        !           200:
        !           201: \noindent There are also low level functions which are special cases of the
        !           202: above:
        !           203:
        !           204: \fun{GEN}{addii}{GEN x, GEN y}: here $x$ and $y$ are \kbd{GEN}s of type
        !           205: \typ{INT} (this is not checked).
        !           206:
        !           207: \fun{GEN}{addrr}{GEN x, GEN y}: here $x$ and $y$ are \kbd{GEN} reals
        !           208: (type \typ{REAL}).
        !           209:
        !           210: \noindent
        !           211: There also exist functions \teb{addir}, \teb{addri}, \teb{mpadd} (whose
        !           212: two arguments can be of type integer or real), \teb{addis} (to add a \typ{INT}
        !           213: and a \kbd{long}) and so on.
        !           214:
        !           215: All these functions can of course be called by the user but we feel that
        !           216: the few microseconds lost in calling more general functions (in this case
        !           217: \kbd{gadd}) are compensated by the fact that one needs to remember a much
        !           218: smaller number of functions, and also because there is a hidden danger here:
        !           219: the types of the objects that you use, if they are themselves results of a
        !           220: previous computation, are not completely predetermined. For instance the
        !           221: multiplication of a type real \typ{REAL} by a type integer \typ{INT}
        !           222: {\it usually\/} gives a result of type real, except when the integer is~0, in
        !           223: which case according to the PARI philosophy the result is the exact integer~0.
        !           224: Hence if afterwards you call a function which specifically needs a real
        !           225: type argument, you are going to be in trouble.
        !           226:
        !           227: If you really want to use these functions, their names are self-explanatory
        !           228: once you know that {\bf i} stands for a PARI integer, {\bf r} for a PARI
        !           229: real, {\bf mp} for i or r, {\bf s} for an ordinary signed long, whereas {\bf
        !           230: z} (as a suffix) means that the result is not created on the PARI
        !           231: stack but assigned to a preexisting GEN object passed as an extra argument.
        !           232:
        !           233: For completeness, Chapter 5 gives a description of all these
        !           234: low-level functions.
        !           235:
        !           236: Please note that in the present version \vers{} the names of the functions
        !           237: are not always consistent. This will be changed. Hence anyone programming in
        !           238: PARI must be aware that the names of almost all functions that he uses might
        !           239: be subject to change. If the need arises (i.e.~if there really are people out
        !           240: there who delve into the innards of PARI), updated versions with no name
        !           241: changes will be released.
        !           242:
        !           243: \subsec{Portability: 32-bit / 64-bit architectures}.
        !           244:
        !           245: \noindent
        !           246: PARI supports both 32-bit and 64-bit based machines, but not simultaneously!
        !           247: The library will have been compiled assuming a given architecture (a~priori
        !           248: following a guess by the \kbd{Configure} program, see Appendix~A), and some
        !           249: of the header files you include (through \kbd{pari.h}) will have been modified
        !           250: to match the library.
        !           251:
        !           252: Portable macros are defined to bypass most machine dependencies. If you
        !           253: want your programs to run identically on 32-bit and 64-bit machines, you will
        !           254: have to use these, and not the corresponding numeric values, whenever the
        !           255: precise size of your \kbd{long} integers might matter. Here are the most
        !           256: important ones:
        !           257:
        !           258: \settabs\+
        !           259: -----------------------------&---------------&------------&\cr
        !           260: \+
        !           261:                     & 64-bit  & 32-bit
        !           262: \cr\+
        !           263: \tet{BITS_IN_LONG}  & 64      & 32
        !           264: \cr\+
        !           265: \tet{LONG_IS_64BIT} & defined & undefined
        !           266: \cr\+
        !           267: \tet{DEFAULTPREC}   & 3       & 4 & ($\approx$ 19 decimal digits, %
        !           268:  see formula below)
        !           269: \cr\+
        !           270: \tet{MEDDEFAULTPREC}& 4       & 6 & ($\approx$ 38 decimal digits)
        !           271: \cr\+
        !           272: \tet{BIGDEFAULTPREC}& 5       & 8 & ($\approx$ 57 decimal digits)
        !           273: \cr
        !           274: \noindent
        !           275: For instance, suppose you call a transcendental function, such as
        !           276:
        !           277: \kbd{GEN \key{gexp}(GEN x, long prec)}.
        !           278:
        !           279: \noindent The last argument \kbd{prec} is only used if \kbd{x} is an exact
        !           280: object (otherwise the relative precision is determined by the precision
        !           281: of~\kbd{x}). But since \kbd{prec} sets the size of the inexact result counted
        !           282: in (\kbd{long}) {\it words\/} (including codewords), the same value of
        !           283: \kbd{prec} will yield different results on 32-bit and 64-bit machines. Real
        !           284: numbers have two codewords (see~\secref{se:impl}), so the formula for
        !           285: computing the bit accuracy is
        !           286: $$ \tet{bit_accuracy}(\kbd{prec}) = (\kbd{prec} - 2) * \tet{BITS_IN_LONG}$$
        !           287: (this is actually the definition of a macro). The corresponding accuracy
        !           288: expressed in decimal digits would be
        !           289: %
        !           290: $$ \kbd{bit\_accuracy(prec)} * \log(2) / \log(10).$$
        !           291: %
        !           292: For example if the value of \kbd{prec} is 5, the corresponding accuracy for
        !           293: 32-bit machines is $(5-2)*\log(2^{32})/\log(10)\approx 28$ decimal digits,
        !           294: while for 64-bit machines it is $(5-2)*\log(2^{64})/\log(10)\approx 57$
        !           295: decimal digits.
        !           296:
        !           297: Thus, you must take care to change the \kbd{prec} parameter you are supplying
        !           298: according to the bit size, either using the default precisions given by the
        !           299: various \kbd{DEFAULTPREC}s, or by using conditional constructs of the form:
        !           300: %
        !           301: \bprog
        !           302: #ifndef LONG_IS_64BIT
        !           303:   prec = 4;
        !           304: #else
        !           305:   prec = 6;
        !           306: #endif
        !           307: @eprog
        !           308: \noindent which is in this case equivalent to the statement
        !           309: \kbd{prec = MEDDEFAULTPREC;}.
        !           310:
        !           311: Note that for parity reasons, half the accuracies available on 32-bit
        !           312: architectures (the odd ones) have no precise equivalents on 64-bit machines.
        !           313:
        !           314: \section{Creation of PARI objects, assignments, conversions}
        !           315:
        !           316: \subsec{Creation of PARI objects}.\sidx{creation}
        !           317: The basic function which creates a PARI object is the function
        !           318: \teb{cgetg} whose prototype is:
        !           319:
        !           320: \kbd{GEN \key{cgetg}(long length, long type)}.
        !           321:
        !           322: \noindent
        !           323: Here \kbd{length} specifies the number of longwords to be allocated to the
        !           324: object, and type is the type number of the object, preferably in symbolic
        !           325: form (see \secref{se:impl} for the list of these). The precise effect of
        !           326: this function is as follows: it first creates on the PARI {\it stack\/} a
        !           327: chunk of memory of size \kbd{length} longwords, and saves the address of the
        !           328: chunk which it will in the end return.  If the stack has been used up, a
        !           329: message to the effect that ``the PARI stack overflows'' will be printed,
        !           330: and an error raised. Otherwise, it sets the type and length of the PARI object.
        !           331: In effect, it fills correctly and completely its first codeword (\kbd{z[0]} or
        !           332: \kbd{*z}).  Many PARI objects also have a second codeword (types \typ{INT},
        !           333: \typ{REAL},  \typ{PADIC}, \typ{POL}, and \typ{SER}). In case you want to
        !           334: produce one of those from scratch (this should be exceedingly rare), {\it it
        !           335: is your responsibility to fill this second codeword}, either explicitly (using
        !           336: the macros described in \secref{se:impl}), or implicitly using an assignment
        !           337: statement (using \kbd{gaffect}).
        !           338:
        !           339: Note that the argument \kbd{length} is predetermined for a number of types:
        !           340: 3 for types \typ{INTMOD}, \typ{FRAC}, \typ{FRACN}, \typ{COMPLEX},
        !           341: \typ{POLMOD}, \typ{RFRAC} and \typ{RFRACN}, 4 for type \typ{QUAD}
        !           342: and \typ{QFI}, and 5 for type \typ{PADIC} and \typ{QFR}. However for the sake
        !           343: of efficiency, no checking is done in the function \kbd{cgetg}, so
        !           344: disasters will occur if you give an incorrect length.
        !           345:
        !           346: \misctitle{Notes}:
        !           347: 1)  The main use of this function is to prepare for later assigments
        !           348: (see \secref{se:assign}). Most of the time you will use \kbd{GEN} objects
        !           349: as they are created and returned by PARI functions. In this case you don't need
        !           350: to use \kbd{cgetg} to create space to hold them.
        !           351:
        !           352: \noindent 2) For the creation of leaves, i.e.~integers or reals, which is
        !           353: very common,
        !           354:
        !           355: \fun{GEN}{cgeti}{long length}
        !           356:
        !           357: \fun{GEN}{cgetr}{long length}
        !           358:
        !           359: \noindent should be used instead of \kbd{cgetg(length, t\_INT)} and
        !           360: \kbd{cgetg(length, t\_REAL)} respectively.
        !           361:
        !           362: \noindent 3) The macros \teb{lgetg}, \teb{lgeti}, \teb{lgetr} are
        !           363: predefined as \kbd{(long)cgetg}, \kbd{(long)cgeti}, \kbd{(long)cgetr},
        !           364: respectively.
        !           365:
        !           366: \misctitle{Examples}: 1) \kbd{z = cgeti(DEFAULTPREC)} and
        !           367: \kbd{cgetg(DEFAULTPREC, t\_INT)} create an integer object whose ``precision''
        !           368: is \kbd{bit\_accuracy(DEFAULTPREC)} = 64. This means \kbd{z} can hold rational
        !           369: integers of absolute value less than $2^{64}$. Note that in both cases, the
        !           370: second codeword will {\it not\/} be filled. Of course we could use numerical
        !           371: values, e.g.~\kbd{cgeti(4)}, but this would have different meanings on
        !           372: different machines as \kbd{bit\_accuracy(4)} equals 64 on 32-bit machines,
        !           373: but 128 on 64-bit machines.
        !           374:
        !           375: \noindent 2) The following creates a type ``complex'' object whose real and
        !           376: imaginary parts can hold real numbers of precision
        !           377: $\kbd{bit\_accuracy(MEDDEFAULTPREC)} = 96\hbox{ bits:}$
        !           378: %
        !           379: \bprog
        !           380:   z = cgetg(3, t_COMPLEX);
        !           381:   z[1] = lgetr(MEDDEFAULTPREC);
        !           382:   z[2] = lgetr(MEDDEFAULTPREC);
        !           383: @eprog
        !           384:
        !           385: \noindent 3) To create a matrix object for $4\times 3$ matrices:
        !           386: %
        !           387: \bprog
        !           388:   z = cgetg(4, t_MAT);
        !           389:   for(i=1; i<4; i++) z[i] = lgetg(5, t_COL);
        !           390: @eprog
        !           391: %
        !           392: \noindent If one wishes to create space for the matrix elements themselves,
        !           393: one has to follow this with a double loop to fill each column vector.
        !           394:
        !           395: These last two examples illustrate the fact that since PARI types are
        !           396: recursive, all the branches of the tree must be created. The function
        !           397: \teb{cgetg} creates only the ``root'', and other calls to \kbd{cgetg} must be
        !           398: made to produce the whole tree.  For matrices, a common mistake is to think
        !           399: that \kbd{z = cgetg(4, t\_MAT)} (for example) will create the root of the
        !           400: matrix: one needs also to create the column vectors of the matrix (obviously,
        !           401: since we specified only one dimension in the first \kbd{cgetg}!). This is
        !           402: because a matrix is really just a row vector of column vectors (hence a
        !           403: priori not a basic type), but it has been given a special type number so that
        !           404: operations with matrices become possible.
        !           405:
        !           406: \subsec{Assignments}.
        !           407: Firstly, if \kbd{x} and \kbd{y} are both declared as \kbd{GEN} (i.e.~pointers
        !           408: to something), the ordinary C assignment \kbd{y = x} makes perfect sense: we
        !           409: are just moving a pointer around. However, physically modifying either
        !           410: \kbd{x} or \kbd{y} (for instance, \kbd{x[1] = 0}) will also change the other
        !           411: one, which is usually not desirable. \label{se:assign}
        !           412:
        !           413: \misctitle{Very important note}: Using the functions described in this
        !           414: paragraph is very inefficient and often awkward: one of the \tet{gerepile}
        !           415: functions (see~\secref{se:garbage}) should be preferred. See the paragraph
        !           416: end for some exceptions to this rule.
        !           417:
        !           418: \noindent
        !           419: The general PARI \idx{assignment} function is the function \teb{gaffect} with
        !           420: the following syntax:
        !           421:
        !           422: \fun{void}{gaffect}{GEN x, GEN y}
        !           423:
        !           424: \noindent
        !           425: Its effect is to assign the PARI object \kbd{x} into the {\it preexisting\/}
        !           426: object \kbd{y}. This copies the whole structure of \kbd{x} into \kbd{y} so
        !           427: many conditions must be met for the assignment to be possible. For instance
        !           428: it is allowed to assign an integer into a real number, but the converse is
        !           429: forbidden.  For that, you must use the truncation or rounding function of
        !           430: your choice (see section 3.2). It can also happen that \kbd{y} is not large
        !           431: enough or does not have the proper tree structure to receive the object
        !           432: \kbd{x}. As an extreme example, assume \kbd{y} is the zero integer with length
        !           433: equal to 2. Then all assignments of a non-zero integer into \kbd{y} will
        !           434: result in an error message since \kbd{y} is not large enough to accommodate
        !           435: a non-zero integer.  In general common sense will tell you what is possible,
        !           436: keeping in mind the PARI philosophy which says that if it makes sense it is
        !           437: legal. For instance, the assignment of an imprecise object into a precise one
        !           438: does {\it not\/} make sense. However, a change in precision of imprecise
        !           439: objects is allowed.
        !           440:
        !           441: All functions ending in ``\kbd{z}'' such as \teb{gaddz}
        !           442: (see~\secref{se:low_level}) implicitly use this function. In fact what they
        !           443: exactly do is record {\teb{avma}} (see~\secref{se:garbage}), perform the
        !           444: required operation, \teb{gaffect} the result to the last operand, then
        !           445: restore the initial \kbd{avma}.
        !           446:
        !           447: You can assign ordinary C long integers into a PARI object (not necessarily
        !           448: of type \typ{INT}). Use the function \teb{gaffsg} with the following
        !           449: syntax:
        !           450:
        !           451: \fun{void}{gaffsg}{long s, GEN y}
        !           452:
        !           453: \misctitle{Note}: due to the requirements mentionned above, it's usually
        !           454: a bad idea to use \tet{gaffect} statements. Two exceptions:
        !           455:
        !           456: $\bullet$ for simple objects (e.g.~leaves) whose size is controlled, they can
        !           457: be easier to use than gerepile, and about as efficient.
        !           458:
        !           459: $\bullet$ to coerce an inexact object to a given precision. For instance
        !           460: \bprog
        !           461: gaffect(x, (tmp=cgetr(3))); x = tmp;
        !           462: @eprog
        !           463: \noindent at the beginning of a routine where precision can be kept to a
        !           464: minimum (otherwise the precision of \kbd{x} will be used in all subsequent
        !           465: computations, which will be a disaster if \kbd{x} is known to thousands of
        !           466: digits).
        !           467:
        !           468: \subsec{Copy}. It is also very useful to \idx{copy} a PARI object, not
        !           469: just by moving around a pointer as in the \kbd{y = x} example, but by
        !           470: creating a copy of the whole tree structure, without pre-allocating a
        !           471: possibly complicated \kbd{y} to use with \kbd{gaffect}. The function which
        !           472: does this is called \teb{gcopy}, with the predefined macro
        !           473: \teb{lcopy} as a synonym for \kbd{(long)gcopy}. Its syntax is:
        !           474:
        !           475: \fun{GEN}{gcopy}{GEN x}
        !           476:
        !           477: \noindent and the effect is to create a new copy of x on the PARI stack.
        !           478: Beware that universal objects which occur in specific components of certain
        !           479: types (mainly moduli for types \typ{INTMOD} and \typ{PADIC}) are not
        !           480: copied, as they are assumed to be permanent. In this case, \kbd{gcopy} only
        !           481: copies the pointer. Use \fun{GEN}{forcecopy}{GEN x} if you want a complete
        !           482: copy.
        !           483:
        !           484: Please be sure at this point that you really understand the difference between
        !           485: \kbd{y = x}, \kbd{y = gcopy(x)}, and \kbd{gaffect(x,y)}: this will save you
        !           486: from many ``obvious'' mistakes later on.
        !           487:
        !           488: \subsec{Clones}.\sidx{clone}
        !           489: Sometimes, it may be more efficient to create a {\it permanent\/} copy of a
        !           490: PARI object. This will not be created on the stack but on the heap. The
        !           491: function which does this is called \teb{gclone}, with the predefined macro
        !           492: \teb{lclone} as a synonym for \kbd{(long)gclone}. Its syntax is:
        !           493:
        !           494: \fun{GEN}{gclone}{GEN x}
        !           495:
        !           496: A clone can be removed from the heap (thus destroyed) using
        !           497:
        !           498: \fun{void}{gunclone}{GEN x}
        !           499:
        !           500: \noindent No PARI object should keep references to a clone which has been
        !           501: destroyed. If you want to copy a clone back to the stack then delete it, use
        !           502: \tet{forcecopy} and not \tet{gcopy}, otherwise some components might not be
        !           503: copied (moduli of \typ{INTMOD}s and \typ{POLMOD}s for instance).
        !           504:
        !           505: \subsec{Conversions}.\sidx{conversions}
        !           506: The following functions convert C objects to PARI objects (creating them on
        !           507: the stack as usual):
        !           508:
        !           509: \fun{GEN}{stoi}{long s}: C \kbd{long} integer  (``small'') to PARI integer
        !           510: (\typ{INT})
        !           511:
        !           512: \fun{GEN}{dbltor}{double s}: C \kbd{double} to PARI real (\typ{REAL}). The
        !           513: accuracy of the result is 19 decimal digits, i.e.~a type \typ{REAL} of
        !           514: length \kbd{DEFAULTPREC}, although on 32-bit machines only 16 of them will
        !           515: be significant.
        !           516:
        !           517: \noindent We also have the converse functions:
        !           518:
        !           519: \fun{long}{itos}{GEN x}: \kbd{x} must be of type \typ{INT},
        !           520:
        !           521: \fun{double}{rtodbl}{GEN x}: \kbd{x} must be of type \typ{REAL},
        !           522:
        !           523: \noindent as well as the more general ones:
        !           524:
        !           525: \fun{long}{gtolong}{GEN x},
        !           526:
        !           527: \fun{double}{gtodouble}{GEN x}.
        !           528:
        !           529: \section{Garbage collection}\label{se:garbage}\sidx{garbage collecting}
        !           530:
        !           531: \subsec{Why and how}.
        !           532:
        !           533: \noindent
        !           534: As we have seen, the \kbd{pari\_init} routine allocates a big range of
        !           535: addresses (the {\it stack\/}) that are going to be used throughout. Recall that
        !           536: all PARI objects are pointers. But for universal objects, they will all point
        !           537: at some part of the stack.
        !           538:
        !           539: The stack starts at the address \kbd{bot} and ends just before \kbd{top}. This
        !           540: means that the quantity
        !           541: %
        !           542: $$ (\kbd{top} - \kbd{bot})\,/\,\kbd{sizeof(long)} $$
        !           543: %
        !           544: is equal to the \kbd{size} argument of \kbd{pari\_init}. The PARI
        !           545: stack also has a ``current stack pointer'' called \teb{avma}, which
        !           546: stands for {\bf av}ailable {\bf m}emory {\bf a}ddress. These three variables
        !           547: are global (declared for you by \kbd{pari.h}). For historical reasons they
        !           548: are of type \tet{ulong} (unsigned long) and not of type \kbd{GEN} as would
        !           549: seem more natural.
        !           550:
        !           551: The stack is oriented upside-down: the more recent an object, the closer to
        !           552: \kbd{bot}. Accordingly, initially \kbd{avma} = \kbd{top}, and \kbd{avma} gets
        !           553: {\it decremented\/} as new objects are created. As its name indicates,
        !           554: \kbd{avma} always points just {\it after\/} the first free address on the
        !           555: stack, and \kbd{(GEN)avma} is always (a pointer to) the latest created object.
        !           556: When \kbd{avma} reaches \kbd{bot}, the stack overflows, aborting all
        !           557: computations, and an error message is issued. To avoid this {\it you\/} will
        !           558: need to clean up the stack from time to time, when some bunch of intermediate
        !           559: objects will not be needed anymore. This is called ``{\it garbage
        !           560: collecting}.''
        !           561:
        !           562: We are now going to describe briefly how this is done. We will see many
        !           563: concrete examples in the next subsection.
        !           564:
        !           565: \noindent$\bullet$
        !           566: First, PARI routines will do their own garbage collecting, which
        !           567: means that whenever a documented function from the library returns, only its
        !           568: result(s) will have been added to the stack (non-documented ones may not do
        !           569: this, for greater speed). In particular, a PARI function that does not return
        !           570: a \kbd{GEN} does not clutter the stack. Thus, if your computation is small
        !           571: enough (i.e.~you call few PARI routines, or most of them return \kbd{long}
        !           572: integers), then you don't need to do any garbage collecting. This will probably
        !           573: be the case in many of your subroutines. Of course the objects that were on
        !           574: the stack {\it before\/} the function call are left alone. Except for the ones
        !           575: listed below, PARI functions only collect their own garbage.
        !           576:
        !           577: \noindent$\bullet$
        !           578: It may happen that all objects that were created after a certain point can
        !           579: be deleted~--- for instance, if the final result you need is not a
        !           580: \kbd{GEN}, or if some search proved futile. Then, it is enough to record
        !           581: the value of \kbd{avma} just {\it before\/} the first garbage is created,
        !           582: and restore it upon exit:
        !           583:
        !           584: \bprog
        !           585: ulong ltop = avma; /*@Ccom record initial avma */
        !           586:
        !           587: garbage ...
        !           588: avma = ltop; /*@Ccom restore it */
        !           589: @eprog
        !           590: \noindent All objects created in the \kbd{garbage} zone will eventually
        !           591: be overwritten: they should not be accessed anymore once \kbd{avma} has been
        !           592: restored.
        !           593:
        !           594: \noindent$\bullet$
        !           595: If you want to destroy (i.e.~give back the memory occupied by) the
        !           596: latest PARI object on the stack (e.g.~the latest one obtained from a function
        !           597: call), and the above method is not available (because the initial value of
        !           598: \kbd{avma} has been lost), just use the function\sidx{destruction}%
        !           599: \vadjust{\penalty500}%discourage page break
        !           600:
        !           601: \fun{void}{cgiv}{GEN z}
        !           602:
        !           603: \noindent where \kbd{z} is the object you want to give back.
        !           604:
        !           605: \noindent$\bullet$
        !           606: Unfortunately life is not so simple, and sometimes you will want
        !           607: to give back accumulated garbage {\it during\/} a computation without losing
        !           608: recent data. For this you need the \kbd{gerepile} function (or one of its
        !           609: variants described hereafter):
        !           610:
        !           611: \fun{GEN}{gerepile}{ulong ltop, ulong lbot, GEN q}
        !           612:
        !           613: \noindent
        !           614: This function cleans up the stack between \kbd{ltop} and \kbd{lbot}, where
        !           615: $\kbd{lbot} < \kbd{ltop}$, and returns the updated object \kbd{q}. This means:
        !           616:
        !           617: 1) we translate (copy) all the objects in the interval
        !           618: $[\kbd{avma}, \kbd{lbot}[$, so that its right extremity abuts the address
        !           619: \kbd{ltop}. Graphically
        !           620:
        !           621: \vbox{\bprog
        !           622:              bot           avma   lbot          ltop     top
        !           623: End of stack  |-------------[++++++[-/-/-/-/-/-/-|++++++++|  Start
        !           624:                 free memory            garbage
        !           625: @eprog
        !           626: \noindent becomes:
        !           627: \bprog
        !           628:              bot                         avma   ltop     top
        !           629: End of stack  |---------------------------[++++++[++++++++|  Start
        !           630:                        free memory
        !           631: @eprog
        !           632: }
        !           633: \noindent where \kbd{++} denote significant objects, \kbd{--} the unused part
        !           634: of the stack, and \kbd{-/-} the garbage we remove.
        !           635:
        !           636: 2) The function then inspects all the PARI objects between \kbd{avma} and
        !           637: \kbd{lbot} (i.e.~the ones that we want to keep and that have been translated)
        !           638: and looks at every component of such an object which is not a codeword. Each
        !           639: such component is a pointer to an object whose address is either
        !           640:
        !           641: --- between \kbd{avma} and \kbd{lbot}, in which case it will be suitably
        !           642: updated,
        !           643:
        !           644: --- larger than or equal to \kbd{ltop}, in which case it will not change, or
        !           645:
        !           646: --- between \kbd{lbot} and \kbd{ltop} in which case \kbd{gerepile} will
        !           647: scream an error message at you (``significant pointers lost in gerepile'').
        !           648:
        !           649: 3) \key{avma} is updated (we add $\kbd{ltop} - \kbd{lbot}$ to the old value).
        !           650:
        !           651: 4) We return the (possibly updated) object \kbd{q}: if \kbd{q} initially
        !           652: pointed between \kbd{avma} and \kbd{lbot}, we return the translated
        !           653: address, as in~2). If not, the original address is still valid (and we return
        !           654: it!).
        !           655:
        !           656: As stated above, no component of the remaining objects (in particular
        !           657: \kbd{q}) should belong to the erased segment [\kbd{lbot}, \kbd{ltop}[, and
        !           658: this is checked within \kbd{gerepile}. But beware as well that the addresses
        !           659: of all the objects in the translated zone will have changed after a call to
        !           660: \kbd{gerepile}: every pointer you may have kept around elsewhere, outside the
        !           661: stack objects, which previously pointed into the zone below \kbd{ltop}
        !           662: must be discarded. If you need to recover more than one object, use one of
        !           663: the \kbd{gerepilemany} functions below.
        !           664:
        !           665: As a consequence of the preceding explanation, we must now state the most
        !           666: important law about programming in PARI:
        !           667:
        !           668: {\bf If a given PARI object is to be relocated by \hbox{gerepile} then,
        !           669: apart from universal objects, the chunks of memory used by its components
        !           670: should be in consecutive memory locations}. All \kbd{GEN}s created by
        !           671: documented PARI function are guaranteed to satisfy this.
        !           672:
        !           673: This is because the \kbd{gerepile} function knows only about {\it two
        !           674: connected zones\/}: the garbage that will be erased (between \kbd{lbot} and
        !           675: \kbd{ltop}) and the  significant pointers that will be copied and updated.
        !           676: If there is garbage interspersed with your objects, disasters will occur when
        !           677: we try to update them and consider the corresponding ``pointers''. So be
        !           678: {\it very\/} wary when you allow objects to become disconnected. Have a look
        !           679: at the examples, it's not as complicated as it seems.
        !           680:
        !           681: \noindent In practice this is achieved by the following programming idiom:
        !           682: \bprog
        !           683:   ltop=avma; garbage(); lbot=avma; q=anything();
        !           684:   return gerepile(ltop, lbot, q); /*@Ccom returns the updated q */
        !           685: @eprog
        !           686:
        !           687: \noindent Beware that
        !           688: \bprog
        !           689:   ltop=avma; garbage();
        !           690:   return gerepile(ltop, avma, anything())
        !           691: @eprog
        !           692:
        !           693: \noindent might work, but should be frowned upon. We can't predict whether
        !           694: \kbd{avma} is going to be evaluated after or before the call to
        !           695: \kbd{anything()}: it depends on the compiler. If we are out of luck, it will
        !           696: be {\it after\/} the call, so the result will belong to the garbage zone and
        !           697: the \kbd{gerepile} statement becomes equivalent to \kbd{avma = ltop}. Thus we
        !           698: would return a pointer to random garbage.
        !           699:
        !           700: \noindent$\bullet$ A simple variant is
        !           701:
        !           702: \fun{GEN}{gerepileupto}{ulong ltop, GEN q}
        !           703:
        !           704: \noindent which cleans the stack between \kbd{ltop} and the {\it connected\/}
        !           705: object \kbd{q} and returns \kbd{q} updated. For this to work, \kbd{q} must
        !           706: have been created {\it before\/} all its components, otherwise they would
        !           707: belong to the garbage zone! Documented PARI functions guarantee this. If you
        !           708: stumble upon one that does not, consider it a bug worth reporting.
        !           709:
        !           710: \noindent$\bullet$ Another variant (a special case of \tet{gerepilemany}
        !           711: below, where $n=1$) is
        !           712:
        !           713: \fun{GEN}{gerepilecopy}{ulong ltop, GEN x)}
        !           714:
        !           715: \noindent which is functionnally equivalent to \kbd{gerepileupto(ltop,
        !           716: gcopy(x))} but more efficient. In this case, the \kbd{GEN} parameter \kbd{x}
        !           717: need not satisfy any property before the garbage collection (it may be
        !           718: disconnected, components created before the root and so on). Of course, this
        !           719: is less efficient than either \tet{gerepileupto} or \tet{gerepile}, because
        !           720: \kbd{x} has to be copied to a clean stack zone first.
        !           721:
        !           722: \noindent$\bullet$
        !           723: To cope with complicated cases where many objects have to be
        !           724: preserved, you can use
        !           725:
        !           726: \fun{void}{gerepilemany}{ulong ltop, GEN *gptr[], long n)}
        !           727:
        !           728: \noindent which cleans up the most recent part of the stack (between
        !           729: \kbd{ltop} and \kbd{avma}). All the \kbd{GEN}s pointed at by the elements of
        !           730: the array \kbd{gptr} (of length \kbd{n}) are updated. A copy is done just
        !           731: before the cleaning to preserve them, so they don't need to be connected
        !           732: before the call. With \kbd{gerepilecopy}, this is the most robust of the
        !           733: \kbd{gerepile} functions (the less prone to user error), but also the
        !           734: slowest.
        !           735:
        !           736: \noindent$\bullet$ More efficient, but tricky to use is
        !           737:
        !           738: \fun{void}{gerepilemanysp}{ulong ltop, ulong lbot, GEN *gptr[], long n}
        !           739:
        !           740: \noindent which cleans the stack between \kbd{lbot} and \kbd{ltop} and
        !           741: updates the \kbd{GEN}s pointed at by the elements of \kbd{gptr} without doing
        !           742: any copying. This is subject to the same restrictions as \kbd{gerepile}, the
        !           743: only difference being that more than one address gets updated.
        !           744:
        !           745: \subsec{Examples}.
        !           746:
        !           747: \noindent
        !           748: Let \kbd{x} and \kbd{y} be two preexisting PARI objects and suppose that we
        !           749: want to compute $\kbd{x}^2+ \kbd{y}^2$. This can trivially be done using the
        !           750: following program (we skip the necessary declarations; everything in sight is
        !           751: a \kbd{GEN}):
        !           752: \bprog
        !           753: p1 = gsqr(x);
        !           754: p2 = gsqr(y); z = gadd(p1,p2);
        !           755: @eprog\noindent
        !           756: The \kbd{GEN} \kbd{z} indeed points at the desired quantity. However,
        !           757: consider the stack: it contains as unnecessary garbage \kbd{p1} and \kbd{p2}.
        !           758: More precisely it contains (in this order) \kbd{z}, \kbd{p2}, \kbd{p1}
        !           759: (recall that, since the stack grows downward from the top, the most recent
        !           760: object comes first). We need a way to get rid of this garbage (in this case
        !           761: it causes no harm except that it occupies memory space, but in other cases
        !           762: it could disconnect other PARI objects and this is dangerous).
        !           763:
        !           764: It would not have been possible to get rid of \kbd{p1}, \kbd{p2} before
        !           765: \kbd{z} is computed, since they are used in the final operation. We cannot
        !           766: record \kbd{avma} before \kbd{p1} is computed and restore it later, since
        !           767: this would destroy \kbd{z} as well. It is not possible either to use the
        !           768: function \kbd{cgiv} since \kbd{p1} and \kbd{p2} are not at the bottom of the
        !           769: stack and we don't want to give back~\kbd{z}.
        !           770:
        !           771: But using \kbd{gerepile}, we can give back the memory locations corresponding
        !           772: to \kbd{p1}, \kbd{p2}, and move the object \kbd{z} upwards so that no
        !           773: space is lost. Specifically:
        !           774: \bprog
        !           775:   ltop = avma; /*@Ccom remember the current address of the top of the stack */
        !           776:   p1 = gsqr(x); p2 = gsqr(y);
        !           777:   lbot = avma; /*@Ccom keep the address of the bottom of the garbage pile */
        !           778:   z = gadd(p1, p2); /*@Ccom z is now the last object on the stack */
        !           779:   z = gerepile(ltop, lbot, z); /*@Ccom garbage collecting */
        !           780: @eprog
        !           781: \noindent Of course, the last two instructions could also have been
        !           782: written more simply:
        !           783:
        !           784: \kbd{z = gerepile(ltop, lbot, gadd(p1,p2));}
        !           785:
        !           786: \noindent In fact \kbd{gerepileupto} is even simpler to use, because the
        !           787: result of \kbd{gadd} will be the last object on the stack and \kbd{gadd} is
        !           788: guaranteed to return an object suitable for \kbd{gerepileupto}:
        !           789: \bprog
        !           790:   ltop = avma;
        !           791:   z = gerepileupto(ltop, gadd(gsqr(x), gsqr(y)));
        !           792: @eprog
        !           793: \noindent
        !           794: As you can see, in simple conditions the use of \kbd{gerepile} is not really
        !           795: difficult. However make sure you understand exactly what has happened before
        !           796: you go on (use the figure from the preceding section).
        !           797:
        !           798: \misctitle{Important remark}: as we will see presently it is often
        !           799: necessary to do several \kbd{gerepile}s during a computation. However, the
        !           800: fewer the better.  The only condition for \kbd{gerepile} to work is that the
        !           801: garbage be connected. If the computation can be arranged so that there is a
        !           802: minimal number of connected pieces of garbage, then it should be done that
        !           803: way.
        !           804:
        !           805: For example suppose we want to write a function of two \kbd{GEN} variables
        !           806: \kbd{x} and \kbd{y} which creates the vector $\kbd{[x}^2+\kbd{y},
        !           807: \kbd{y}^2+\kbd{x]}$. Without garbage collecting, one would write:
        !           808: %
        !           809: \bprog
        !           810:   p1 = gsqr(x); p2 = gadd(p1, y);
        !           811:   p3 = gsqr(y); p4 = gadd(p3, x);
        !           812:   z = cgetg(3,t_VEC);
        !           813:   z[1] = (long)p2;
        !           814:   z[2] = (long)p4;
        !           815: @eprog
        !           816: \noindent
        !           817: This leaves a dirty stack containing (in this order) \kbd{z}, \kbd{p4},
        !           818: \kbd{p3}, \kbd{p2}, \kbd{p1}. The garbage here consists of \kbd{p1} and
        !           819: \kbd{p3}, which are separated by \kbd{p2}. But if we compute \kbd{p3}
        !           820: {\it before\/} \kbd{p2} then the garbage becomes connected, and we get the
        !           821: following program with garbage collecting:
        !           822: %
        !           823: \bprog
        !           824:   ltop = avma; p1 = gsqr(x); p3 = gsqr(y); lbot = avma;
        !           825:   z = cgetg(3,t_VEC);
        !           826:   z[1] = ladd(p1,y);
        !           827:   z[2] = ladd(p3,x);
        !           828:   z = gerepile(ltop,lbot,z);
        !           829: @eprog
        !           830:
        !           831: \noindent Finishing by \kbd{z = gerepileupto(ltop, z)} would be ok as well.
        !           832: But when you have the choice, it's usually clearer to brace the garbage
        !           833: between \kbd{ltop}~/ \kbd{lbot} pairs.
        !           834:
        !           835: \noindent Beware that
        !           836: \bprog
        !           837:   ltop = avma; p1 = gadd(gsqr(x), y); p3 = gadd(gsqr(y), x);
        !           838:   z = cgetg(3,t_VEC);
        !           839:   z[1] = (long)p1;
        !           840:   z[2] = (long)p3
        !           841:   z = gerepileupto(ltop,z); /*@Ccom WRONG !!! */
        !           842: @eprog
        !           843: \noindent would be a disaster since \kbd{p1} and \kbd{p3} would be created
        !           844: before \kbd{z}, so the call to \kbd{gerepileupto} would overwrite them,
        !           845: leaving \kbd{z[1]} and \kbd{z[2]} pointing at random data!
        !           846:
        !           847: We next want to write a program to compute the product of two complex numbers
        !           848: $x$ and $y$, using a method which takes only 3 multiplications instead of 4.
        !           849: Let $z = x*y$, and set $x = x_r + i*x_i$ and similarly for $y$ and $z$. The
        !           850: well-known trick is to compute $p_1 = x_r*y_r$, $p_2=x_i*y_i$,
        !           851: $p_3=(x_r+x_i)*(y_r+y_i)$, and then we have $z_r=p_1-p_2$,
        !           852: $z_i=p_3-(p_1+p_2)$. The program is essentially as follows:
        !           853: %
        !           854: \bprog
        !           855: ltop = avma;
        !           856: p1 = gmul(x[1],y[1]);
        !           857: p2 = gmul(x[2],y[2]);
        !           858: p3 = gmul(gadd(x[1],x[2]), gadd(y[1],y[2]));
        !           859: p4 = gadd(p1,p2); lbot = avma;
        !           860: z = cgetg(3,t_COMPLEX);
        !           861: z[1] = lsub(p1,p2);
        !           862: z[2] = lsub(p3,p4);
        !           863: z = gerepile(ltop,lbot,z);
        !           864: @eprog
        !           865: \noindent
        !           866: ``Essentially'', because for instance \kbd{x[1]} is a \kbd{long} and not a
        !           867: \kbd{GEN}, so we need to insert many annoying typecasts:
        !           868: \kbd{p1 = gmul((GEN)x[1], (GEN)y[1])} and so on.
        !           869:
        !           870: Let us now look at a less trivial example where more than one \kbd{gerepile}
        !           871: is needed in practice (at the expense of efficiency, one can always use only
        !           872: one using \kbd{gerepilecopy}). Suppose that we want to write a function
        !           873: which multiplies a line vector by a matrix (such a function is of course
        !           874: already part of \kbd{gmul}, but let's ignore this for a moment). Then the
        !           875: most natural way is to do a \kbd{cgetg} of the result immediately, and then a
        !           876: \kbd{gerepile} for each coefficient of the result vector to get rid of the
        !           877: garbage which has accumulated while this particular coefficient was computed.
        !           878: We leave the details to the reader, who can look at the answer in the file
        !           879: \kbd{basemath/gen1.c}, in the function \kbd{gmul}, case \typ{VEC} times case
        !           880: \typ{MAT}. It would theoretically be possible to have a single connected
        !           881: piece of garbage, but it would be a much less natural and unnecessarily
        !           882: complicated program, which would in fact be slower.
        !           883:
        !           884: Let us now take an example which is probably the least trivial way of using
        !           885: \kbd{gerepile}, but is unfortunately sometimes necessary. Although it is not
        !           886: an infrequent occurrence, we will not give a specific example but a general
        !           887: one: suppose that we want to do a computation (usually inside a larger
        !           888: function) producing more than one PARI object as a result, say two for
        !           889: instance. Then even if we set up the work properly, before cleaning up we
        !           890: will have a stack which has the desired results \kbd{z1}, \kbd{z2} (say),
        !           891: and then connected garbage from lbot to ltop. If we write
        !           892:
        !           893: \kbd{z1 = gerepile(ltop,lbot,z1);}
        !           894:
        !           895: \noindent
        !           896: then the stack will be cleaned, the pointers fixed up, but we will have lost
        !           897: the address of \kbd{z2}. This is where we need one of the \idx{gerepilemany}
        !           898: functions: we declare
        !           899: \bprog
        !           900:   GEN *gptr[2]; /*@Ccom Array of pointers to GENs */
        !           901:   gptr[0] = &z1; gptr[1] = &z2;
        !           902: @eprog
        !           903: \noindent and now the call \kbd{gerepilemany(ltop, gptr, 2)} copies \kbd{z1}
        !           904: and \kbd{z2} to new locations, cleans the stack from \kbd{ltop} to the old
        !           905: \kbd{avma}, and updates the pointers \kbd{z1} and \kbd{z2}. Here we don't
        !           906: assume anything about the stack: the garbage can be disconnected and
        !           907: \kbd{z1}, \kbd{z2} need not be at the bottom of the stack. If all of these
        !           908: assumptions are in fact satisfied, then we can call \kbd{gerepilemanysp}
        !           909: instead, which will usually be faster since we don't need the initial copy
        !           910: (on the other hand, it is less cache friendly).
        !           911:
        !           912: Another important usage is ``random'' garbage collection during loops
        !           913: whose size requirements we cannot (or don't bother to) control in advance:
        !           914: \bprog
        !           915:   ulong ltop = avma, limit = (avma+bot)/2;
        !           916:   GEN x, y;
        !           917:
        !           918:   while (...)
        !           919:   {
        !           920:     garbage(); x = anything();
        !           921:     garbage(); y = anything()
        !           922:     garbage();
        !           923:     if (avma < limit) /*@Ccom memory is running low (half spent since entry) */
        !           924:     {
        !           925:        GEN *gptr[2];
        !           926:        gptr[0] = &x; gptr[1] = &y;
        !           927:        gerepilemany(ltop, gptr, 2);
        !           928:     }
        !           929:   }
        !           930: @eprog
        !           931: \noindent Here we assume that only \kbd{x} and \kbd{y} are needed from one
        !           932: iteration to the next. As it would be too costly to call gerepile once for
        !           933: each iteration, we only do it when it seems to have become necessary. Of
        !           934: course, when the need arises, you can use bigger \kbd{gptr} arrays: in the
        !           935: PARI library source code, we once needed to preserve up to 10 objects at a
        !           936: time (in a variant of the LLL algorithm)!
        !           937:
        !           938: \misctitle{Technical note:} the statement \kbd{limit = (avma+bot)/2} is
        !           939: dangerous since the addition can overflow, which would result in \kbd{limit}
        !           940: being always smaller than \kbd{avma}. This will prevent garbage collection in
        !           941: the loop. To avoid this problem, we provide a robust macro
        !           942: \tet{stack_lim}\kbd{(avma,$n$)}, which denotes an address where $2^{n-1} /
        !           943: (2^{n-1}+1)$ of the total stack space is exhausted ($1/2$ for $n=1$, $2/3$
        !           944: for $n=2$). Hence, the above snippet should be written as
        !           945:
        !           946: \bprog
        !           947:   ulong ltop = avma, limit = stack_lim(avma,1);
        !           948:   @dots
        !           949: @eprog
        !           950:
        !           951: \subsec{Some hints and tricks}. In this section, we give some indications
        !           952: on how to avoid most problems connected with garbage collecting:
        !           953:
        !           954: First, although it looks complicated, \kbd{gerepile} has turned out to be a
        !           955: very flexible and fast garbage collector, which compares very favorably
        !           956: with much more sophisticated methods used in other systems. A few tests that
        !           957: we have done indicate that the price paid for using \kbd{gerepile}, when
        !           958: properly used, is usually around 1 or 2 percents of the total running time,
        !           959: which is quite acceptable.
        !           960:
        !           961: Secondly, in many cases, in particular when the tree structure and the size of
        !           962: the PARI objects which will appear in a computation are under control, one
        !           963: can avoid \kbd{gerepile} altogether by creating sufficiently large objects at
        !           964: the beginning (using \teb{cgetg}), and then using assignment statements and
        !           965: operations ending with z (such as \teb{gaddz}). Coming back to our first
        !           966: example, note that if we know that x and y are of type real and of length
        !           967: less than or equal to 5, we can program without using \kbd{gerepile} at all:
        !           968:
        !           969: \bprog
        !           970:   z = cgetr(5); ltop = avma;
        !           971:   p1 = gsqr(x); p2 = gsqr(y); gaddz(p1,p2,z);
        !           972:   avma = ltop;
        !           973: @eprog
        !           974: \noindent This practice will usually be {\it slower\/} than a craftily used
        !           975: \kbd{gerepile} though, and is certainly more cumbersome to use. As a rule,
        !           976: assignment statements should generally be avoided.
        !           977: \smallskip
        !           978:
        !           979: Thirdly, the philosophy of \kbd{gerepile} is the following: keep the value of
        !           980: the stack pointer \kbd{avma} at the beginning, and just {\it before\/} the
        !           981: last operation.  Afterwards, it would be too late since the lower end address
        !           982: of the garbage zone would have been lost. Of course you can always use
        !           983: \kbd{gerepileupto}, but you will have to assume that the object was created
        !           984: {\it before\/} its components.
        !           985:
        !           986: Lastly, if all seems lost, just use \tet{gerepilecopy} (or
        !           987: \tet{gerepilemany}) to fix up the stack for you.
        !           988:
        !           989: \smallskip If you followed us this far, congratulations, and rejoice: the
        !           990: rest is much easier.
        !           991:
        !           992: \section{Implementation of the PARI types}
        !           993: \label{se:impl}
        !           994:
        !           995: \noindent
        !           996: Although it is a little tedious, we now go through each type and explain its
        !           997: implementation. Let \kbd{z} be a \kbd{GEN}, pointing at a PARI object. In
        !           998: the following paragraphs, we will constantly mix two points of view: on the
        !           999: one hand, \kbd{z} will be treated as the C pointer it is (in the context of
        !          1000: program fragments like \kbd{z[1]}), on the other, as PARI's handle on (the
        !          1001: internal representation of) some mathematical entity, so we will shamelessly
        !          1002: write $\kbd{z} \ne 0$ to indicate that the {\it value\/} thus represented
        !          1003: is nonzero (in which case the {\it pointer\/}~\kbd{z} certainly will be
        !          1004: non-\kbd{NULL}). We offer no apologies for this style. In fact, you had
        !          1005: better feel comfortable juggling both views simultaneously in your mind if
        !          1006: you want to write correct PARI programs.
        !          1007:
        !          1008: Common to all the types is the
        !          1009: first codeword \kbd{z[0]}, which we don't have to worry about since this is
        !          1010: taken care of by \kbd{cgetg}. Its precise structure will depend on the
        !          1011: machine you are using, but it always contain the following data: the
        !          1012: {\it internal \idx{type number}\/} associated to the symbolic type name, the
        !          1013: {\it\idx{length}\/} of the root in longwords, and a technical bit which
        !          1014: indicates whether the object is a clone (see below) or not. This last one is
        !          1015: used by GP for internal garbage collecting, you won't have to worry about it.
        !          1016:
        !          1017: \noindent These data can be handled through the following {\it macros\/}:
        !          1018:
        !          1019: \fun{long}{typ}{GEN z} returns the type number of \kbd{z}.
        !          1020:
        !          1021: \fun{void}{settyp}{GEN z, long n} sets the type number of \kbd{z} to
        !          1022: \kbd{n} (you should not have to use this function if you use \kbd{cgetg}).
        !          1023:
        !          1024: \fun{long}{lg}{GEN z} returns the length (in longwords) of the root of \kbd{z}.
        !          1025:
        !          1026: \fun{long}{setlg}{GEN z, long l} sets the length of \kbd{z} to \kbd{l} (you
        !          1027: should not have to use this function if you use \kbd{cgetg}; however, see
        !          1028: an advanced example in \secref{se:prog}).
        !          1029:
        !          1030: \noindent
        !          1031: (If you know enough about PARI to need to access the ``clone'' bit, then you'll
        !          1032: be able to find usage hints in the code (esp. \kbd{killbloc()} and
        !          1033: \kbd{matrix\_block()}). It {\it is\/} technical after all.)
        !          1034:
        !          1035: These macros are written in such a way that you don't need to worry about
        !          1036: type casts when using them: i.e.~if \kbd{z} is a \kbd{GEN}, \kbd{typ(z[2])}
        !          1037: will be accepted by your compiler, without your having to explicitly type
        !          1038: \kbd{typ((GEN)z[2])}. Note that for the sake of efficiency, none of the
        !          1039: codeword-handling macros check the types of their arguments even when there
        !          1040: are stringent restrictions on their use.
        !          1041:
        !          1042: The possible second codeword is used differently by the different types, and
        !          1043: we will describe it as we now consider each of them in turn:
        !          1044:
        !          1045:
        !          1046: \subsec{Type \typ{INT} (integer):}\sidx{integer}\kbdsidx{t_INT} this type has
        !          1047: a second codeword \kbd{z[1]} which contains the following information:
        !          1048:
        !          1049: the sign of \kbd{z}: coded as $1$, $0$ or $-1$ if $\kbd{z} > 0$, $\kbd{z} = 0$,
        !          1050: $\kbd{z} < 0$ respectively.
        !          1051:
        !          1052: the {\it effective length\/} of \kbd{z}, i.e.~the total number of significant
        !          1053: longwords. This means the following: apart from the integer 0, every integer
        !          1054: is ``normalized'', meaning that the first mantissa longword (i.e.~\kbd{z[2]})
        !          1055: is non-zero. However, the integer may have been created with a longer length.
        !          1056: Hence the ``length'' which is in \kbd{z[0]} can be larger than the
        !          1057: ``effective length'' which is in \kbd{z[1]}. Accessing \kbd{z[i]} for \kbd{i}
        !          1058: larger than or equal to the effective length will yield random results.
        !          1059:
        !          1060: \noindent This information is handled using the following macros:
        !          1061:
        !          1062: \fun{long}{signe}{GEN z} returns the sign of \kbd{z}.
        !          1063:
        !          1064: \fun{void}{setsigne}{GEN z, long s} sets the sign of \kbd{z} to \kbd{s}.
        !          1065:
        !          1066: \fun{long}{lgefint}{GEN z} returns the \idx{effective length} of \kbd{z}.
        !          1067:
        !          1068: \fun{void}{setlgefint}{GEN z, long l} sets the effective length
        !          1069: of \kbd{z} to \kbd{l}.
        !          1070:
        !          1071: The integer 0 can be recognized either by its sign being~0, or by its
        !          1072: effective length being equal to~2. When $\kbd{z} \ne 0$, the word
        !          1073: \kbd{z[2]} exists and is non-zero, and the absolute value of \kbd{z}
        !          1074: is (\kbd{z[2]},\kbd{z[3]},\dots,\kbd{z[lgefint(z)-1]}) in base
        !          1075: \kbd{2\pow BITS\_IN\_LONG}, where as usual in this notation \kbd{z[2]} is
        !          1076: the highest order longword.
        !          1077:
        !          1078: \noindent The following further macros are available:
        !          1079:
        !          1080: \fun{long}{mpodd}{GEN x} which is 1 if \kbd{x} is odd, and 0 otherwise.
        !          1081:
        !          1082: \fun{long}{mod2}{GEN x}, \fun{}{mod4}{x}, and so on up to \fun{}{mod64}{x},
        !          1083: which give the residue class of \kbd{x} modulo the corresponding power of
        !          1084: 2, for {\it positive\/}~\kbd{x} (you will obtain weird results if you use
        !          1085: these on the integer 0 or on negative numbers).
        !          1086:
        !          1087: These macros directly access the binary data and are thus much faster than
        !          1088: the generic modulo functions. Besides, they return long integers instead of
        !          1089: \kbd{GEN}s, so they don't clutter up the stack.
        !          1090:
        !          1091: \subsec{Type \typ{REAL} (real number):}\kbdsidx{t_REAL}\sidx{real number}
        !          1092: this type has a second codeword z[1] which also encodes its sign (obtained
        !          1093: or set using the same functions as for the integers), and a biased binary
        !          1094: exponent (i.e.~the actual exponent value plus some constant bias, actually
        !          1095: a power of~2, whose value is given by \kbd{HIGHEXPOBIT}). This exponent can
        !          1096: be handled using the following macros:
        !          1097:
        !          1098: \fun{long}{expo}{GEN z} returns the true (unbiased) exponent of \kbd{z}.
        !          1099: This is defined even when \kbd{z} is equal to zero, see
        !          1100: \secref{se:whatzero}.
        !          1101:
        !          1102: \fun{void}{setexpo}{GEN z, long e} sets the exponent of \kbd{z} to \kbd{e},
        !          1103: of course after adding the bias.
        !          1104:
        !          1105: \noindent Note the functions:
        !          1106:
        !          1107: \fun{long}{gexpo}{GEN z} which tries to return an exponent for \kbd{z},
        !          1108: even if \kbd{z} is not a real number.
        !          1109:
        !          1110: \fun{long}{gsigne}{GEN z} which returns a sign for \kbd{z}, even when
        !          1111: \kbd{z} is neither real nor integer (a rational number for instance).
        !          1112:
        !          1113: The real zero is characterized by having its sign equal to 0. However,
        !          1114: usually the first mantissa word \kbd{z[2]} is defined and equal to~0. This
        !          1115: fact must {\it never\/} be used to recognize a real~0. If \kbd{z} is not
        !          1116: equal to~0, the first mantissa word \kbd{z[2]} is normalized, i.e.~its most
        !          1117: significant bit is~1. The mantissa is (\kbd{z[2]},\kbd{z[3]},\dots,%
        !          1118: \kbd{z[lg(z]-1]}) in base \kbd{2\pow BITS\_IN\_LONG}. Here, \kbd{z[2]} is
        !          1119: the most significant longword, and the mantissa takes values between
        !          1120: 1 (included) and 2 (excluded). Thus, assume that \kbd{sizeof(long)} is 32 and
        !          1121: the length is 4, the real number $3.5$ is represented as \kbd{z[0]} (encoding
        !          1122: $\kbd{type} = \typ{REAL}$, $\kbd{lg} = 4$), \kbd{z[1]} (encoding $\kbd{sign} =
        !          1123: 1$, $\kbd{expo} = 1$), $\kbd{z[2]} = \kbd{0xe0000000}$,
        !          1124: $\kbd{z[3]} = \kbd{0x0}$.
        !          1125:
        !          1126: \subsec{Type \typ{INTMOD} (integermod):}\kbdsidx{t_INTMOD}\sidx{integermod}
        !          1127: \kbd{z[1]} points to the modulus, and \kbd{z[2]} at the number representing
        !          1128: the class \kbd{z}. Both are separate \kbd{GEN} objects, and both must be of
        !          1129: type integer, satisfying the inequality $0 \le \kbd{z[2]} < \kbd{z[1]}$.
        !          1130:
        !          1131: It is good practice to keep the modulus object on the heap, so that new
        !          1132: integermods resulting from operations can point at this common object,
        !          1133: instead of carrying along their own copies of it on the stack. The library
        !          1134: functions implement this practice almost by default.
        !          1135:
        !          1136: \subsec{Type \typ{FRAC} and \typ{FRACN} (rational number):}%
        !          1137: \kbdsidx{t_FRAC}\kbdsidx{t_FRACN}\sidx{rational number}
        !          1138: \kbd{z[1]} points to the numerator, and \kbd{z[2]} to the denominator. Both
        !          1139: must be of type integer. In principle $\kbd{z[2]} > 0$, but this rule does not
        !          1140: have to be strictly obeyed. Note that a type \typ{FRACN} rational number can be
        !          1141: converted to irreducible form using the function \fun{GEN}{gred}{GEN x}.
        !          1142:
        !          1143: \subsec{Type \typ{COMPLEX} (complex number):}%
        !          1144: \kbdsidx{t_COMPLEX}\sidx{complex number}
        !          1145: \kbd{z[1]} points to the real part, and \kbd{z[2]} to the imaginary part. A
        !          1146: priori \kbd{z[1]} and \kbd{z[2]} can be of any type, but only certain types
        !          1147: are useful and make sense.
        !          1148:
        !          1149: \subsec{Type \typ{PADIC} ($p$-adic numbers):}%
        !          1150: \sidx{p-adic number}\kbdsidx{t_PADIC} this type has a second codeword
        !          1151: \kbd{[1]} which contains the following information: the $p$-adic precision
        !          1152: (the exponent of $p$ modulo which the $p$-adic unit corresponding to
        !          1153: \kbd{z} is defined if \kbd{z} is not~0), i.e.~one less than the number of
        !          1154: significant $p$-adic digits, and the biased exponent of \kbd{z} (the bias
        !          1155: being equal to \kbd{HIGHVALPBIT} here). This information can be handled
        !          1156: using the following functions:
        !          1157:
        !          1158: \fun{long}{precp}{GEN z} returns the $p$-adic precision of \kbd{z}.
        !          1159:
        !          1160: \fun{void}{setprecp}{GEN z, long l} sets the $p$-adic precision of \kbd{z}
        !          1161: to \kbd{l}.
        !          1162:
        !          1163: \fun{long}{valp}{GEN z} returns the $p$-adic valuation of \kbd{z} (i.e. the
        !          1164: unbiased exponent). This is defined even if \kbd{z} is equal to~0, see
        !          1165: \secref{se:whatzero}.
        !          1166:
        !          1167: \fun{void}{setvalp}{GEN z, long e} sets the $p$-adic valuation of \kbd{z}
        !          1168: to \kbd{e}.
        !          1169:
        !          1170: In addition to this codeword, \kbd{z[2]} points to the prime $p$,
        !          1171: \kbd{z[3]} points to $p^{\text{precp(z)}}$, and \kbd{z[4]} points to an
        !          1172: integer representing the $p$-adic unit associated to \kbd{z} modulo
        !          1173: \kbd{z[3]} (and points to zero if \kbd{z} is zero). To summarize, if $z\neq
        !          1174: 0$, we have the equality:
        !          1175: $$ \kbd{z} = p^{\text{valp(z)}} * (\kbd{z[4]} + O(\kbd{z[3]})) =
        !          1176:      p^{\text{valp(z)}} * (\kbd{z[4]} + O(p^{\text{precp(z)}})) $$
        !          1177:
        !          1178: \subsec{Type \typ{QUAD} (quadratic number):}\sidx{quadratic
        !          1179: number}\kbdsidx{t_QUAD} \kbd{z[1]} points to the polynomial defining the
        !          1180: quadratic field, \kbd{z[2]} to the ``real part'' and \kbd{z[3]} to the
        !          1181: ``imaginary part'', which are to be taken as the coefficients of \kbd{z}
        !          1182: with respect to the ``canonical'' basis $(1,w)$, see~\secref{se:compquad}.
        !          1183: Complex numbers are a particular case of quadratics but deserve a separate
        !          1184: type.
        !          1185:
        !          1186: \subsec{Type \typ{POLMOD} (polmod):}\kbdsidx{t_POLMOD}\sidx{polmod} exactly as
        !          1187: for integermods, \kbd{z[1]} points to the modulus, and \kbd{z[2]} to a
        !          1188: polynomial representing the class of~\kbd{z}. Both must be of type
        !          1189: \typ{POL} in the same variable. However, \kbd{z[2]} is allowed to be a
        !          1190: simplification of such a polynomial, e.g a scalar. This is quite tricky
        !          1191: considering the hierarchical structure of the variables; in particular, a
        !          1192: polynomial in variable of \var{lesser} priority than the modulus variable
        !          1193: is valid, since it can be considered as the constant term of a polynomial
        !          1194: of degree 0 in the correct variable. On the other hand a variable of
        !          1195: \var{greater} priority would not be acceptable.
        !          1196:
        !          1197: \subsec{Type \typ{POL} (polynomial):}\kbdsidx{t_POL}\sidx{polynomial} this
        !          1198: type has a second codeword which is analogous to the one for integers. It
        !          1199: contains a ``{\it sign\/}'': 0 if the polynomial is equal to~0, and 1 if
        !          1200: not (see however the important remark below), a {\it variable number\/}
        !          1201: (e.g.~0 for $x$, 1 for $y$, etc\dots), and an {\it effective length}.
        !          1202:
        !          1203: \noindent These data can be handled with the following macros:
        !          1204:
        !          1205: \teb{signe} and \teb{setsigne} as for reals and integers.
        !          1206:
        !          1207: \fun{long}{lgef}{GEN z} returns the \idx{effective length} of \kbd{z}.
        !          1208:
        !          1209: \fun{void}{setlgef}{GEN z, long l} sets the effective length of \kbd{z} to
        !          1210: \kbd{l}.
        !          1211:
        !          1212: \fun{long}{varn}{GEN z} returns the variable number of the object \kbd{z}.
        !          1213:
        !          1214: \fun{void}{setvarn}{GEN z, long v} sets the variable number of \kbd{z} to
        !          1215: \kbd{v}.
        !          1216:
        !          1217: Note also the function \fun{long}{gvar}{GEN z} which tries to return a
        !          1218: \idx{variable number} for \kbd{z}, even if \kbd{z} is not a polynomial or
        !          1219: power series. The variable number of a scalar type is set by definition
        !          1220: equal to \tet{BIGINT}.
        !          1221:
        !          1222: The components \kbd{z[2]}, \kbd{z[3]},\dots \kbd{z[lgef(z)-1]} point to the
        !          1223: coefficients of the polynomial {\it in ascending order}, with \kbd{z[2]}
        !          1224: being the constant term and so on. Note that the {\it \idx{degree}\/} of the
        !          1225: polynomial is equal to its effective length minus three. The function
        !          1226:
        !          1227: \fun{long}{degree}{GEN x} returns the degree of \kbd{x} with respect to its
        !          1228: main variable even when \kbd{x} is not a polynomial (a rational function
        !          1229: for instance). By convention, the degree of $0$ is~$-1$.
        !          1230:
        !          1231: \misctitle{Important remark}. A zero polynomial can be characterized by the
        !          1232: fact that its sign is~0. However, its effective length may be equal to 2, or
        !          1233: greater than 2. If it is greater than 2, this means that all the coefficients
        !          1234: of the polynomial are equal to zero (as they should for a zero polynomial),
        !          1235: but not all of these zeros are exact zeros, and more precisely the leading
        !          1236: term \kbd{z[lgef(z)-1]} is not an exact zero.
        !          1237:
        !          1238: \subsec{Type \typ{SER} (power series):}\kbdsidx{t_SER}\sidx{power series} This
        !          1239: type also has a second codeword, which encodes a ``{\it sign\/}'', i.e.~0
        !          1240: if the power series is 0, and 1 if not, a {\it variable number\/} as for
        !          1241: polynomials, and a {\it biased exponent\/} with a bias of
        !          1242: \kbd{HIGHVALPBIT}. This information can be handled with the following
        !          1243: functions: \teb{signe}, \teb{setsigne}, \teb{varn}, \teb{setvarn} as for
        !          1244: polynomials, and \teb{valp}, \teb{setvalp} for the exponent as for $p$-adic
        !          1245: numbers. Beware: do {\it not\/} use \teb{expo} and \teb{setexpo} on power
        !          1246: series.
        !          1247:
        !          1248: If the power series is non-zero, \kbd{z[2]}, \kbd{z[3]},\dots
        !          1249: \kbd{z[lg(z)-1]} point to the coefficients of \kbd{z} in ascending order,
        !          1250: \kbd{z[2]} being the first non-zero coefficient.  Note that the exponent of a
        !          1251: power series can be negative, i.e.~we are then dealing with a Laurent series
        !          1252: (with a finite number of negative terms).
        !          1253:
        !          1254: \subsec{Type \typ{RFRAC} and \typ{RFRACN} (rational function):}%
        !          1255: \kbdsidx{t_RFRAC}\kbdsidx{t_RFRACN}\sidx{rational function}
        !          1256: \kbd{z[1]} points to the numerator, and \kbd{z[2]} on the denominator. The
        !          1257: denominator must be of type polynomial. Note that a type \typ{RFRACN}
        !          1258: rational function can be converted to irreducible form using the function
        !          1259: \teb{gred}.
        !          1260:
        !          1261: \subsec{Type \typ{QFR} (indefinite binary quadratic form):}%
        !          1262: \kbdsidx{t_QFR}\sidx{indefinite binary quadratic form}
        !          1263: \kbd{z[1]}, \kbd{z[2]}, \kbd{z[3]} point to the three coefficients of the
        !          1264: form and should be of type integer. \kbd{z[4]} is Shanks's distance
        !          1265: function, and should be of type real.
        !          1266:
        !          1267: \subsec{Type \typ{QFI} (definite binary quadratic form):}%
        !          1268: \kbdsidx{t_QFI}\sidx{definite binary quadratic form}
        !          1269: \kbd{z[1]}, \kbd{z[2]}, \kbd{z[3]} point to the three coefficients of the
        !          1270: form. All three should be of type integer.
        !          1271:
        !          1272: \subsec{Type \typ{VEC} and \typ{COL} (vector):}%
        !          1273: \kbdsidx{t_VEC}\kbdsidx{t_COL}\sidx{row vector}\sidx{column vector}
        !          1274: \kbd{z[1]}, \kbd{z[2]},\dots \kbd{z[lg(z)-1]} point to the components of
        !          1275: the vector.
        !          1276:
        !          1277: \subsec{Type \typ{MAT} (matrix):}\kbdsidx{t_MAT}\sidx{matrix}
        !          1278: \kbd{z[1]}, \kbd{z[2]},\dots \kbd{z[lg(z)-1]} point to the column vectors
        !          1279: of \kbd{z}, i.e.~they must be of type \typ{COL} and of the same length.
        !          1280:
        !          1281: \noindent The last two were introduced for specific GP use, and you'll be
        !          1282: much better off using the standard malloc'ed C constructs when programming
        !          1283: in library mode. We quote them just for completeness (advising you not to
        !          1284: use them):
        !          1285:
        !          1286: \subsec{Type \typ{LIST} (list):}\kbdsidx{t_LIST}\sidx{list}
        !          1287: This one has a second codeword which contains an effective length (handled
        !          1288: through \teb{lgef}~/ \teb{setlgef}). \kbd{z[2]},\dots, \kbd{z[lgef(z)-1]}
        !          1289: contain the components of the list.
        !          1290:
        !          1291: \subsec{Type \typ{STR} (character string):}%
        !          1292: \kbdsidx{t_STR}\sidx{character string}
        !          1293: \fun{char *}{GSTR}{z} (= \kbd{(z+1)}) points to the first character of the
        !          1294: (\kbd{NULL}-terminated) string.
        !          1295:
        !          1296: \section{PARI variables}\label{se:vars}
        !          1297: \subsec{Multivariate objects}
        !          1298:
        !          1299: \noindent
        !          1300: We now consider variables and formal computations. As we have seen in
        !          1301: \secref{se:impl}, the codewords for types \typ{POL} and \typ{SER}
        !          1302: encode a ``variable number''. This is an integer, ranging from $0$ to
        !          1303: \kbd{MAXVARN}. The lower it is, the higher the variable priority. PARI does
        !          1304: not know anything about intelligent ``sparse'' representation of polynomials.
        !          1305: So a multivariate polynomial in PARI is just a polynomial (in one variable),
        !          1306: whose coefficients are themselves (arbitrary) polynomials. All computations
        !          1307: are then just done formally on the coefficients as if the polynomial was
        !          1308: univariate.
        !          1309:
        !          1310: In fact, the way an object will be considered in formal computations depends
        !          1311: entirely on its ``principal variable number'' which is given by the function
        !          1312:
        !          1313: \fun{long}{gvar}{GEN z}
        !          1314:
        !          1315: \noindent which returns a \idx{variable number} for \kbd{z}, even if \kbd{z}
        !          1316: is not a polynomial or power series. The variable number of a scalar type is
        !          1317: set by definition equal to \tet{BIGINT} which is bigger than any legal
        !          1318: variable number. The variable number of a recursive type which is not a
        !          1319: polynomial or power series is the minimal variable number of its components.
        !          1320: But for polynomials and power series only the ``outermost'' number counts:
        !          1321: the representation is not symmetrical at all.
        !          1322:
        !          1323: Under GP, one need not worry too much since the interpreter will define
        !          1324: the variables as it sees them and do the right thing with the polynomials
        !          1325: produced (however, have a look at the remark in \secref{se:rempolmod}). But
        !          1326: in library mode, they are tricky objects if you intend to build polynomials
        !          1327: yourself (and not just let PARI functions produce them, which is usually less
        !          1328: efficient). For instance, it does not make sense to have a variable number
        !          1329: occur in the components of a polynomial whose main variable has a higher
        !          1330: number (lower priority), even though there's nothing PARI can do to prevent
        !          1331: you from doing it.
        !          1332:
        !          1333: \subsec{Creating variables}
        !          1334: A basic difficulty is to ``create'' a variable. As we have seen in
        !          1335: \secref{se:intro4}, a plethora of objects is associated to variable
        !          1336: number~$v$. Here is the complete list: \teb{polun}$[v]$ and
        !          1337: \teb{polx}$[v]$, which you can use in library mode and which represent,
        !          1338: respectively, the monic monomials of degrees 0 and 1 in~$v$;
        !          1339: \teb{varentries}$[v]$, and \teb{polvar}$[v]$. The latter two are only
        !          1340: meaningful to GP, but they have to be set nevertheless. All of them must be
        !          1341: properly defined before you can use a given integer as a variable number.
        !          1342:
        !          1343: Initially, this is done for $0$ (the variable \kbd{x} under GP), and
        !          1344: \tet{MAXVARN}, which is there to address the need for a ``temporary'' new
        !          1345: variable, which would not be used in regular objects (created by the
        !          1346: library). We call the latter type a ``temporary variable''. The regular
        !          1347: variables meant to be used in regular objects, are called ``user
        !          1348: variables\sidx{variable (user)}''.
        !          1349:
        !          1350: \subsubsec{User variables}\sidx{variable (user)}:
        !          1351: When the program starts, \kbd{x} is the only user variable (number~$0$). To
        !          1352: define new ones, use
        !          1353:
        !          1354: \fun{long}{fetch_user_var}{char *$s$}
        !          1355:
        !          1356: \noindent which inspects the user variable named $s$ (creating it if
        !          1357: needed), and returns its variable number.
        !          1358: \bprog
        !          1359: long v = fetch_user_var("y");
        !          1360: GEN gy = polx[v];
        !          1361: @eprog
        !          1362: This function raises an error if $s$ is already known as a function name to
        !          1363: the interpreter.
        !          1364:
        !          1365: \misctitle{Caveat:} it is possible to use \teb{flissexpr}
        !          1366: (see~\secref{se:flisexpr}) to execute a GP command and create GP variables
        !          1367: on the fly as needed:
        !          1368:
        !          1369: \bprog
        !          1370: GEN gy = flissexpr("y"); /*@Ccom supposedly returns polx[$v$], for some $v$ */
        !          1371: long v = gvar(gy);
        !          1372: @eprog
        !          1373:
        !          1374: \noindent This is dangerous, especially when programming functions that
        !          1375: will be used under GP. The code above reads the value of \kbd{y}, as it is
        !          1376: currently known by the GP interpreter (possibly creating it in the
        !          1377: process). All is well and good if \kbd{y} hasn't been tampered with in
        !          1378: previous GP commands. But if \kbd{y} has been modified (e.g \kbd {y = 1}),
        !          1379: then the value of \kbd{gy} is not what you expected it to be and corresponds
        !          1380: instead to the current value of the GP variable (e.g \kbd{gun}).
        !          1381:
        !          1382: \subsubsec{Temporary variables}\sidx{variable (temporary)}:
        !          1383: \kbd{MAXVARN} is available, but is better left to pari internal functions
        !          1384: (some of which don't check that \kbd{MAXVARN} is free for them to use,
        !          1385: which can be considered a bug). You can create more temporary variables
        !          1386: using
        !          1387:
        !          1388: \fun{long}{fetch_var}{}\label{se:fetch_var}
        !          1389:
        !          1390: \noindent
        !          1391: This returns a variable number which is guaranteed to be unused by the
        !          1392: library at the time you get it and as long as you do not delete it (we'll see
        !          1393: how to do that shortly). This has {\it lower\/} number (i.e.~{\it higher\/}
        !          1394: priority) than any temporary variable produced so far (\kbd{MAXVARN} is
        !          1395: assumed to be the first such). This call updates all the aforementioned
        !          1396: internal arrays. In particular, after the statement \kbd{v = fetch\_var()},
        !          1397: you can use \kbd{polun[v]} and \kbd{polx[v]}. The variables created in this
        !          1398: way have no identifier assigned to them though, and they will be printed as
        !          1399: \kbd{\#<\text{number}>}, except for \kbd{MAXVARN} which will be printed
        !          1400: as~\kbd{\#}. You can assign a name to a temporary variable, after creating
        !          1401: it, by calling the function
        !          1402:
        !          1403: \fun{void}{name_var}{long n, char *s}
        !          1404:
        !          1405: \noindent after which the output machinery will use the name \kbd{s} to
        !          1406: represent the variable number~\kbd{n}. The GP parser will {\it not\/}
        !          1407: recognize it by that name, however, and calling this on a variable known
        !          1408: to~GP will raise an error. Temporary variables are meant to be used as free
        !          1409: variables, and you should never assign values or functions to them as you
        !          1410: would do with variables under~GP. For that, you need a user variable.
        !          1411:
        !          1412: All objects created by \kbd{fetch\_var} are on the heap and not on the stack,
        !          1413: thus they are not subject to standard garbage collecting (they won't be
        !          1414: destroyed by a \kbd{gerepile} or \kbd{avma = ltop} statement). When you don't
        !          1415: need a variable number anymore, you can delete it using
        !          1416:
        !          1417: \fun{long}{delete_var}{}
        !          1418:
        !          1419: \noindent which deletes the {\it latest\/} temporary variable created and
        !          1420: returns the variable number of the previous one (or simply returns 0 if you
        !          1421: try, in vain, to delete \kbd{MAXVARN}). Of course you should make sure that
        !          1422: the deleted variable does not appear anywhere in the objects you use later
        !          1423: on. Here is an example:
        !          1424:
        !          1425: \bprog
        !          1426: {
        !          1427:   long first = fetch_var();
        !          1428:   long n1 = fetch_var();
        !          1429:   long n2 = fetch_var(); /*@Ccom prepare three variables for internal use */
        !          1430:   ...
        !          1431:   /*@Ccom delete all variables before leaving */
        !          1432:   do { num = delete_var(); } while (num && num <= first);
        !          1433: }@eprog
        !          1434:
        !          1435: \noindent
        !          1436: The (dangerous) statement
        !          1437:
        !          1438: \bprog
        !          1439: while (delete_var()) /*@Ccom empty */;
        !          1440: @eprog
        !          1441:
        !          1442: \noindent removes all temporary variables that were in use, except
        !          1443: \kbd{MAXVARN} which cannot be deleted.
        !          1444:
        !          1445: \section{Input and output}
        !          1446:
        !          1447: \noindent
        !          1448: Two important aspects have not yet been explained which are specific to
        !          1449: library mode: input and output of PARI objects.
        !          1450:
        !          1451: \subsec{Input}.
        !          1452:
        !          1453: \noindent
        !          1454: For \idx{input}, PARI provides you with two powerful high level functions
        !          1455: which enables you to input your objects as if you were under GP. In fact,
        !          1456: the second one {\it is\/} essentially the GP syntactical parser, hence you
        !          1457: can use it not only for input but for (most) computations that you can do
        !          1458: under GP. These functions are called \teb{flisexpr} and \teb{flisseq}. The
        !          1459: first one has the following syntax:\label{se:flisexpr}
        !          1460:
        !          1461: \fun{GEN}{flisexpr}{char *s}
        !          1462:
        !          1463: \noindent
        !          1464: Its effect is to analyze the input string s and to compute the result as in
        !          1465: GP.  However it is limited to one expression. If you want to read and
        !          1466: evaluate a sequence of expressions, use
        !          1467:
        !          1468: \fun{GEN}{flisseq}{char *s}
        !          1469:
        !          1470: \noindent\sidx{filter}
        !          1471: In fact these two functions start by {\it filtering\/} out all spaces and
        !          1472: comments in the input string (that's what the initial \kbd{f} stands for).
        !          1473: They then call the underlying basic functions, the GP parser proper:
        !          1474: \fun{GEN}{lisexpr}{char *s} and \fun{GEN}{lisseq}{char *s}, which are
        !          1475: slightly faster but which you probably don't need.
        !          1476:
        !          1477: To read a \kbd{GEN} from a file, you can use the simpler interface
        !          1478:
        !          1479: \fun{GEN}{lisGEN}{FILE *file}
        !          1480:
        !          1481: which reads a character string of arbitrary length from the stream \kbd{file}
        !          1482: (up to the first newline character), applies \kbd{flisexpr} to it, and
        !          1483: returns the resulting \kbd{GEN}. This way, you won't have to worry about
        !          1484: allocating buffers to hold the string. To interactively input an expression,
        !          1485: use \kbd{lisGEN(stdin)}. This function returns \kbd{NULL} if \kbd{EOF} is
        !          1486: encountered before a complete expression could be read.
        !          1487:
        !          1488: Once in a while, it may be necessary to evaluate a GP expression sequence
        !          1489: involving a call to a function you have defined in~C. This is easy using
        !          1490: \teb{install} which allows you to manipulate quite an arbitrary function (GP
        !          1491: knows about pointers!). The syntax is
        !          1492:
        !          1493: \fun{void}{install}{void *f, char *name, char *code}
        !          1494:
        !          1495: \noindent where \kbd{f} is the (address of) the function (cast to the C type
        !          1496: \kbd{void*}), \kbd{name} is the name by which you want to access your
        !          1497: function from within your GP expressions, and \kbd{code} is a character
        !          1498: string describing the function call prototype (see~\secref{se:gp.interface}
        !          1499: for the precise description of prototype strings). In case the function
        !          1500: returns a \kbd{GEN}, it should satisfy \kbd{gerepileupto} assumptions (see
        !          1501: \secref{se:garbage}).
        !          1502:
        !          1503: \subsec{Output}.
        !          1504:
        !          1505: \noindent
        !          1506: For \idx{output}, there exist essentially three different functions (with
        !          1507: variants), corresponding to the three main GP output formats (as described in
        !          1508: \secref{se:output}), plus three extra ones, respectively devoted to
        !          1509: \TeX\ output, string output, and (advanced) debugging.
        !          1510:
        !          1511: \noindent $\bullet$ ``raw'' format, obtained by using the function
        !          1512: \teb{brute} with the following syntax:
        !          1513:
        !          1514: \fun{void}{brute}{GEN obj, char x, long n}
        !          1515:
        !          1516: \noindent
        !          1517: This prints the PARI object \kbd{obj} in \idx{format} \kbd{x0.n}, using the
        !          1518: notations from \secref{se:format}. Recall that here \kbd{x} is either
        !          1519: \kbd{'e'}, \kbd{'f'} or \kbd{'g'} corresponding to the three numerical output
        !          1520: formats, and \kbd{n} is the number of printed significant digits, and should
        !          1521: be set to $-1$ if all of them are wanted (these arguments only affect the
        !          1522: printing of real numbers). Usually you won't need that much flexibility, so
        !          1523: most of the time you will get by with the function
        !          1524:
        !          1525: \fun{void}{outbrute}{GEN obj}, which is equivalent to \kbd{brute(x,'g',-1)},
        !          1526:
        !          1527: \noindent or even better, with
        !          1528:
        !          1529: \fun{void}{output}{GEN obj} which is equivalent to \kbd{outbrute(obj)}
        !          1530: followed by a newline and a buffer flush. This is especially nice during
        !          1531: debugging. For instance using \kbd{dbx} or \kbd{gdb}, if \kbd{obj} is a
        !          1532: \kbd{GEN}, typing \kbd{print output(obj)} will enable you to see the
        !          1533: content of \kbd{obj} (provided the optimizer has not put it into a
        !          1534: register, but it's rarely a good idea to debug optimized code).
        !          1535:
        !          1536: \noindent $\bullet$ ``prettymatrix'' format: this format is identical to the
        !          1537: preceding one except for matrices. The relevant functions are:
        !          1538:
        !          1539: \fun{void}{matbrute}{GEN obj, char x, long n}
        !          1540:
        !          1541: \fun{void}{outmat}{GEN obj}, which is followed by a newline and a buffer flush.
        !          1542:
        !          1543: \noindent $\bullet$ ``prettyprint'' format: the basic function has an
        !          1544: additional parameter \kbd{m}, corresponding to the (minimum) field width
        !          1545: used for printing integers:
        !          1546:
        !          1547: \fun{void}{sor}{GEN obj, char x, long n, long m}
        !          1548:
        !          1549: \noindent The simplified version is
        !          1550:
        !          1551: \fun{void}{outbeaut}{GEN obj} which is equivalent to
        !          1552: \kbd{sor(obj,'g',-1,0)} followed by a newline and a buffer flush.
        !          1553:
        !          1554: \noindent $\bullet$ The first extra format corresponds to the \teb{texprint}
        !          1555: function of GP, and gives a \TeX\ output of the result. It is obtained by
        !          1556: using:
        !          1557:
        !          1558: \fun{void}{exe}{GEN obj, char x, long n}
        !          1559:
        !          1560: \noindent $\bullet$ The second one is the function \teb{GENtostr} which
        !          1561: converts a PARI \kbd{GEN} to an ASCII string. The syntax is
        !          1562:
        !          1563: \fun{char*}{GENtostr}{GEN obj}, wich returns a \kbd{malloc}'ed character
        !          1564: string (which you should \kbd{free} after use).
        !          1565:
        !          1566: \noindent $\bullet$ The third and final one outputs the \idx{hexadecimal tree}
        !          1567: corresponding to the GP command \kbd{\b x} using the function
        !          1568:
        !          1569: \fun{void}{voir}{GEN obj, long nb}, which will only output the first
        !          1570: \kbd{nb} words corresponding to leaves (very handy when you have a look at
        !          1571: big recursive structures). If you set this parameter to $-1$ all
        !          1572: significant words will be printed. Usually this last type of output would
        !          1573: only be used for debugging purposes.
        !          1574:
        !          1575: \misctitle{Remark}. Apart from \teb{GENtostr}, all PARI output is done on
        !          1576: the stream \teb{outfile}, which by default is initialized to \teb{stdout}. If
        !          1577: you want that your output be directed to another file, you should use the
        !          1578: function \fun{void}{switchout}{char *name} where \kbd{name} is a
        !          1579: character string giving the name of the file you are going to use. The
        !          1580: output will be {\it appended\/} at the end of the file. In order to close
        !          1581: the file, simply call \kbd{switchout(NULL)}.
        !          1582:
        !          1583: Similarly, errors are sent to the stream \teb{errfile} (\teb{stderr}
        !          1584: by default), and input is done on the stream \teb{infile}, which you can change
        !          1585: using the function \teb{switchin} which is analogous to \teb{switchout}.
        !          1586:
        !          1587: \misctitle{(Advanced) Remark}. All output is done according to the values
        !          1588: of the \teb{pariOut}~/ \teb{pariErr} global variables which are pointers to
        !          1589: structs of pointer to functions. If you really intend to use these, this
        !          1590: probably means you are rewriting GP. In that case, have a look at the code in
        !          1591: \kbd{language/es.c} (\kbd{init80()} or \kbd{GENtostr()} for instance).
        !          1592:
        !          1593: \subsec{Errors}.\sidx{error}\kbdsidx{talker}
        !          1594:
        !          1595: \noindent
        !          1596: If you want your functions to issue error messages, you can use the general
        !          1597: error handling routine \teb{err}. The basic syntax is
        !          1598: %
        !          1599: \bprog
        !          1600:   err(talker, "error message");
        !          1601: @eprog
        !          1602:
        !          1603: \noindent
        !          1604: This will print the corresponding error message and exit the program (in
        !          1605: library mode; go back to the GP prompt otherwise).\label{se:err} You can
        !          1606: also use it in the more versatile guise
        !          1607: \bprog
        !          1608:   err(talker, format, ...);
        !          1609: @eprog\noindent
        !          1610: where \kbd{format} describes the format to use to write the remaining
        !          1611: operands, as in the \teb{printf} function (however, see the next section).
        !          1612: The simple syntax above is just a special case with a constant format and no
        !          1613: remaining arguments.
        !          1614:
        !          1615: \noindent
        !          1616: The general syntax is
        !          1617:
        !          1618: \fun{void}{err}{numerr,...}
        !          1619:
        !          1620: \noindent where \kbd{numerr} is a codeword which indicates what to do with
        !          1621: the remaining arguments and what message to print. The list of valid keywords
        !          1622: is in \kbd{language/errmessages.c} together with the basic corresponding
        !          1623: message. For instance, \kbd{err(typeer,"matexp")} will print the message:
        !          1624:
        !          1625: \kbd{ ***   incorrect type in matexp.}
        !          1626:
        !          1627: \noindent
        !          1628: Among the codewords are {\it warning\/} keywords (all those which start with
        !          1629: the prefix \kbd{warn}). In that case, \teb{err} does {\it not\/} abort the
        !          1630: computation, just print the requested message and go on. The basic example is
        !          1631:
        !          1632: \kbd{err(warner, "Strategy 1 failed. Trying strategy 2")}
        !          1633:
        !          1634: \noindent which is the exact equivalent of \kbd{err(talker,...)} except that
        !          1635: you certainly don't want to stop the program at this point, just inform the
        !          1636: user that something important has occured (in particular, this output would be
        !          1637: suitably highlighted under GP, whereas a simple \kbd{printf} would not).
        !          1638:
        !          1639: \subsec{Debugging output}.\sidx{debugging}\sidx{format}\label{se:dbg_output}
        !          1640:
        !          1641: \noindent
        !          1642: The global variables \teb{DEBUGLEVEL} and \teb{DEBUGMEM} (corresponding
        !          1643: to the default \teb{debug} and \teb{debugmem}, see \secref{se:defaults})
        !          1644: are used throughout the PARI code to govern the amount of diagnostic and
        !          1645: debugging output, depending on their values. You can use them to debug your
        !          1646: own functions, especially after having made them accessible under GP through
        !          1647: the command \teb{install} (see \secref{se:install}).
        !          1648:
        !          1649: For debugging output, you can use \kbd{printf} and the standard output
        !          1650: functions (\teb{brute} or \teb{output} mainly), but also some special purpose
        !          1651: functions which embody both concepts, the main one being
        !          1652:
        !          1653: \fun{void}{fprintferr}{char *pariformat, ...}
        !          1654:
        !          1655: \noindent
        !          1656: Now let's define what a PARI format is. It is a character string, similar
        !          1657: to the one \kbd{printf} uses, where \kbd{\%} characters have a special
        !          1658: meaning. It describes the format to use when printing the remaining operands.
        !          1659: But, in addition to the standard format types, you can use \kbd{\%Z} to
        !          1660: denote a \kbd{GEN} object (we would have liked to pick \kbd{\%G} but it was
        !          1661: already in use!). For instance you could write:
        !          1662: \bprog
        !          1663: err(talker, "x[%d] = %Z is not invertible!", i, x[i])
        !          1664: @eprog
        !          1665: \noindent since the \teb{err} function accepts PARI formats. Here \kbd{i}
        !          1666: is an \kbd{int}, \kbd{x} a \kbd{GEN} which is not a leaf and this would
        !          1667: insert in raw format the value of the \kbd{GEN} \kbd{x[i]}.
        !          1668:
        !          1669: \subsec{Timers and timing output}.
        !          1670:
        !          1671: \noindent
        !          1672: To profile your functions, you can use the PARI timer. The functions
        !          1673: \fun{long}{timer}{} and \fun{long}{timer2}{} return the elapsed time since
        !          1674: the last call of the same function (in milliseconds). Two different
        !          1675: functions (identical except for their independent time-of-last-call
        !          1676: memories!) are provided so you can have both global timing and fine tuned
        !          1677: profiling.
        !          1678:
        !          1679: You can also use \fun{void}{msgtimer}{char *format,...}, which prints
        !          1680: prints \kbd{Time}, then the remaining arguments as specified by
        !          1681: \kbd{format} (which is a PARI format), then the output of \kbd{timer2}.
        !          1682:
        !          1683: This mechanism is simple to use but not foolproof. If some other function
        !          1684: uses these timers, and many PARI functions do when DEBUGLEVEL is high enough,
        !          1685: the timings will be meaningless. The functions \fun{long}{gentimer}{long
        !          1686: id} or \fun{long}{genmsgtimer}{long id, char *format,...} are equivalent to
        !          1687: \kbd{timer} and \kbd{msgtimer} respectively, except they will use a unique
        !          1688: timer denoted by \kbd{id}. To get a valid identifier, use
        !          1689: \kbd{id = }\tet{get_timer}\kbd{(0)}.
        !          1690:
        !          1691: This timer has to be deleted when it's not needed anymore
        !          1692: (i.e.~when the main function returns), with a call to \kbd{get\_timer(id)}.
        !          1693: After such a call, the reserved identifier becomes available again.
        !          1694:
        !          1695: \section{A complete program}
        !          1696: \label{se:prog}
        !          1697:
        !          1698: \noindent
        !          1699: Now that the preliminaries are out of the way, the best way to learn how to
        !          1700: use the library mode is to work through a detailed non-trivial example of a
        !          1701: main program. We will write a program which computes the exponential of a
        !          1702: square matrix~$x$.  The complete listing is given in Appendix~B, but each
        !          1703: part of the program will be produced and explained here. We will use an
        !          1704: algorithm which is not optimal but is not far from the one used for the PARI
        !          1705: function \teb{gexp} (in fact embodied in the function \kbd{mpexp1}). This
        !          1706: consists in calculating the sum of the series:
        !          1707: $$e^{x/(2^n)}=\sum_{k=0}^\infty \dfrac{(x/(2^n))^k}{k!}$$
        !          1708: for a suitable positive integer $n$, and then computing $e^x$ by repeated
        !          1709: squarings.  First, we will need to compute the $L^2$-norm of the matrix~$x$,
        !          1710: i.e.~the quantity:
        !          1711: $$z=\|x\|_2=\sqrt{\sum x_{i,j}^2}.$$
        !          1712: We will then choose the integer $n$ such that the $L^2$-norm of $x/(2^n)$ is
        !          1713: less than or equal to~1, i.e.
        !          1714: $$ n = \left\lceil{\ln(z)}\big/{\ln(2)}\right\rceil $$
        !          1715: if $z\ge1$, and~$n=0$ otherwise. Then the series will converge at least as
        !          1716: fast as the usual one for $e^1$, and the cutoff error will be easy to
        !          1717: estimate. In fact a larger value of $n$ would be preferable, but this is
        !          1718: slightly machine dependent and more complicated, and will be left to the
        !          1719: reader.
        !          1720:
        !          1721: Let us start writing our program. So as to be able to use it in other
        !          1722: contexts, we will structure it in the following way: a main program which
        !          1723: will do the input and output, and a function which we shall call \kbd{matexp}
        !          1724: which does the real work. The main program is easy to write. It can be
        !          1725: something like this:
        !          1726:
        !          1727: \bprog
        !          1728: #include <pari.h>
        !          1729:
        !          1730: GEN matexp(GEN x, long prec);
        !          1731:
        !          1732: int
        !          1733: main()
        !          1734: {
        !          1735:   long d, prec = 3;
        !          1736:   GEN x;
        !          1737:
        !          1738:   /*@Ccom take a stack of $10^6$ bytes, no prime table */
        !          1739:   pari_init(1000000, 2);
        !          1740:   printf("precision of the computation in decimal digits:\n");
        !          1741:   d = itos(lisGEN(stdin));
        !          1742:   if (d > 0) prec = (long) (d*pariK1+3);
        !          1743:
        !          1744:   printf("input your matrix in GP format:\n");
        !          1745:   x = matexp(lisGEN(stdin), prec);
        !          1746:
        !          1747:   sor(x, 'g', d, 0);
        !          1748:   exit(0);
        !          1749: }@eprog
        !          1750: \noindent
        !          1751: The variable \kbd{prec} represents the length in longwords of the real
        !          1752: numbers used. \teb{pariK1} is a constant (defined in \kbd{paricom.h}) equal
        !          1753: to $\ln(10) / (\ln(2) * \kbd{BITS\_IN\_LONG})$, which allows us to convert
        !          1754: from a number of decimal digits to a number of longwords, independently of
        !          1755: the actual bit size of your long integers. The function \teb{lisGEN} reads an
        !          1756: expression (here from standard input) and converts it to a \kbd{GEN}, like
        !          1757: the GP parser itself would. This means it takes care of whitespace etc.\ in
        !          1758: the input, and can do computations (e.g.~\kbd{matid(2)} or \kbd{[1,0; 0,1]}
        !          1759: are equally valid inputs).
        !          1760:
        !          1761: Finally, \kbd{sor} is the general output routine. We have chosen to give
        !          1762: \kbd{d} significant digits since this is what was asked for. Note that there
        !          1763: is a trick hidden here: if a negative \kbd{d} was input, then the computation
        !          1764: will be done in precision 3 (i.e.~about 9.7 decimal digits for 32-bit
        !          1765: machines and 19.4 for 64-bit machines) and in the function \kbd{sor}, giving
        !          1766: a negative third argument outputs all the significant digits, which is entirely
        !          1767: appropriate. Now let us attack the main course, the function \kbd{matexp}:
        !          1768: %
        !          1769: \bprog
        !          1770: GEN
        !          1771: matexp(GEN x, long prec)
        !          1772: {
        !          1773:   long lx=lg(x),i,k,n,lbot, ltop = avma;
        !          1774:   GEN y,r,s,p1,p2;
        !          1775:
        !          1776:   /*@Ccom check that x is a square matrix */
        !          1777:   if (typ(x) != t_MAT) err(talker,"this expression is not a matrix");
        !          1778:   if (lx == 1) return cgetg(1, t_MAT);
        !          1779:   if (lx != lg(x[1])) err(talker,"not a square matrix");
        !          1780:
        !          1781:   /*@Ccom compute the $L_2$ norm of x */
        !          1782:   s = gzero;
        !          1783:   for (i=1; i<lx; i++)
        !          1784:     s = gadd(s, gnorml2((GEN)x[i]));
        !          1785:   if (typ(s) == t_REAL) setlg(s,3);
        !          1786:   s = gsqrt(s,3); /*@Ccom we do not need much precision on s */
        !          1787:
        !          1788:   /*@Ccom if $s<1$, we are happy */
        !          1789:   k = expo(s);
        !          1790:   if (k < 0) { n = 0; p1 = x; }
        !          1791:   else { n = k+1; p1 = gmul2n(x,-n); setexpo(s,-1); }@eprog
        !          1792: \noindent
        !          1793: Before continuing, several remarks are in order.
        !          1794:
        !          1795: First, before starting this computation which will produce garbage on the
        !          1796: stack, we have carefully saved the value of the stack pointer \kbd{avma} in
        !          1797: \kbd{ltop}. Note that we are going to assume throughout that the garbage does
        !          1798: not overflow the currently available stack. If it ever did, we would
        !          1799: have several options~--- allocate a larger stack in the main program (for
        !          1800: instance change 1000000 into 2000000), do some \kbd{gerepile}ing along the
        !          1801: way, or (if you know what you are doing) use \tet{allocatemoremem}.
        !          1802:
        !          1803: Secondly, the \teb{err} function is the general error handler for the
        !          1804: PARI library. This will abort the program after printing the required
        !          1805: message.
        !          1806:
        !          1807: Thirdly, notice how we handle the special case $\kbd{lx} = 1$ (empty matrix)
        !          1808: {\it before\/} accessing \kbd{lx(x[1])}. Doing it the other way round could
        !          1809: produce a fatal error (a segmentation fault or a bus error, most probably).
        !          1810: Indeed, if \kbd{x} is of length 1, then \kbd{x[1]} is not a component of
        !          1811: \kbd{x}. It is just the contents of the memory cell which happens to follow
        !          1812: the one pointed to by \kbd{x}, and thus has no reason to be a valid \kbd{GEN}.
        !          1813: Now recall that none of the codeword handling macros do any kind of type
        !          1814: checking (see \secref{se:impl}), thus \teb{lg} would consider \kbd{x[1]}
        !          1815: as a valid address, and try to access \kbd{*((GEN)x[1])} (the first codeword)
        !          1816: which is unlikely to be a legal memory address.
        !          1817:
        !          1818: In the fourth place, to compute the square of the $L^2$-norm of \kbd{x} we
        !          1819: just add the squares of the $L^2$-norms of the column vectors which we obtain
        !          1820: using the library function \teb{gnorml2}. Had this function not existed, the
        !          1821: norm computation would of course have been just as easy to write, but we would
        !          1822: have needed a double loop.
        !          1823:
        !          1824: We then take the square root of \kbd{s}, in precision~3 (the smallest
        !          1825: possible). The \kbd{prec} argument of transcendental functions (here~$3$) is
        !          1826: only taken into account when the arguments are {\it exact\/} objects, and thus
        !          1827: no a priori precision can be determined from the objects themselves. To cater
        !          1828: for this possibility, if \kbd{s} is of type \typ{REAL}, we use the function
        !          1829: \teb{setlg} which effectively sets the precision of \kbd{s} to the required
        !          1830: value. Note that here, since we are using a numeric value for a \kbd{cget}
        !          1831: function, the program will run slightly differently on 32-bit and 64-bit
        !          1832: machines: we want to use the smallest possible bit accuracy, and this is equal
        !          1833: to \kbd{BITS\_IN\_LONG}.
        !          1834:
        !          1835: Note that the matrix \kbd{x} is allowed to have complex entries, but the
        !          1836: function \kbd{gnorml2} guarantees that \kbd{s} is a non-negative real number
        !          1837: (not necessarily of type \typ{REAL} of course). If we had not known this fact,
        !          1838: we would simply have added the instruction \kbd{s = greal(s);} just after the
        !          1839: \kbd{for} loop.
        !          1840:
        !          1841: Note also that the function \kbd{gnorml2} works as desired on matrices, so we
        !          1842: really did not need this loop at all (\kbd{s = gnorml2(x)} would have been
        !          1843: enough), but we wanted to give examples of function usage. Similarly, it is of
        !          1844: course not necessary to take the square root for testing whether the norm
        !          1845: exceeds~$1$.
        !          1846:
        !          1847: In the fifth place, note that we initialized the sum \kbd{s} to \teb{gzero},
        !          1848: which is an exact zero. This is logical, but has some disadvantages: if all
        !          1849: the entries of the matrix are integers (or rational numbers), the computation
        !          1850: will take rather long, about twice as long as with real numbers of the same
        !          1851: length. It would be better to initialize \kbd{s} to a real zero, using for
        !          1852: instance the instructions:
        !          1853:
        !          1854: \kbd{s = cgetr(prec+1); gaffsg(0,s);}
        !          1855:
        !          1856: \noindent
        !          1857: This raises the question: which real zero does this produce (have a look
        !          1858: at~\secref{se:whatzero})? In fact, the following choice has been made: it will
        !          1859: give you the zero with exponent equal to $-\kbd{BITS\_IN\_LONG}$ times the
        !          1860: number of longwords in the mantissa, i.e.~$-\kbd{bit\_accuracy(lg(s))}$.
        !          1861: Instead of the above idiom, you can also use the function
        !          1862: \fun{GEN}{realzero}{long prec}, which simply returns a real zero to
        !          1863: accuracy $-\tet{bit_accuracy}(\var{prec})$.
        !          1864:
        !          1865: The sixth remark here is about how to determine the approximate size
        !          1866: of a real number. The fastest way to do this is to look at its binary
        !          1867: exponent. Hence we need to have \kbd{s} actually represented as a real number,
        !          1868: and not as an integer or a rational number. The result of transcendental
        !          1869: functions is guaranteed to be of type \typ{REAL}, or complex with \typ{REAL}
        !          1870: components, thus this is indeed the case after the call to \kbd{gsqrt} since
        !          1871: its argument is a nonnegative (real) number.
        !          1872:
        !          1873: Finally, note the use of the function \teb{gmul2n}. It has the following
        !          1874: syntax:
        !          1875:
        !          1876: \fun{GEN}{gmul2n}{GEN x, long n}
        !          1877:
        !          1878: \noindent and the effect is simply to multiply \kbd{x} by $2^{\text n}$,
        !          1879: where \kbd{n} can be positive or negative. This is much faster than
        !          1880: \kbd{gmul} or \kbd{gmulgs}.
        !          1881:
        !          1882: There is another function \teb{gshift} with exactly the same syntax.
        !          1883: When \kbd{n} is non-negative, the effects of these two functions are the same.
        !          1884: However, when \kbd{n} is negative, \kbd{gshift} acts like a right shift of
        !          1885: \kbd{-n}, hence does not noramlly perform an exact division on integers. The
        !          1886: function  \kbd{gshift} is the PARI analogue of the C or GP operators \kbd{<<}
        !          1887: and~\kbd{>>}.
        !          1888:
        !          1889: We now come to the heart of the function. We have a \kbd{GEN} \kbd{p1} which
        !          1890: points to a certain matrix of which we want to take the exponential. We will
        !          1891: want to transform this matrix into a matrix with real (or complex of real)
        !          1892: entries before starting the computation. To do this, we simply multiply by
        !          1893: the real number 1 in precision $\kbd{prec}+1$ (to be on the side of safety).
        !          1894: To sum the series, we will use three variables: a variable \kbd{p2} which at
        !          1895: stage $k$ will contain $\kbd{p1}^k/k!$, a variable \kbd{y} which will contain
        !          1896: $\sum_{i=0}^k \kbd{p1}^i/i!$, and a variable \kbd{r} which will contain the
        !          1897: size estimate $\kbd{s}^k/k!$. Note that we do not use Horner's rule. This is
        !          1898: simply because we are lazy and do not want to compute in advance the number
        !          1899: of terms that we need. We leave this modification (and many other
        !          1900: improvements!) to the reader. The program continues as follows:
        !          1901:
        !          1902: \bprog
        !          1903:   /*@Ccom initializations before the loop */
        !          1904:   r = cgetr(prec+1); gaffsg(1,r); p1 = gmul(r,p1);
        !          1905:   y = gscalmat(r,lx-1); /*@Ccom creates scalar matrix with r on diagonal */
        !          1906:   p2 = p1; r = s; k = 1;
        !          1907:   y = gadd(y,p2);
        !          1908:
        !          1909:   /*@Ccom now the main loop */
        !          1910:   while (expo(r) >= -BITS_IN_LONG*(prec-1))
        !          1911:   {
        !          1912:     k++; p2 = gdivgs(gmul(p2,p1),k);
        !          1913:     r = gdivgs(gmul(s,r),k); y = gadd(y,p2);
        !          1914:   }
        !          1915:
        !          1916:   /*@Ccom now square back n times if necessary */
        !          1917:   if (!n) { lbot = avma; y = gcopy(y); }
        !          1918:   else
        !          1919:   {
        !          1920:     for (i=0; i<n; i++) { lbot = avma; y = gsqr(y); }
        !          1921:   }
        !          1922:   return gerepile(ltop,lbot,y);
        !          1923: }@eprog
        !          1924: \noindent
        !          1925: A few remarks once again. First note the use of the function
        !          1926: \teb{gscalmat} with the following syntax:
        !          1927:
        !          1928: \fun{GEN}{gscalmat}{GEN x, long m}
        !          1929:
        !          1930: \noindent
        !          1931: The effect of this function is to create the $\kbd{m}\times\kbd{m}$ scalar
        !          1932: matrix whose diagonal entries are~\kbd{x}. Hence the length of the matrix
        !          1933: including the codeword will in fact be \kbd{m+1}.  There is a corresponding
        !          1934: function \teb{gscalsmat} which takes a long as a first argument.
        !          1935:
        !          1936: If we refer to what has been said above, the main loop should be self-evident.
        !          1937:
        !          1938: When we do the final squarings, according to the fundamental dogma on the
        !          1939: use of \teb{gerepile}, we keep the value of \kbd{avma} in \kbd{lbot} just {\it
        !          1940: before\/} the squaring, so that if it is the last one, \kbd{lbot} will indeed
        !          1941: be the bottom address of the garbage pile, and \kbd{gerepile} will work. Note
        !          1942: that it takes a completely negligible time to do this in each loop compared
        !          1943: to a matrix squaring.  However, when \kbd{n} is initially equal to 0, no
        !          1944: squaring has to be done, and we have our final result ready but we lost the
        !          1945: address of the bottom of the garbage pile. Hence we use the trick of copying
        !          1946: \kbd{y} again to the top of the stack. This is inefficient, but does the trick.
        !          1947: If we wanted to avoid this using only \kbd{gerepile}, the best thing to do
        !          1948: would be to put the instruction \kbd{lbot=avma} just before both occurrences
        !          1949: of the instruction \kbd{y=gadd(p2,y)}. Of course, we could also rewrite the
        !          1950: last block as follows:
        !          1951:
        !          1952: \bprog
        !          1953:   /*@Ccom now square back n times */
        !          1954:   for (i=0; i<n; i++) y = gsqr(y);
        !          1955:   return gerepileupto(ltop,y);
        !          1956: @eprog
        !          1957: \noindent
        !          1958: because it does not matter to \teb{gerepileupto} that we have lost the address
        !          1959: just before the final result (note that the loop is not executed if \kbd{n}
        !          1960: is~0). It is safe to use \kbd{gerepileupto} here as \kbd{y} will have been
        !          1961: created by either \kbd{gsqr} or \kbd{gadd}, both of which are guaranteed to
        !          1962: return suitable objects.
        !          1963:
        !          1964: \misctitle{Remarks}. As such, the program should work most of the time if
        !          1965: \kbd{x} is a square matrix with real or complex entries. Indeed, since
        !          1966: essentially the first thing that we do is to multiply by the real number~1,
        !          1967: the program should work for integer, real, rational, complex or quadratic
        !          1968: entries. This is in accordance with the behavior of transcendental functions.
        !          1969:
        !          1970: Furthermore, since this program is intended to be only an illustrative
        !          1971: example, it has been written a little sloppily. In particular many error
        !          1972: checks have been omitted, and the efficiency is far from optimal. An evident
        !          1973: improvement would be the use of \kbd{gerepileupto} mentioned above. Another
        !          1974: improvement is to multiply the matrix x by the real number 1 right at the
        !          1975: beginning, speeding up the computation of the $L^2$-norm in many cases. These
        !          1976: improvements are included in the version given in Appendix~B. Still another
        !          1977: improvement would come from a better choice of~\kbd{n}. If the reader takes a
        !          1978: look at the implementation of the function \kbd{mpexp1} in the file
        !          1979: \kbd{basemath/trans1.c}, he can make the necessary changes himself. Finally,
        !          1980: there exist other algorithms of a different nature to compute the exponential
        !          1981: of a matrix.
        !          1982:
        !          1983: \section{Adding functions to PARI}
        !          1984: \subsec{Nota Bene}.
        !          1985: %
        !          1986: As mentioned in the \kbd{COPYING} file, modified versions of the PARI package
        !          1987: can be distributed under the conditions of the GNU General Public License. If
        !          1988: you do modify PARI, however, it is certainly for a good reason, hence we
        !          1989: would like to know about it, so that everyone can benefit from it. There is
        !          1990: then a good chance that the modifications that you have made will be
        !          1991: incorporated into the next release.
        !          1992:
        !          1993: (Recall the e-mail address: \kbd{pari@math.u-bordeaux.fr}, or use the mailing
        !          1994: lists).
        !          1995:
        !          1996: Roughly four types of modifications can be made. The first type includes all
        !          1997: improvements to the documentation, in a broad sense. This includes correcting
        !          1998: typos or inacurracies of course, but also items which are not really covered
        !          1999: in this document, e.g.~if you happen to write a tutorial, or pieces of code
        !          2000: exemplifying some fine points that you think were unduly omitted.
        !          2001:
        !          2002: The second type is to expand or modify the configuration routines and skeleton
        !          2003: files (the \kbd{Configure} script and anything in the \kbd{config/}
        !          2004: subdirectory) so that compilation is possible (or easier, or more efficient)
        !          2005: on an operating system previously not catered for. This includes discovering
        !          2006: and removing idiosyncrasies in the code that would hinder its portability.
        !          2007:
        !          2008: The third type is to modify existing (mathematical) code, either to correct
        !          2009: bugs, to add new functionalities to existing functions, or to improve their
        !          2010: efficiency.
        !          2011:
        !          2012: Finally the last type is to add new functions to PARI. We explain here how
        !          2013: to do this, so that in particular the new function can be called from GP.
        !          2014:
        !          2015: \subsec{The calling interface from GP, parser codes}.
        !          2016: \label{se:gp.interface}
        !          2017: A \idx{parser code} is a character string describing all the GP parser
        !          2018: needs to know about the function prototype. It contains a sequence of the
        !          2019: following atoms:
        !          2020:
        !          2021: \settabs\+\indent&\kbd{Dxxx}\quad&\cr
        !          2022: \noindent $\bullet$ Syntax requirements, used by functions like
        !          2023:  \kbd{for}, \kbd{sum}, etc.:
        !          2024: %
        !          2025: \+& \kbd{=} & separator \kbd{=} required at this point (between two
        !          2026: arguments)\cr
        !          2027:
        !          2028: \noindent$\bullet$ Mandatory arguments, appearing in the same order as the
        !          2029: input arguments they describe:
        !          2030: %
        !          2031: \+& \kbd{G} & \kbd{GEN}\cr
        !          2032: \+& \kbd{\&}& \kbd{*GEN}\cr
        !          2033: \+& \kbd{L} & long {\rm (we implicitly identify \kbd{int} with \kbd{long})}\cr
        !          2034: \+& \kbd{S} & symbol (i.e.~GP identifier name). Function expects a
        !          2035: \kbd{*entree}\cr
        !          2036: \+& \kbd{V} & variable (as \kbd{S}, but rejects symbols associated to
        !          2037: functions)\cr
        !          2038: \+& \kbd{n} & variable, expects a \idx{variable number} (a \kbd{long}, not an
        !          2039: \kbd{*entree})\cr
        !          2040: \+& \kbd{I} & string containing a sequence of GP statements (a \var{seq}), %
        !          2041: to be processed by \kbd{lisseq}\cr
        !          2042: \+&&(useful for control statements)\cr
        !          2043: \+& \kbd{E} & string containing a {\it single} GP statement (an %
        !          2044: \var{expr}), to be processed by \kbd{lisexpr}\cr
        !          2045: \+& \kbd{r} & raw input (treated as a string without quotes). Quoted %
        !          2046:  args are copied as strings\cr
        !          2047: \+&&\quad Stops at first unquoted \kbd{')'} or \kbd{','}. Special chars can
        !          2048: be quoted using '\kbd{\bs}'\cr
        !          2049: \+&&\quad Example: \kbd{aa"b\bs n)"c} yields the string \kbd{"aab\bs{n})c"}\cr
        !          2050: \+& \kbd{s} & expanded string. Example: \kbd{Pi"x"2} yields \kbd{"3.142x2"}\cr
        !          2051: \+&& Unquoted components can be of any PARI type (converted following current
        !          2052: output\cr
        !          2053: \+&& format)\cr
        !          2054:
        !          2055: \noindent$\bullet$ Optional arguments:
        !          2056: %
        !          2057: \+& \kbd{s*} & any number of strings, possibly 0 (see \kbd{s})\cr
        !          2058: \+& \kbd{s*p} & idem, setting $\kbd{prettyp} = 1$ (i.e.~in beautified
        !          2059: format)\cr
        !          2060: \+& \kbd{s*t} & idem, in \TeX\ format\cr
        !          2061: \+& \kbd{D\var{xxx}} &  argument has a default value\cr
        !          2062:
        !          2063: The format to indicate a default value (atom starts with a \kbd{D}) is
        !          2064: ``\kbd{D\var{value},\var{type},}'', where \var{type} is the code for any
        !          2065: mandatory atom (previous group), \var{value} is any valide GP expression
        !          2066: which is converted according to \var{type}, and the ending comma is
        !          2067: mandatory. For instance \kbd{D0,L,} stands for ``this optional argument will
        !          2068: be converted to a \kbd{long}, and is \kbd{0} by default''. So if the
        !          2069: user-given argument reads \kbd{1 + 3} at this point, \kbd{(long)4} is sent to
        !          2070: the function (via \tet{itos}$()$); and \kbd{(long)0} if the argument is
        !          2071: ommitted. The following special syntaxes are available:
        !          2072:
        !          2073: \settabs\+\indent\indent&\kbd{Dxxx}\quad& optional \kbd{*GEN},&\cr
        !          2074: \+&\kbd{DG}& optional \kbd{GEN}, & send \kbd{NULL} if argument omitted.\cr
        !          2075:
        !          2076: \+&\kbd{D\&}& optional \kbd{*GEN}, send \kbd{NULL} if argument omitted.\cr
        !          2077:
        !          2078: \+&\kbd{DV}& optional \kbd{*entree}, send \kbd{NULL} if argument omitted.\cr
        !          2079:
        !          2080: \+&\kbd{DI}& optional \kbd{*char}, send \kbd{NULL} if argument omitted.\cr
        !          2081:
        !          2082: \+&\kbd{Dn}& optional variable number, $-1$ if omitted.\cr
        !          2083:
        !          2084: \noindent$\bullet$ Automatic arguments:
        !          2085: %
        !          2086: \+& \kbd{f} &  Fake \kbd{*long}. C function requires a pointer but we
        !          2087: don't use the resulting \kbd{long}\cr
        !          2088: \+& \kbd{p} &  real precision (default \kbd{realprecision})\cr
        !          2089: \+& \kbd{P} &  series precision (default \kbd{seriesprecision},
        !          2090:  global variable \kbd{precdl} for the library)\cr
        !          2091:
        !          2092: \noindent $\bullet$ Return type: \kbd{GEN} by default, otherwise the
        !          2093: following can appear at the start of the code string:
        !          2094: %
        !          2095: \+& \kbd{l} & return \kbd{long}\cr
        !          2096: \+& \kbd{v} & return \kbd{void}\cr
        !          2097:
        !          2098: No more than 8 arguments can be given (syntax requirements and return types
        !          2099: are not considered as arguments). This is currently hardcoded but can
        !          2100: trivially be changed by modifying the definition of \kbd{argvec} in
        !          2101: \kbd{anal.c:identifier()}. This limitation should disappear in future
        !          2102: versions.
        !          2103:
        !          2104: When the function is called under GP, the prototype is scanned and each time
        !          2105: an atom corresponding to a mandatory argument is met, a user-given argument
        !          2106: is read (GP outputs an error message it the argument was missing). Each time
        !          2107: an optional atom is met, a default value is inserted if the user omits the
        !          2108: argument. The ``automatic'' atoms fill in the argument list transparently,
        !          2109: supplying the current value of the corresponding variable (or a dummy
        !          2110: pointer).
        !          2111:
        !          2112: For instance, here is how you would code the following prototypes (which
        !          2113: don't involve default values):
        !          2114: \bprog
        !          2115: GEN name(GEN x, GEN y, long prec)   ----> "GGp"
        !          2116: void name(GEN x, GEN y, long prec)  ----> "vGGp"
        !          2117: void name(GEN x, long y, long prec) ----> "vGLp"
        !          2118: long name(GEN x)                    ----> "lG"
        !          2119: @eprog
        !          2120:
        !          2121: If you want more examples, GP gives you easy access to the parser codes
        !          2122: associated to all GP functions: just type \kbd{\b{h} \var{function}}. You
        !          2123: can then compare with the C prototypes as they stand in the code.
        !          2124:
        !          2125: \misctitle{Remark}: If you need to implement complicated control statements
        !          2126: (probably for some improved summation functions), you'll need to know about
        !          2127: the \teb{entree} type, which is not documented. Check the comment before
        !          2128: the function list at the end of \kbd{language/init.c} and the source code
        !          2129: in \kbd{language/sumiter.c}. You should be able to make something of it.
        !          2130: \smallskip
        !          2131:
        !          2132: \subsec{Coding guidelines}.
        !          2133: \noindent
        !          2134: Code your function in a file of its own, using as a guide other functions
        !          2135: in the PARI sources. One important thing to remember is to clean the stack
        !          2136: before exiting your main function (usually using \kbd{gerepile}), since
        !          2137: otherwise successive calls to the function will clutter the stack with
        !          2138: unnecessary garbage, and stack overflow will occur sooner. Also, if it
        !          2139: returns a \kbd{GEN} and you want it to be accessible to GP, you have to
        !          2140: make sure this \kbd{GEN} is suitable for \kbd{gerepileupto} (see
        !          2141: \secref{se:garbage}).
        !          2142:
        !          2143: If error messages are to be generated in your function, use the general
        !          2144: error handling routine \kbd{err} (see \secref{se:err}). Recall that, apart
        !          2145: from the \kbd{warn} variants, this function does not return but ends with
        !          2146: a \kbd{longjmp} statement. As well, instead of explicit \kbd{printf}~/
        !          2147: \kbd{fprintf} statements, use the following encapsulated variants:
        !          2148:
        !          2149: \fun{void}{pariputs}{char *s}: write \kbd{s} to the GP output stream.
        !          2150:
        !          2151: \fun{void}{fprintferr}{char *s}: write \kbd{s} to the GP error stream (this
        !          2152: function is in fact much more versatile, see \secref{se:dbg_output}).
        !          2153:
        !          2154: Declare all public functions in an appropriate header file, if you
        !          2155: expect somebody will access them from C.  For example, if dynamic
        !          2156: loading is not available, you may need to modify PARI to access these
        !          2157: functions, so put them in \kbd{paridecl.h}. The other functions should
        !          2158: be declared \kbd{static} in your file.
        !          2159:
        !          2160: Your function is now ready to be used in library mode after compilation and
        !          2161: creation of the library. If possible, compile it as a shared library (see
        !          2162: the \kbd{Makefile} coming with the \kbd{matexp} example in the
        !          2163: distribution). It is however still inaccessible from GP.\smallskip
        !          2164:
        !          2165: \subsec{Integration with GP as a shared module}
        !          2166:
        !          2167: To tell GP about your function, you must do the following. First, find a
        !          2168: name for it. It does not have to match the one used in library mode, but
        !          2169: consistency is nice. It has to be a valid GP identifier, i.e.~use only
        !          2170: alphabetic characters, digits and the underscore character (\kbd{\_}), the
        !          2171: first character being alphabetic.
        !          2172:
        !          2173: Then you have to figure out the correct \idx{parser code} corresponding to
        !          2174: the function prototype. This has been explained above
        !          2175: (\secref{se:gp.interface}).
        !          2176:
        !          2177: Now, assuming your Operating System is supported by \tet{install}, simply
        !          2178: write a GP script like the following:
        !          2179:
        !          2180: \bprog
        !          2181: install(libname, code, gpname, library)
        !          2182: addhelp(gpname, "some help text")
        !          2183: @eprog
        !          2184: \noindent(see \secref{se:addhelp} and~\ref{se:install}). The \idx{addhelp}
        !          2185: part is not mandatory, but very useful if you want others to use your
        !          2186: module.  \kbd{libname} is how the function is named in the library,
        !          2187: usually the same name as one visible from C.
        !          2188:
        !          2189: Read that file from your GP session (from your \idx{preferences file} for
        !          2190: instance, see \secref{se:gprc}), and that's it, you can use the new
        !          2191: function \var{gpname} under GP (and we would very much like to hear about
        !          2192: it!).
        !          2193:
        !          2194: \subsec{Integration the hard way}
        !          2195:
        !          2196: If \tet{install} is not available for your Operating System, it's more
        !          2197: complicated: you have to hardcode your function in the GP binary (or
        !          2198: install \idx{Linux}). Here's what needs to be done:
        !          2199:
        !          2200: In the definition of \kbd{functions\_basic} (file \kbd{language/init.c}),
        !          2201: add your entry in exact alphabetical order by its GP name (note that digits
        !          2202: come before letters), in a line of the form:
        !          2203: \bprog
        !          2204: { "gpname", V, (void*)libname, secno, "code" }
        !          2205: @eprog
        !          2206:
        !          2207: \noindent where
        !          2208:
        !          2209: \kbd{libname} is the name of your function in library mode,
        !          2210:
        !          2211: \kbd{gpname} the name that you have chosen to call it under GP,
        !          2212:
        !          2213: \kbd{secno} is the section number of Chapter~3 in which this function would
        !          2214: belong (type \kbd{?} in GP to see the list),
        !          2215:
        !          2216: \kbd{V} is a number between 0 and 99. Right now, for PARI there are only two
        !          2217: significant values: zero means that it's possible to call the function
        !          2218: without argument, and non-zero means it needs at least one argument.
        !          2219: A binding of PARI to an external language (such as \kbd{Math::Pari}
        !          2220: Perl module) may actually distinguish between different non-zero values.
        !          2221: Better use 99 if you want a non-zero value which will not confuse anybody.
        !          2222:
        !          2223: \kbd{code} is the parser code.
        !          2224:
        !          2225: Once this has been done, in the file \kbd{language/helpmessages.c} add in
        !          2226: exact alphabetical order a short message describing the effect of your
        !          2227: function:
        !          2228: \kbd{"name(x,y,...)=short descriptive message",}
        !          2229:
        !          2230: The message must be a single line, of arbitrary length. Do not use
        !          2231: \kbd{\bs{n}}; the necessary newlines will be inserted by GP's online help
        !          2232: functions. Optional arguments should be shown between braces (see the other
        !          2233: messages for comparison).\smallskip
        !          2234:
        !          2235: Now, you can recompile GP.
        !          2236:
        !          2237: \subsec{Example}.
        !          2238: %
        !          2239: A complete description could look like this:
        !          2240:
        !          2241: \bprog
        !          2242: {
        !          2243:   install(bnfinit0, GD0,L,DGp, ClassGroupInit, "libpari.so");
        !          2244:   addhelp(ClassGroupInit, "ClassGroupInit(P,{flag=0},{data=[]}):
        !          2245:     compute the necessary data for ...");
        !          2246: }
        !          2247: @eprog
        !          2248: which means we have a function \kbd{ClassGroupInit} under GP, which calls
        !          2249: the library function \kbd{bnfinit0} . The function has one mandatory
        !          2250: argument, and possibly two more (two \kbd{'D'} in the code), plus the
        !          2251: current real precision. More precisely, the first argument is a \kbd{GEN},
        !          2252: the second one is converted to a \kbd{long} using \kbd{itos} (\kbd{0} is
        !          2253: passed if it is omitted), and the third one is also a \kbd{GEN}, but we
        !          2254: pass \kbd{NULL} if no argument was supplied by the user. This matches the C
        !          2255: prototype (from \kbd{paridecl.h}):
        !          2256: %
        !          2257: \bprog
        !          2258:   GEN bnfinit0(GEN P, long flag, GEN data, long prec)
        !          2259: @eprog
        !          2260:
        !          2261: This function is in fact coded in \kbd{basemath/buch2.c}, and will in this
        !          2262: case be completely identical to the GP function \kbd{bnfinit} but GP does
        !          2263: not need to know about this, only that it can be found somewhere in the
        !          2264: shared library \kbd{libpari.so}.
        !          2265:
        !          2266: \misctitle{Important note:} You see in this example that it is the
        !          2267: function's responsibility to correctly interpret its operands: \kbd{data =
        !          2268: NULL} is interpreted {\it by the function\/} as an empty vector. Note that
        !          2269: since \kbd{NULL} is never a valid \kbd{GEN} pointer, this trick always
        !          2270: enables you to distinguish between a default value and actual input: the
        !          2271: user could explicitly supply an empty vector!
        !          2272:
        !          2273: \misctitle{Note:} If \kbd{install} were not available we would have to
        !          2274: modify \kbd{language/helpmessages.c}, and \kbd{language/init.c} and
        !          2275: recompile GP. The entry in \kbd{functions\_basic} corresponding to the
        !          2276: function above is actually
        !          2277: \bprog
        !          2278: { "bnfinit", 91, (void*)bnfinit0, 6, "GD0,L,DGp" }
        !          2279: @eprog
        !          2280: \vfill\eject

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>