]> granicus.if.org Git - postgresql/blob - src/backend/nodes/read.c
pgindent run. Make it all clean.
[postgresql] / src / backend / nodes / read.c
1 /*-------------------------------------------------------------------------
2  *
3  * read.c
4  *        routines to convert a string (legal ascii representation of node) back
5  *        to nodes
6  *
7  * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *        $Header: /cvsroot/pgsql/src/backend/nodes/read.c,v 1.29 2001/03/22 03:59:32 momjian Exp $
13  *
14  * HISTORY
15  *        AUTHOR                        DATE                    MAJOR EVENT
16  *        Andrew Yu                     Nov 2, 1994             file creation
17  *
18  *-------------------------------------------------------------------------
19  */
20 #include "postgres.h"
21
22 #include <ctype.h>
23 #include <errno.h>
24
25 #include "nodes/pg_list.h"
26 #include "nodes/readfuncs.h"
27
28
29 /* Static state for pg_strtok */
30 static char *pg_strtok_ptr = NULL;
31
32
33 /*
34  * stringToNode -
35  *        returns a Node with a given legal ASCII representation
36  */
37 void *
38 stringToNode(char *str)
39 {
40         char       *save_strtok;
41         void       *retval;
42
43         /*
44          * We save and restore the pre-existing state of pg_strtok. This makes
45          * the world safe for re-entrant invocation of stringToNode, without
46          * incurring a lot of notational overhead by having to pass the
47          * next-character pointer around through all the readfuncs.c code.
48          */
49         save_strtok = pg_strtok_ptr;
50
51         pg_strtok_ptr = str;            /* point pg_strtok at the string to read */
52
53         retval = nodeRead(true);        /* do the reading */
54
55         pg_strtok_ptr = save_strtok;
56
57         return retval;
58 }
59
60 /*****************************************************************************
61  *
62  * the lisp token parser
63  *
64  *****************************************************************************/
65
66 /*
67  * pg_strtok --- retrieve next "token" from a string.
68  *
69  * Works kinda like strtok, except it never modifies the source string.
70  * (Instead of storing nulls into the string, the length of the token
71  * is returned to the caller.)
72  * Also, the rules about what is a token are hard-wired rather than being
73  * configured by passing a set of terminating characters.
74  *
75  * The string is assumed to have been initialized already by stringToNode.
76  *
77  * The rules for tokens are:
78  *      * Whitespace (space, tab, newline) always separates tokens.
79  *      * The characters '(', ')', '{', '}' form individual tokens even
80  *        without any whitespace around them.
81  *      * Otherwise, a token is all the characters up to the next whitespace
82  *        or occurrence of one of the four special characters.
83  *      * A backslash '\' can be used to quote whitespace or one of the four
84  *        special characters, so that it is treated as a plain token character.
85  *        Backslashes themselves must also be backslashed for consistency.
86  *        Any other character can be, but need not be, backslashed as well.
87  *      * If the resulting token is '<>' (with no backslash), it is returned
88  *        as a non-NULL pointer to the token but with length == 0.      Note that
89  *        there is no other way to get a zero-length token.
90  *
91  * Returns a pointer to the start of the next token, and the length of the
92  * token (including any embedded backslashes!) in *length.      If there are
93  * no more tokens, NULL and 0 are returned.
94  *
95  * NOTE: this routine doesn't remove backslashes; the caller must do so
96  * if necessary (see "debackslash").
97  *
98  * NOTE: prior to release 7.0, this routine also had a special case to treat
99  * a token starting with '"' as extending to the next '"'.      This code was
100  * broken, however, since it would fail to cope with a string containing an
101  * embedded '"'.  I have therefore removed this special case, and instead
102  * introduced rules for using backslashes to quote characters.  Higher-level
103  * code should add backslashes to a string constant to ensure it is treated
104  * as a single token.
105  */
106 char *
107 pg_strtok(int *length)
108 {
109         char       *local_str;          /* working pointer to string */
110         char       *ret_str;            /* start of token to return */
111
112         local_str = pg_strtok_ptr;
113
114         while (*local_str == ' ' || *local_str == '\n' || *local_str == '\t')
115                 local_str++;
116
117         if (*local_str == '\0')
118         {
119                 *length = 0;
120                 pg_strtok_ptr = local_str;
121                 return NULL;                    /* no more tokens */
122         }
123
124         /*
125          * Now pointing at start of next token.
126          */
127         ret_str = local_str;
128
129         if (*local_str == '(' || *local_str == ')' ||
130                 *local_str == '{' || *local_str == '}')
131         {
132                 /* special 1-character token */
133                 local_str++;
134         }
135         else
136         {
137                 /* Normal token, possibly containing backslashes */
138                 while (*local_str != '\0' &&
139                            *local_str != ' ' && *local_str != '\n' &&
140                            *local_str != '\t' &&
141                            *local_str != '(' && *local_str != ')' &&
142                            *local_str != '{' && *local_str != '}')
143                 {
144                         if (*local_str == '\\' && local_str[1] != '\0')
145                                 local_str += 2;
146                         else
147                                 local_str++;
148                 }
149         }
150
151         *length = local_str - ret_str;
152
153         /* Recognize special case for "empty" token */
154         if (*length == 2 && ret_str[0] == '<' && ret_str[1] == '>')
155                 *length = 0;
156
157         pg_strtok_ptr = local_str;
158
159         return ret_str;
160 }
161
162 /*
163  * debackslash -
164  *        create a palloc'd string holding the given token.
165  *        any protective backslashes in the token are removed.
166  */
167 char *
168 debackslash(char *token, int length)
169 {
170         char       *result = palloc(length + 1);
171         char       *ptr = result;
172
173         while (length > 0)
174         {
175                 if (*token == '\\' && length > 1)
176                         token++, length--;
177                 *ptr++ = *token++;
178                 length--;
179         }
180         *ptr = '\0';
181         return result;
182 }
183
184 #define RIGHT_PAREN (1000000 + 1)
185 #define LEFT_PAREN      (1000000 + 2)
186 #define PLAN_SYM        (1000000 + 3)
187 #define AT_SYMBOL       (1000000 + 4)
188 #define ATOM_TOKEN      (1000000 + 5)
189
190 /*
191  * nodeTokenType -
192  *        returns the type of the node token contained in token.
193  *        It returns one of the following valid NodeTags:
194  *              T_Integer, T_Float, T_String, T_BitString
195  *        and some of its own:
196  *              RIGHT_PAREN, LEFT_PAREN, PLAN_SYM, AT_SYMBOL, ATOM_TOKEN
197  *
198  *        Assumption: the ascii representation is legal
199  */
200 static NodeTag
201 nodeTokenType(char *token, int length)
202 {
203         NodeTag         retval;
204         char       *numptr;
205         int                     numlen;
206         char       *endptr;
207
208         /*
209          * Check if the token is a number
210          */
211         numptr = token;
212         numlen = length;
213         if (*numptr == '+' || *numptr == '-')
214                 numptr++, numlen--;
215         if ((numlen > 0 && isdigit((unsigned char) *numptr)) ||
216         (numlen > 1 && *numptr == '.' && isdigit((unsigned char) numptr[1])))
217         {
218
219                 /*
220                  * Yes.  Figure out whether it is integral or float; this requires
221                  * both a syntax check and a range check. strtol() can do both for
222                  * us. We know the token will end at a character that strtol will
223                  * stop at, so we do not need to modify the string.
224                  */
225                 errno = 0;
226                 (void) strtol(token, &endptr, 10);
227                 if (endptr != token + length || errno == ERANGE)
228                         return T_Float;
229                 return T_Integer;
230         }
231
232         /*
233          * these three cases do not need length checks, since pg_strtok() will
234          * always treat them as single-byte tokens
235          */
236         else if (*token == '(')
237                 retval = LEFT_PAREN;
238         else if (*token == ')')
239                 retval = RIGHT_PAREN;
240         else if (*token == '{')
241                 retval = PLAN_SYM;
242         else if (*token == '@' && length == 1)
243                 retval = AT_SYMBOL;
244         else if (*token == '\"' && length > 1 && token[length - 1] == '\"')
245                 retval = T_String;
246         else if (*token == 'b')
247                 retval = T_BitString;
248         else
249                 retval = ATOM_TOKEN;
250         return retval;
251 }
252
253 /*
254  * nodeRead -
255  *        Slightly higher-level reader.
256  *
257  * This routine applies some semantic knowledge on top of the purely
258  * lexical tokenizer pg_strtok().       It can read
259  *      * Value token nodes (integers, floats, or strings);
260  *      * Plan nodes (via parsePlanString() from readfuncs.c);
261  *      * Lists of the above.
262  *
263  * We assume pg_strtok is already initialized with a string to read (hence
264  * this should only be invoked from within a stringToNode operation).
265  * Any callers should set read_car_only to true.
266  */
267 void *
268 nodeRead(bool read_car_only)
269 {
270         char       *token;
271         int                     tok_len;
272         NodeTag         type;
273         Node       *this_value,
274                            *return_value;
275         bool            make_dotted_pair_cell = false;
276
277         token = pg_strtok(&tok_len);
278
279         if (token == NULL)
280                 return NULL;
281
282         type = nodeTokenType(token, tok_len);
283
284         switch (type)
285         {
286                 case PLAN_SYM:
287                         this_value = parsePlanString();
288                         token = pg_strtok(&tok_len);
289                         if (token == NULL || token[0] != '}')
290                                 elog(ERROR, "nodeRead: did not find '}' at end of plan node");
291                         if (!read_car_only)
292                                 make_dotted_pair_cell = true;
293                         else
294                                 make_dotted_pair_cell = false;
295                         break;
296                 case LEFT_PAREN:
297                         if (!read_car_only)
298                         {
299                                 List       *l = makeNode(List);
300
301                                 lfirst(l) = nodeRead(false);
302                                 lnext(l) = nodeRead(false);
303                                 this_value = (Node *) l;
304                         }
305                         else
306                                 this_value = nodeRead(false);
307                         break;
308                 case RIGHT_PAREN:
309                         this_value = NULL;
310                         break;
311                 case AT_SYMBOL:
312                         this_value = NULL;
313                         break;
314                 case ATOM_TOKEN:
315                         if (tok_len == 0)
316                         {
317                                 /* must be "<>" */
318                                 this_value = NULL;
319
320                                 /*
321                                  * It might be NULL but it is an atom!
322                                  */
323                                 if (read_car_only)
324                                         make_dotted_pair_cell = false;
325                                 else
326                                         make_dotted_pair_cell = true;
327                         }
328                         else
329                         {
330                                 /* !attention! result is not a Node.  Use with caution. */
331                                 this_value = (Node *) debackslash(token, tok_len);
332                                 make_dotted_pair_cell = true;
333                         }
334                         break;
335                 case T_Integer:
336
337                         /*
338                          * we know that the token terminates on a char atol will stop
339                          * at
340                          */
341                         this_value = (Node *) makeInteger(atol(token));
342                         make_dotted_pair_cell = true;
343                         break;
344                 case T_Float:
345                         {
346                                 char       *fval = (char *) palloc(tok_len + 1);
347
348                                 memcpy(fval, token, tok_len);
349                                 fval[tok_len] = '\0';
350                                 this_value = (Node *) makeFloat(fval);
351                                 make_dotted_pair_cell = true;
352                         }
353                         break;
354                 case T_String:
355                         /* need to remove leading and trailing quotes, and backslashes */
356                         this_value = (Node *) makeString(debackslash(token + 1, tok_len - 2));
357                         make_dotted_pair_cell = true;
358                         break;
359                 case T_BitString:
360                         {
361                                 char       *val = palloc(tok_len);
362
363                                 /* skip leading 'b' */
364                                 strncpy(val, token + 1, tok_len - 1);
365                                 val[tok_len - 1] = '\0';
366                                 this_value = (Node *) makeBitString(val);
367                                 break;
368                         }
369                 default:
370                         elog(ERROR, "nodeRead: Bad type %d", type);
371                         this_value = NULL;      /* keep compiler happy */
372                         break;
373         }
374         if (make_dotted_pair_cell)
375         {
376                 List       *l = makeNode(List);
377
378                 lfirst(l) = this_value;
379
380                 if (!read_car_only)
381                         lnext(l) = nodeRead(false);
382                 else
383                         lnext(l) = NULL;
384                 return_value = (Node *) l;
385         }
386         else
387                 return_value = this_value;
388         return return_value;
389 }