]> granicus.if.org Git - postgresql/blob - src/backend/nodes/read.c
Error message editing in backend/bootstrap, /lib, /nodes, /port.
[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-2002, 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.34 2003/07/22 23:30:38 tgl 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 NODE_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, NODE_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
207         /*
208          * Check if the token is a number
209          */
210         numptr = token;
211         numlen = length;
212         if (*numptr == '+' || *numptr == '-')
213                 numptr++, numlen--;
214         if ((numlen > 0 && isdigit((unsigned char) *numptr)) ||
215         (numlen > 1 && *numptr == '.' && isdigit((unsigned char) numptr[1])))
216         {
217                 /*
218                  * Yes.  Figure out whether it is integral or float; this requires
219                  * both a syntax check and a range check. strtol() can do both for
220                  * us. We know the token will end at a character that strtol will
221                  * stop at, so we do not need to modify the string.
222                  */
223                 long            val;
224                 char       *endptr;
225
226                 errno = 0;
227                 val = strtol(token, &endptr, 10);
228                 if (endptr != token + length || errno == ERANGE
229 #ifdef HAVE_LONG_INT_64
230                 /* if long > 32 bits, check for overflow of int4 */
231                         || val != (long) ((int32) val)
232 #endif
233                         )
234                         return T_Float;
235                 return T_Integer;
236         }
237
238         /*
239          * these three cases do not need length checks, since pg_strtok() will
240          * always treat them as single-byte tokens
241          */
242         else if (*token == '(')
243                 retval = LEFT_PAREN;
244         else if (*token == ')')
245                 retval = RIGHT_PAREN;
246         else if (*token == '{')
247                 retval = NODE_SYM;
248         else if (*token == '@' && length == 1)
249                 retval = AT_SYMBOL;
250         else if (*token == '\"' && length > 1 && token[length - 1] == '\"')
251                 retval = T_String;
252         else if (*token == 'b')
253                 retval = T_BitString;
254         else
255                 retval = ATOM_TOKEN;
256         return retval;
257 }
258
259 /*
260  * nodeRead -
261  *        Slightly higher-level reader.
262  *
263  * This routine applies some semantic knowledge on top of the purely
264  * lexical tokenizer pg_strtok().       It can read
265  *      * Value token nodes (integers, floats, or strings);
266  *      * General nodes (via parseNodeString() from readfuncs.c);
267  *      * Lists of the above.
268  *
269  * We assume pg_strtok is already initialized with a string to read (hence
270  * this should only be invoked from within a stringToNode operation).
271  * Any callers should set read_car_only to true.
272  */
273 void *
274 nodeRead(bool read_car_only)
275 {
276         char       *token;
277         int                     tok_len;
278         NodeTag         type;
279         Node       *this_value,
280                            *return_value;
281         bool            make_dotted_pair_cell = false;
282
283         token = pg_strtok(&tok_len);
284
285         if (token == NULL)
286                 return NULL;
287
288         type = nodeTokenType(token, tok_len);
289
290         switch (type)
291         {
292                 case NODE_SYM:
293                         this_value = parseNodeString();
294                         token = pg_strtok(&tok_len);
295                         if (token == NULL || token[0] != '}')
296                                 elog(ERROR, "did not find '}' at end of input node");
297                         if (!read_car_only)
298                                 make_dotted_pair_cell = true;
299                         else
300                                 make_dotted_pair_cell = false;
301                         break;
302                 case LEFT_PAREN:
303                         if (!read_car_only)
304                         {
305                                 List       *l = makeNode(List);
306
307                                 lfirst(l) = nodeRead(false);
308                                 lnext(l) = nodeRead(false);
309                                 this_value = (Node *) l;
310                         }
311                         else
312                                 this_value = nodeRead(false);
313                         break;
314                 case RIGHT_PAREN:
315                         this_value = NULL;
316                         break;
317                 case AT_SYMBOL:
318                         this_value = NULL;
319                         break;
320                 case ATOM_TOKEN:
321                         if (tok_len == 0)
322                         {
323                                 /* must be "<>" */
324                                 this_value = NULL;
325
326                                 /*
327                                  * It might be NULL but it is an atom!
328                                  */
329                                 if (read_car_only)
330                                         make_dotted_pair_cell = false;
331                                 else
332                                         make_dotted_pair_cell = true;
333                         }
334                         else
335                         {
336                                 /* !attention! result is not a Node.  Use with caution. */
337                                 this_value = (Node *) debackslash(token, tok_len);
338                                 make_dotted_pair_cell = true;
339                         }
340                         break;
341                 case T_Integer:
342
343                         /*
344                          * we know that the token terminates on a char atol will stop
345                          * at
346                          */
347                         this_value = (Node *) makeInteger(atol(token));
348                         make_dotted_pair_cell = true;
349                         break;
350                 case T_Float:
351                         {
352                                 char       *fval = (char *) palloc(tok_len + 1);
353
354                                 memcpy(fval, token, tok_len);
355                                 fval[tok_len] = '\0';
356                                 this_value = (Node *) makeFloat(fval);
357                                 make_dotted_pair_cell = true;
358                         }
359                         break;
360                 case T_String:
361                         /* need to remove leading and trailing quotes, and backslashes */
362                         this_value = (Node *) makeString(debackslash(token + 1, tok_len - 2));
363                         make_dotted_pair_cell = true;
364                         break;
365                 case T_BitString:
366                         {
367                                 char       *val = palloc(tok_len);
368
369                                 /* skip leading 'b' */
370                                 strncpy(val, token + 1, tok_len - 1);
371                                 val[tok_len - 1] = '\0';
372                                 this_value = (Node *) makeBitString(val);
373                                 break;
374                         }
375                 default:
376                         elog(ERROR, "unrecognized node type: %d", (int) type);
377                         this_value = NULL;      /* keep compiler happy */
378                         break;
379         }
380         if (make_dotted_pair_cell)
381         {
382                 List       *l = makeNode(List);
383
384                 lfirst(l) = this_value;
385
386                 if (!read_car_only)
387                         lnext(l) = nodeRead(false);
388                 else
389                         lnext(l) = NULL;
390                 return_value = (Node *) l;
391         }
392         else
393                 return_value = this_value;
394         return return_value;
395 }