Debian Codegraph @

src/sexpr/sexp.h

raw symbols SCIP
1 /**
2 This software and ancillary information (herein called "SOFTWARE")
3 called Supermon is made available under the terms described
4 here. The SOFTWARE has been approved for release with associated
5 LA-CC Number LA-CC 99-51.
6
7 Unless otherwise indicated, this SOFTWARE has been authored by an
8 employee or employees of the University of California, operator of the
9 Los Alamos National Laboratory under Contract No. W-7405-ENG-36 with
10 the U.S. Department of Energy. The U.S. Government has rights to use,
11 reproduce, and distribute this SOFTWARE, and to allow others to do so.
12 The public may copy, distribute, prepare derivative works and publicly
13 display this SOFTWARE without charge, provided that this Notice and
14 any statement of authorship are reproduced on all copies. Neither the
15 Government nor the University makes any warranty, express or implied,
16 or assumes any liability or responsibility for the use of this
17 SOFTWARE.
18
19 If SOFTWARE is modified to produce derivative works, such modified
20 SOFTWARE should be clearly marked, so as not to confuse it with the
21 version available from LANL.
22 **/
23 /** NOTICE: This software is licensed under the GNU Public License, which
24 is included as LICENSE_GPL in this source distribution. **/
25 /** NOTE: This library is part of the supermon project, hence the name
26 supermon above. **/
27 #ifndef __SEXP_H__
28 #define __SEXP_H__
29
30 #include <stdio.h>
31 #include "faststack.h"
32
33 /**
34 * \mainpage A small and quick S-expression parsing library.
35 *
36 * \section intro Intro
37 *
38 * This library was created to provide s-expression parsing and manipulation
39 * facilities to C and C++ programs. The primary goals were speed and
40 * efficiency - low memory impact, and the highest speed we could achieve in
41 * parsing. Suprisingly, no other libraries on the net were found that
42 * were not bloated with features or involved embedding a full-fledged
43 * LISP or Scheme interpreter into our programs. So, this library evolved
44 * to fill this gap. As such, it does not guarantee that every valid LISP
45 * expression is parseable (although every parseable expression is valid LISP),
46 * and many features that are not required aren't implemented. See Rivest's
47 * S-expression library for an example of a much more featureful library.
48 *
49 * What features does this library include? At the heart of the code is a
50 * continuation-based parser implementing a basic state machine. Continuations
51 * allow users to accumulate multiple streams of characters, and parse
52 * each stream simultaneously. A continuation allows the parser to stop
53 * midstream, start working on a new expression, and return to the first
54 * without corruption of complex state management in the users code. No
55 * threads, no forking, nothing more than a data structure that must be passed
56 * in and captured as data becomes available to parse. Once an expression
57 * has been parsed, a simple structure is returned that represents
58 * the "abstract syntax tree" of the parsed expression. For the majority
59 * of users, the parser and this data structure will be all that they will
60 * ever need to see. For convenience reasons, other functions such as I/O
61 * wrappers and AST traversal routines have been included, but they are
62 * not required if users don't wish to use them.
63 *
64 * \section performance Performance Results
65 *
66 * The standard benchmark to compare versions of this parser has been the
67 * "torture.c" file included in the tests/ subdirectory. This file takes
68 * a large s-expression via STDIN, and parses, unparses, and destroys it
69 * 1,000 times. The following numbers reflect tests done on a
70 * representative expression from Supermon, the tool that this code was
71 * created for.
72 *
73 * - <B>v0.1.1</B> : 1.61s
74 * - <B>v0.1.2</B> : 1.12s
75 * - <B>v0.2.0</B> : 1.07s
76 * - <B>v0.2.1</B> : 1.09s
77 * - <B>v0.2.2</B> : 1.09s
78 * - <B>v0.2.3</B> : 1.11s
79 * - <B>v0.3.0</B> : 0.42s
80 *
81 * \section license License Information
82 *
83 * This software and ancillary information (herein called "SOFTWARE")
84 * called Supermon is made available under the terms described
85 * here. The SOFTWARE has been approved for release with associated
86 * LA-CC Number LA-CC 99-51.
87 *
88 * Unless otherwise indicated, this SOFTWARE has been authored by an
89 * employee or employees of the University of California, operator of the
90 * Los Alamos National Laboratory under Contract No. W-7405-ENG-36 with
91 * the U.S. Department of Energy. The U.S. Government has rights to use,
92 * reproduce, and distribute this SOFTWARE, and to allow others to do so.
93 * The public may copy, distribute, prepare derivative works and publicly
94 * display this SOFTWARE without charge, provided that this Notice and
95 * any statement of authorship are reproduced on all copies. Neither the
96 * Government nor the University makes any warranty, express or implied,
97 * or assumes any liability or responsibility for the use of this
98 * SOFTWARE.
99 *
100 * If SOFTWARE is modified to produce derivative works, such modified
101 * SOFTWARE should be clearly marked, so as not to confuse it with the
102 * version available from LANL.
103 *
104 * This software is licensed under the GNU Public License, which
105 * is included as LICENSE_GPL in this source distribution.
106 *
107 * This library is part of the Supermon project, hence the name
108 * "Supermon" above. See http://www.acl.lanl.gov/supermon/ for details on
109 * that project.
110 */
111
112 /**
113 * \file sexp.h
114 *
115 * \brief API for a small, fast and portable s-expression parser library.
116 *
117 * Written by Matt Sottile ([email protected]), January 2002. See LICENSE
118 * file for licensing details.
119 */
120
121 /*==============*/
122 /* ENUMERATIONS */
123 /*==============*/
124
125 /**
126 * An element in an s-expression can be one of two types: a <i>value</i>
127 * represents an atom with an associated text value. A <i>list</i>
128 * represents an s-expression, and the element contains a pointer to
129 * the head element of the associated s-expression.
130 */
131 typedef enum {
132 /**
133 * An atom of some type. See atom type (aty) field of element structure
134 * for details as to which atom type this is.
135 */
136 SEXP_VALUE,
137
138 /**
139 * A list. This means the element points to an element representing the
140 * head of a list.
141 */
142 SEXP_LIST
143 } elt_t;
144
145 /**
146 * For an element that represents a value, the value can be interpreted
147 * as a more specific type. A <i>basic</i> value is a simple string with
148 * no whitespace (and therefore no quotes required). A <i>double quote</i>
149 * value, or <i>dquote</i>, is one that contains characters (such as
150 * whitespace) that requires quotation marks to contain the string. A
151 * <i>single quote</i> value, or <i>squote</i>, represents an element that is
152 * prefaced with a single tick-mark. This can be either an atom or
153 * s-expression, and the result is that the parser does not attempt to parse
154 * the element following the tick mark. It is simply stored as text. This
155 * is similar to the meaning of a tick mark in the Scheme or LISP family
156 * of programming languages.
157 */
158 typedef enum {
159
160 /**
161 * Basic, unquoted value.
162 */
163 SEXP_BASIC,
164
165 /**
166 * Single quote (tick-mark) value - contains a string representing
167 * a non-parsed portion of the s-expression.
168 */
169 SEXP_SQUOTE,
170
171 /**
172 * Double-quoted string. Similar to a basic value, but potentially
173 * containing white-space.
174 */
175 SEXP_DQUOTE
176 } atom_t;
177
178 /*============*/
179 /* STRUCTURES */
180 /*============*/
181
182 /**
183 * An s-expression is represented as a linked structure of elements,
184 * where each element is either an <I>atom</I> or <I>list</I>. An
185 * atom corresponds to a string, while a list corresponds to an
186 * s-expression. The following grammar represents our definition of
187 * an s-expression:<P>
188 *
189 * <pre>
190 * sexpr ::= ( sx )
191 * sx ::= atom sxtail | sexpr sxtail | 'sexpr sxtail | 'atom sxtail | NULL
192 * sxtail ::= sx | NULL
193 * atom ::= quoted | value
194 * quoted ::= "ws_string"
195 * value ::= nws_string
196 * </pre>
197 * <P>
198 *
199 * An atom can either be a quoted string, which is a string containing
200 * whitespace (possibly) surrounded by double quotes, or a non-whitespace
201 * string that does not require surrounding quotes. An element representing
202 * an atom will have a type of <i>value</i> and data stored in the <i>val</i>
203 * field. An element of type <i>list</i> represents an s-expression
204 * corresponding to <i>sexpr</i> in the grammar, and will have a pointer to
205 * the head of the appropriate s-expression. Details regarding these fields
206 * and their values given with the fields themselves. Notice that a single
207 * quote can appear directly before an s-expression or atom, similar to the
208 * use in LISP.
209 */
210 typedef struct elt {
211 /**
212 * The element has a type that determines how the structure is used. If
213 * the type is <B>SEXP_VALUE</B>, then a programmer knows that the val field
214 * is meaningful and contains the data associated with this element of the
215 * s-expression. If the type is <B>SEXP_LIST</B>, then the list field
216 * contains a pointer to the s-expression element representing the head of
217 * the list. For each case, the field for the opposite case contains no
218 * meaningful data and using them in any way is likely to cause an error.
219 */
220 elt_t ty;
221
222 /**
223 * If the type of the element is <B>SEXP_VALUE</B> this field will contain
224 * the actual data represented by this element.
225 */
226 char *val;
227
228 /**
229 * Number of bytes allocated for val.
230 */
231 int val_allocated;
232
233 /**
234 * Number of bytes used in val (<= val_allocated).
235 */
236 int val_used;
237
238 /**
239 * If the type of the element is <B>SEXP_LIST</B>, this field will contain
240 * a pointer to the head element of the list.
241 */
242 struct elt *list;
243
244 /**
245 * The <I>next</I> field is a pointer to the next element in the current
246 * expression. If this element is the last element in the s-expression,
247 * this field will be <I>NULL</I>.
248 */
249 struct elt *next;
250
251 /**
252 * For elements that represent <I>values</I>, this field will specify the
253 * specific type of value that it represents. This can be used by
254 * functions to determine how this value should be printed (ie: how it
255 * should be quoted) or interpreted (ie: interpreting s-expressions that
256 * are prefixed with a tick-mark.).
257 */
258 atom_t aty;
259
260 } sexp_t;
261
262 /**
263 * A continuation is used by the parser to save and restore state between
264 * invocations to support partial parsing of strings. For example, if we
265 * pass the string "(foo bar)(goo car)" to the parser, we want to be able
266 * to retrieve each s-expression one at a time - it would be difficult to
267 * return all s-expressions at once without knowing how many there are in
268 * advance (this would require more memory management than we want...).
269 * So, by using a continuation-based parser, we can call it with this string
270 * and have it return a continuation when it has parsed the first
271 * s-expression. Once we have processed the s-expression (accessible
272 * through the <i>last_sexpr</i> field of the continuation), we can call
273 * the parser again with the same string and continuation, and it will be
274 * able to pick up where it left off.<P>
275 *
276 * We use continuations instead of a state-ful parser to allow multiple
277 * concurrent strings to be parsed by simply maintaining a set of
278 * continuations. Manipulating continuations by hand is required if the
279 * continuation-based parser is called directly. This is <b>not
280 * recommended</b> unless you are willing to deal with potential errors and
281 * are willing to learn exactly how the continuation relates to the
282 * internals of the parser. A simpler approach is to use either the
283 * <i>parse_sexp</i> function that simply returns an s-expression without
284 * exposing the continuations, or the <i>iparse_sexp</i> function that
285 * allows iteratively popping one s-expression at a time from a string
286 * containing one or more s-expressions. Refer to the documentation for
287 * each parsing function for further details on behavior and usage.
288 */
289 typedef struct pcont {
290 /**
291 * The parser stack used for iterative parsing.
292 */
293 faststack_t *stack;
294
295 /**
296 * The last full s-expression encountered by the parser. If this is
297 * NULL, the parser has not encountered a full s-expression and more
298 * data is required for the current s-expression being parsed. If this
299 * is non-NULL, then the parser has encountered one s-expression and may
300 * be partially through parsing the next s-expression.
301 */
302 sexp_t *last_sexp;
303
304 /**
305 * Pointer to a temporary buffer used to store atom values during parsing.
306 */
307 char *val;
308
309 /**
310 * Current number of bytes allocated for val.
311 */
312 int val_allocated;
313
314 /**
315 * Current number of used bytes in val.
316 */
317 int val_used;
318
319 /**
320 * Pointer to the character following the last character in the current
321 * atom value being parsed.
322 */
323 char *vcur;
324
325 /**
326 * Pointer to the last character to examine in the string being parsed.
327 * When the parser is called with the continuation, this is the first
328 * character that will be processed. If this is NULL, the parser will
329 * start parsing at the beginning of the string passed into the parser.
330 */
331 char *lastPos;
332
333 /**
334 * This is a pointer to the beginning of the current string being
335 * processed. lastPos is a pointer to some value inside the string
336 * that this points to.
337 */
338 char *sbuffer;
339
340 /**
341 * This is the depth of parenthesis (the number of left parens encountered)
342 * that the parser is currently working with.
343 */
344 unsigned int depth;
345
346 /**
347 * This is the depth of parenthesis encountered after a single quote (tick)
348 * if the character immediately following the tick was a left paren.
349 */
350 unsigned int qdepth;
351
352 /**
353 * This is the state ID of the current state of the parser in the
354 * DFA representing the parser. The current parser is a DFA based parser
355 * to simplify restoring the proper state from a continuation.
356 */
357 unsigned int state;
358
359 /**
360 * This is a flag indicating whether the next character to be processed
361 * should be assumed to have been prefaced with a '\' character to escape
362 * it.
363 */
364 unsigned int esc;
365
366 /**
367 * Error code. Used to indicate that the continuation being returned does
368 * not represent a successful parsing and thus the contents aren't of much
369 * value. If this value is 0, no error occurred. Otherwise, it will be 1.
370 */
371 unsigned int error;
372 } pcont_t;
373
374 /**
375 * This structure is a wrapper around a standard I/O file descriptor and
376 * the parsing infrastructure (continuation and a buffer) required to
377 * parse off of it. This is used so that routines can hide the loops and
378 * details required to accumulate up data read off of the file descriptor
379 * and parse expressions individually out of it.
380 */
381 typedef struct sexp_iowrap {
382 /**
383 * Continuation used to parse off of the file descriptor.
384 */
385 pcont_t *cc;
386
387 /**
388 * The file descriptor. Currently CANNOT be a socket since implementation
389 * uses read(), not recv().
390 */
391 int fd;
392
393 /**
394 * Buffer to read data into before parsing.
395 */
396 char buf[BUFSIZ];
397
398 /**
399 * Byte count for last read. If it is -1, there was an error. Otherwise,
400 * it will be a value from 0 to BUFSIZ.
401 */
402 int cnt;
403 } sexp_iowrap_t;
404
405 /*===========*/
406 /* FUNCTIONS */
407 /*===========*/
408
409 /* this is for C++ users */
410 #ifdef __cplusplus
411 extern "C" {
412 #endif
413 /**
414 * Set the parameters on atom value buffer allocation and growth sizes.
415 * This is an important point for performance tuning, as many factors in
416 * the expected expression structure must be taken into account such as:
417 *
418 * - Average size of atom values
419 * - Variance in sizes of atom values
420 * - Amount of memory that is tolerably ''wasted'' (allocated but not
421 * used)
422 *
423 * The \a ss parameter specifies the initial size of all atom buffers.
424 * Ideally, this should be sufficiently large to capture MOST atom values,
425 * or at least close enough such that one growth is required. The
426 * \a gs parameter specifies the number of bytes to increase the buffer size
427 * by when space is exhausted. A safe choice for parameter sizes would
428 * be on the order of the average size for \a ss, and one standard
429 * deviation for \a gs. This ensures that 50% of all expressions are
430 * guaranteed to fit in the initial buffer, and rougly 80-90% will fit in
431 * one growth. If memory is not an issue, choosing ss to be the mean plus
432 * one standard deviation will capture 80-90% of expressions in the initial
433 * buffer, and a gs of one standard deviation will capture nearly all
434 * expressions.
435 *
436 * Note: These parameters can be tuned at runtime as needs change, and they
437 * will be applied to all expressions and expression elements parsed after
438 * they are modified. They will not be applied retroactively to expressions
439 * that have already been parsed.
440 */
441 void set_parser_buffer_params(int ss, int gs);
442
443 /**
444 * return an allocated sexp_t. This structure may be an already allocated
445 * one from the stack or a new one if none are available. Use this instead
446 * of manually mallocing if you want to avoid excessive mallocs. <I>Note:
447 * Mallocing your own expressions is fine - you can even use
448 * sexp_t_deallocate to deallocate them and put them in the pool.</I>
449 * Also, if the stack has not been initialized yet, this does so.
450 */
451 sexp_t *sexp_t_allocate();
452
453 /**
454 * given a malloc'd sexp_t element, put it back into the already-allocated
455 * element stack. This method will allocate a stack if one has not been
456 * allocated already.
457 */
458 void sexp_t_deallocate(sexp_t *s);
459
460 /**
461 * In the event that someone wants us to release ALL of the memory used
462 * between calls by the library, they can free it. If you don't call
463 * this, the caches will be persistent for the lifetime of the library
464 * user.
465 */
466 void sexp_cleanup();
467
468 /**
469 * print a sexp_t struct as a string in the LISP style. If the buffer
470 * is large enough and the conversion is successful, the return value
471 * represents the length of the string contained in the buffer. If the
472 * buffer was too small, or some other error occurred, the return
473 * value is -1 and the contents of the buffer should not be assumed to
474 * contain any useful information.
475 */
476 int print_sexp(char *loc, int size, sexp_t *e);
477
478 /**
479 * \deprecated This function has been replaced with a wrapper around the
480 * IO wrapper based function read_one_sexp. This is to eliminate the
481 * rather braindead method this function used originally to determine
482 * whether or not it had read a complete expression. Now, the parser
483 * under the covers does this FOR the user, and prints the result
484 * into the buffer. In most cases, this buffer will be immediately
485 * passed back to the parser and parsed yet again - a waste of time.
486 * So if you use this, stop, and use the IO wrapper routines. They're
487 * much more convenient, I assure you. Plus, no need to worry about
488 * buffer sizes anymore.
489 */
490 int read_sexp(char *buf, int size, int f);
491
492 /**
493 * \deprecated This function has been replaced with a wrapper around the
494 * IO wrapper based function read_one_sexp. This is to eliminate the
495 * rather braindead method this function used originally to determine
496 * whether or not it had read a complete expression. Now, the parser
497 * under the covers does this FOR the user, and prints the result
498 * into the buffer. In most cases, this buffer will be immediately
499 * passed back to the parser and parsed yet again - a waste of time.
500 * So if you use this, stop, and use the IO wrapper routines. They're
501 * much more convenient, I assure you. Plus, no need to worry about
502 * buffer sizes anymore.
503 */
504 int fread_sexp(char *buf, int size, FILE *fd);
505
506 /**
507 * create an initial continuation for parsing the given string
508 */
509 pcont_t *init_continuation(char *str);
510
511 /**
512 * destroy a continuation. This involves cleaning up what it contains,
513 * and cleaning up the continuation itself.
514 */
515 void destroy_continuation (pcont_t * pc);
516
517 /**
518 * <B>temporary function</B> - this function will be removed as soon as
519 * read and fread_sexp are removed. This handles cleaning up the global
520 * iowrap structure used to fake read and fread_sexp behavior.
521 */
522 int cleanup_sexp_io();
523
524 /**
525 * create an IO wrapper structure around a file descriptor.
526 */
527 sexp_iowrap_t *init_iowrap(int fd);
528
529 /**
530 * destroy an IO wrapper structure
531 */
532 void destroy_iowrap(sexp_iowrap_t *iow);
533
534 /**
535 * given and IO wrapper handle, read one s-expression off of it. this
536 * expression may be contained in a continuation, so there is no
537 * guarantee that under the covers an IO read actually is occuring.
538 * returning null implies no s-expression was able to be read.
539 */
540 sexp_t *read_one_sexp(sexp_iowrap_t *iow);
541
542 /**
543 * wrapper around parser for compatibility.
544 */
545 sexp_t *parse_sexp(char *s, int len);
546
547 /**
548 * wrapper around parser for friendlier continuation use
549 * pre-condition : continuation (cc) is NON-NULL!
550 */
551 sexp_t *iparse_sexp(char *s, int len, pcont_t *cc);
552
553 /**
554 * given a LISP style s-expression string, parse it into a set of
555 * connected sexp_t structures.
556 */
557 pcont_t *cparse_sexp(char *s, int len, pcont_t *pc);
558
559 /**
560 * given a sexp_t structure, free the memory it uses (and recursively free
561 * the memory used by all sexp_t structures that it references). Note
562 * that this will call the deallocation routine for sexp_t elements.
563 * This means that memory isn't freed, but stored away in a cache of
564 * pre-allocated elements. This is an optimization to speed up the
565 * parser to eliminate wasteful free and re-malloc calls.
566 */
567 void destroy_sexp(sexp_t *s);
568
569 /* this is for C++ users */
570 #ifdef __cplusplus
571 }
572 #endif
573
574 #include "sexp_ops.h"
575
576 #endif /* __SEXP_H__ */
577