summaryrefslogtreecommitdiffstats
path: root/src/vppinfra/zvec.c
blob: d062e5f7db1556957de328a660afb69a55e09918 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/*
 * Copyright (c) 2015 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
  Copyright (c) 2001, 2002, 2003, 2005 Eliot Dresselhaus

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <vppinfra/bitmap.h>
#include <vppinfra/bitops.h>	/* for next_with_same_number_of_set_bits */
#include <vppinfra/error.h>	/* for ASSERT */
#include <vppinfra/mem.h>
#include <vppinfra/os.h>	/* for os_panic */
#include <vppinfra/vec.h>
#include <vppinfra/zvec.h>

/* Consider coding as bitmap, coding = 2^c_0 + 2^c_1 + ... + 2^c_n
   With c_0 < c_1 < ... < c_n.  coding == 0 represents c_n = BITS (uword).

   Unsigned integers i = 0 ... are represented as follows:

       0 <= i < 2^c_0       	(i << 1) | (1 << 0) binary:   i 1
   2^c_0 <= i < 2^c_0 + 2^c_1   (i << 2) | (1 << 1) binary: i 1 0
   ...                                              binary: i 0 ... 0

   Smaller numbers use less bits.  Coding is chosen so that encoding
   of given histogram of typical values gives smallest number of bits.
   The number and position of coding bits c_i are used to best fit the
   histogram of typical values.
*/

/* Decode given compressed data.  Return number of compressed data
   bits used. */
uword
zvec_decode (uword coding, uword zdata, uword * n_zdata_bits)
{
  uword c, d, result, n_bits;
  uword explicit_end, implicit_end;

  result = 0;
  n_bits = 0;
  while (1)
    {
      c = first_set (coding);
      implicit_end = c == coding;
      explicit_end = (zdata & 1) & ~implicit_end;
      d = (zdata >> explicit_end) & (c - 1);
      if (explicit_end | implicit_end)
	{
	  result += d;
	  n_bits += min_log2 (c) + explicit_end;
	  break;
	}
      n_bits += 1;
      result += c;
      coding ^= c;
      zdata >>= 1;
    }

  if (coding == 0)
    n_bits = BITS (uword);

  *n_zdata_bits = n_bits;
  return result;
}

uword
zvec_encode (uword coding, uword data, uword * n_result_bits)
{
  uword c, shift, result;
  uword explicit_end, implicit_end;

  /* Data must be in range.  Note special coding == 0
     would break for data - 1 <= coding. */
  ASSERT (data <= coding - 1);

  shift = 0;
  while (1)
    {
      c = first_set (coding);
      implicit_end = c == coding;
      explicit_end = ((data & (c - 1)) == data);
      if (explicit_end | implicit_end)
	{
	  uword t = explicit_end & ~implicit_end;
	  result = ((data << t) | t) << shift;
	  *n_result_bits =
	    /* data bits */ (c == 0 ? BITS (uword) : min_log2 (c))
	    /* shift bits */  + shift + t;
	  return result;
	}
      data -= c;
      coding ^= c;
      shift++;
    }

  /* Never reached. */
  ASSERT (0);
  return ~0;
}

always_inline uword
get_data (void *data, uword data_bytes, uword is_signed)
{
  if (data_bytes == 1)
    return is_signed ? zvec_signed_to_unsigned (*(i8 *) data) : *(u8 *) data;
  else if (data_bytes == 2)
    return is_signed ? zvec_signed_to_unsigned (*(i16 *) data) : *(u16 *)
      data;
  else if (data_bytes == 4)
    return is_signed ? zvec_signed_to_unsigned (*(i32 *) data) : *(u32 *)
      data;
  else if (data_bytes == 8)
    return is_signed ? zvec_signed_to_unsigned (*(i64 *) data) : *(u64 *)
      data;
  else
    {
      os_panic ();
      return ~0;
    }
}

always_inline void
put_data (void *data, uword data_bytes, uword is_signed, uword x)
{
  if (data_bytes == 1)
    {
      if (is_signed)
	*(i8 *) data = zvec_unsigned_to_signed (x);
      else
	*(u8 *) data = x;
    }
  else if (data_bytes == 2)
    {
      if (is_signed)
	*(i16 *) data = zvec_unsigned_to_signed (x);
      else
	*(u16 *) data = x;
    }
  else if (data_bytes == 4)
    {
      if (is_signed)
	*(i32 *) data = zvec_unsigned_to_signed (x);
      else
	*(u32 *) data = x;
    }
  else if (data_bytes == 8)
    {
      if (is_signed)
	*(i64 *) data = zvec_unsigned_to_signed (x);
      else
	*(u64 *) data = x;
    }
  else
    {
      os_panic ();
    }
}

always_inline uword *
zvec_encode_inline (uword * zvec,
		    uword * zvec_n_bits,
		    uword coding,
		    void *data,
		    uword data_stride,
		    uword n_data, uword data_bytes, uword is_signed)
{
  uword i;

  i = *zvec_n_bits;
  while (n_data >= 1)
    {
      uword d0, z0, l0;

      d0 = get_data (data + 0 * data_stride, data_bytes, is_signed);
      data += 1 * data_stride;
      n_data -= 1;

      z0 = zvec_encode (coding, d0, &l0);
      zvec = clib_bitmap_set_multiple (zvec, i, z0, l0);
      i += l0;
    }

  *zvec_n_bits = i;
  return zvec;
}

#define _(TYPE,IS_SIGNED)					\
  uword * zvec_encode_##TYPE (uword * zvec,			\
			      uword * zvec_n_bits,		\
			      uword coding,			\
			      void * data,			\
			      uword data_stride,		\
			      uword n_data)			\
  {								\
    return zvec_encode_inline (zvec, zvec_n_bits,		\
			    coding,				\
			    data, data_stride, n_data,		\
			    /* data_bytes */ sizeof (TYPE),	\
			    /* is_signed */ IS_SIGNED);		\
  }

_(u8, /* is_signed */ 0);
_(u16, /* is_signed */ 0);
_(u32, /* is_signed */ 0);
_(u64, /* is_signed */ 0);
_(i8, /* is_signed */ 1);
_(i16, /* is_signed */ 1);
_(i32, /* is_signed */ 1);
_(i64, /* is_signed */ 1);

#undef _

always_inline uword
coding_max_n_bits (uword coding)
{
  uword n_bits;
  (void) zvec_decode (coding, 0, &n_bits);
  return n_bits;
}

always_inline void
zvec_decode_inline (uword * zvec,
		    uword * zvec_n_bits,
		    uword coding,
		    void *data,
		    uword data_stride,
		    uword n_data, uword data_bytes, uword is_signed)
{
  uword i, n_max;

  i = *zvec_n_bits;
  n_max = coding_max_n_bits (coding);
  while (n_data >= 1)
    {
      uword d0, z0, l0;

      z0 = clib_bitmap_get_multiple (zvec, i, n_max);
      d0 = zvec_decode (coding, z0, &l0);
      i += l0;
      put_data (data + 0 * data_stride, data_bytes, is_signed, d0);
      data += 1 * data_stride;
      n_data -= 1;
    }
  *zvec_n_bits = i;
}

#define _(TYPE,IS_SIGNED)					\
  void zvec_decode_##TYPE (uword * zvec,			\
			   uword * zvec_n_bits,			\
			   uword coding,			\
			   void * data,				\
			   uword data_stride,			\
			   uword n_data)			\
  {								\
    return zvec_decode_inline (zvec, zvec_n_bits,		\
			       coding,				\
			       data, data_stride, n_data,	\
			       /* data_bytes */ sizeof (TYPE),	\
			       /* is_signed */ IS_SIGNED);	\
  }

_(u8, /* is_signed */ 0);
_(u16, /* is_signed */ 0);
_(u32, /* is_signed */ 0);
_(u64, /* is_signed */ 0);
_(i8, /* is_signed */ 1);
_(i16, /* is_signed */ 1);
_(i32, /* is_signed */ 1);
_(i64, /* is_signed */ 1);

#undef _

/* Compute number of bits needed to encode given histogram. */
static uword
zvec_coding_bits (uword coding, uword * histogram_counts, uword min_bits)
{
  uword n_type_bits, n_bits;
  uword this_count, last_count, max_count_index;
  uword i, b, l;

  n_bits = 0;
  n_type_bits = 1;
  last_count = 0;
  max_count_index = vec_len (histogram_counts) - 1;

  /* Coding is not large enough to encode given data. */
  if (coding <= max_count_index)
    return ~0;

  i = 0;
  while (coding != 0)
    {
      b = first_set (coding);
      l = min_log2 (b);
      i += b;

      this_count =
	histogram_counts[i > max_count_index ? max_count_index : i - 1];

      /* No more data to encode? */
      if (this_count == last_count)
	break;

      /* Last coding is i 0 ... 0 so we don't need an extra type bit. */
      if (coding == b)
	n_type_bits--;

      n_bits += (this_count - last_count) * (n_type_bits + l);

      /* This coding cannot be minimal: so return. */
      if (n_bits >= min_bits)
	return ~0;

      last_count = this_count;
      coding ^= b;
      n_type_bits++;
    }

  return n_bits;
}

uword
_zvec_coding_from_histogram (void *histogram,
			     uword histogram_len,
			     uword histogram_elt_count_offset,
			     uword histogram_elt_bytes,
			     uword max_value_to_encode,
			     zvec_coding_info_t * coding_return)
{
  uword coding, min_coding;
  uword min_coding_bits, coding_bits;
  uword i, n_bits_set, total_count;
  uword *counts;
  zvec_histogram_count_t *h_count = histogram + histogram_elt_count_offset;

  if (histogram_len < 1)
    {
      coding_return->coding = 0;
      coding_return->min_coding_bits = 0;
      coding_return->n_data = 0;
      coding_return->n_codes = 0;
      coding_return->ave_coding_bits = 0;
      return 0;
    }

  total_count = 0;
  counts = vec_new (uword, histogram_len);
  for (i = 0; i < histogram_len; i++)
    {
      zvec_histogram_count_t this_count = h_count[0];
      total_count += this_count;
      counts[i] = total_count;
      h_count =
	(zvec_histogram_count_t *) ((void *) h_count + histogram_elt_bytes);
    }

  min_coding = 0;
  min_coding_bits = ~0;

  {
    uword base_coding =
      max_value_to_encode !=
      ~0 ? (1 + max_value_to_encode) : vec_len (counts);
    uword max_coding = max_pow2 (2 * base_coding);

    for (n_bits_set = 1; n_bits_set <= 8; n_bits_set++)
      {
	for (coding = pow2_mask (n_bits_set);
	     coding < max_coding;
	     coding = next_with_same_number_of_set_bits (coding))
	  {
	    coding_bits = zvec_coding_bits (coding, counts, min_coding_bits);
	    if (coding_bits >= min_coding_bits)
	      continue;
	    min_coding_bits = coding_bits;
	    min_coding = coding;
	  }
      }
  }

  if (coding_return)
    {
      coding_return->coding = min_coding;
      coding_return->min_coding_bits = min_coding_bits;
      coding_return->n_data = total_count;
      coding_return->n_codes = vec_len (counts);
      coding_return->ave_coding_bits =
	(f64) min_coding_bits / (f64) total_count;
    }

  vec_free (counts);

  return min_coding;
}

u8 *
format_zvec_coding (u8 * s, va_list * args)
{
  zvec_coding_info_t *c = va_arg (*args, zvec_coding_info_t *);
  return format (s,
		 "zvec coding 0x%x, %d elts, %d codes, %d bits total, %.4f ave bits/code",
		 c->coding, c->n_data, c->n_codes, c->min_coding_bits,
		 c->ave_coding_bits);
}

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
span class="o">: switch (ss) { case cOTHER: break; case cSTRING: ss = cSBACKSLASH; break; case cSBACKSLASH: ss = cSTRING; break; case cCHAR: ss = cCBACKSLASH; break; case cCBACKSLASH: ss = cCHAR; break; case cSLASH: crc = CRC8 (crc, '/'); ; ss = cOTHER; break; case cSLASH_SLASH: continue; /* in comment */ case cSLASH_STAR: continue; /* in comment */ case cSTAR: ss = cSLASH_STAR; continue; /* in comment */ } break; case '/': switch (ss) { case cOTHER: ss = cSLASH; continue; /* potential comment */ case cSTRING: break; case cSBACKSLASH: ss = cSTRING; break; case cCHAR: break; case cCBACKSLASH: ss = cCHAR; break; case cSLASH: ss = cSLASH_SLASH; continue; /* start comment */ case cSLASH_SLASH: continue; /* in comment */ case cSLASH_STAR: continue; /* in comment */ case cSTAR: ss = cOTHER; continue; /* end of comment */ } break; case '*': switch (ss) { case cOTHER: break; case cSTRING: break; case cSBACKSLASH: ss = cSTRING; break; case cCHAR: break; case cCBACKSLASH: ss = cCHAR; break; case cSLASH: ss = cSLASH_STAR; continue; /* start comment */ case cSLASH_SLASH: continue; /* in comment */ case cSLASH_STAR: ss = cSTAR; continue; /* potential end */ case cSTAR: continue; /* still potential end of comment */ } break; case '\n': case '\r': case ' ': case '\t': case '\014': switch (ss) { case cOTHER: continue; /* ignore all whitespace */ case cSTRING: break; case cSBACKSLASH: ss = cSTRING; break; case cCHAR: break; case cCBACKSLASH: ss = cCHAR; break; case cSLASH: c = '/'; ss = cOTHER; break; case cSLASH_SLASH: if (c == '\n' || c == '\r') ss = cOTHER; /* end comment */ continue; case cSLASH_STAR: continue; /* in comment */ case cSTAR: ss = cSLASH_STAR; continue; /* in comment */ } default: switch (ss) { case cOTHER: break; case cSTRING: break; case cSBACKSLASH: ss = cSTRING; break; case cCHAR: break; case cCBACKSLASH: ss = cCHAR; break; case cSLASH: crc = CRC8 (crc, '/'); ss = cOTHER; break; case cSLASH_SLASH: continue; /* in comment */ case cSLASH_STAR: continue; /* in comment */ case cSTAR: ss = cSLASH_STAR; continue; /* in comment */ } } crc = CRC8 (crc, c); } } /* * main */ int main (int argc, char **argv) { int curarg = 1; char *ofile=0; char *pythonfile=0; char *show_name=0; while (curarg < argc) { if (!strncmp (argv [curarg], "--verbose", 3)) { fprintf (stderr, "%s version %s\n", argv [0], version); curarg++; continue; } if (!strncmp (argv [curarg], "--yydebug", 3)) { yydebug = 1; curarg++; continue; } if (!strncmp (argv [curarg], "--dump", 3)) { dump_tree = 1; curarg++; continue; } if (!strncmp (argv[curarg], "--show-name", 3)) { curarg++; if (curarg < argc) { show_name = argv[curarg]; curarg++; continue; } else { fprintf(stderr, "Missing filename after --show-name \n"); exit(1); } } if (!strncmp (argv [curarg], "--input", 3)) { curarg++; if (curarg < argc) { input_filename = argv[curarg]; if (!strcmp (argv [curarg], "-")) ifp = stdin; else ifp = fopen (argv [curarg], "r"); if (ifp == NULL) { fprintf (stderr, "Couldn't open input file %s\n", argv[curarg]); exit (1); } curarg++; } else { fprintf(stderr, "Missing filename after --input\n"); exit(1); } continue; } if (!strncmp (argv [curarg], "--output", 3)) { curarg++; if (curarg < argc) { ofp = fopen (argv[curarg], "w"); if (ofp == NULL) { fprintf (stderr, "Couldn't open output file %s\n", argv[curarg]); exit (1); } ofile = argv[curarg]; curarg++; } else { fprintf(stderr, "Missing filename after --output\n"); exit(1); } continue; } if (!strncmp (argv [curarg], "--python", 8)) { curarg++; if (curarg < argc) { pythonfp = fopen (argv[curarg], "w"); if (pythonfp == NULL) { fprintf (stderr, "Couldn't open python output file %s\n", argv[curarg]); exit (1); } pythonfile = argv[curarg]; curarg++; } else { fprintf(stderr, "Missing filename after --python\n"); exit(1); } continue; } if (!strncmp (argv [curarg], "--app", 4)) { curarg++; if (curarg < argc) { vlib_app_name = argv[curarg]; curarg++; } else { fprintf(stderr, "Missing app name after --app\n"); exit(1); } continue; } usage(argv[0]); exit (1); } if (ofp == NULL) { ofile = 0; } if (pythonfp == NULL) { pythonfile = 0; } if (ifp == NULL) { fprintf(stderr, "No input file specified...\n"); exit(1); } if (show_name) { input_filename = show_name; } starttime = time (0); if (yyparse() == 0) { fclose (ifp); curarg -= 2; if (ofile) { printf ("Output written to %s\n", ofile); fclose (ofp); } if (pythonfile) { printf ("Python bindings written to %s\n", pythonfile); fclose (pythonfp); } } else { fclose (ifp); fclose (ofp); if (ofile) { printf ("Removing %s\n", ofile); unlink (ofile); } if (pythonfile) { printf ("Removing %s\n", pythonfile); unlink (pythonfile); } exit (1); } exit (0); } /* * usage */ static void usage (char *progname) { fprintf (stderr, "usage: %s --input <filename> [--output <filename>] [--python <filename>]\n%s", progname, " [--yydebug] [--dump-tree]\n"); exit (1); } /* * yyerror */ void yyerror (char *s) { fprintf (stderr, "%s:%d %s\n", current_filename, the_lexer_linenumber, s); } static char namebuf [MAXNAME]; /* * yylex (well, yylex_1: The real yylex below does crc-hackery) */ static int yylex_1 (void) { int nameidx=0; char c; int at_bol=1; enum { LP_INITIAL_WHITESPACE, LP_LINE_NUMBER, LP_PRE_FILENAME_WHITESPACE, LP_FILENAME, LP_POST_FILENAME, LP_OTHER } lp_substate = LP_INITIAL_WHITESPACE; again: switch (the_lexer_state) { /* * START state -- looking for something interesting */ case START_STATE: c = getc (ifp); if (feof (ifp)) return (EOF); switch (c) { case '\n': the_lexer_linenumber++; at_bol=1; goto again; case '#': if (!at_bol) { fprintf (stderr, "unknown token /%c at line %d\n", c, the_lexer_linenumber); return (BARF); } the_lexer_state = LINE_PRAGMA_STATE; lp_substate = LP_INITIAL_WHITESPACE; goto again; /* FALLTHROUGH */ case '\t': case ' ': goto again; case '(': return (LPAR); case ')': return (RPAR); case ';': return (SEMI); case '[': return (LBRACK); case ']': return (RBRACK); case '{': return (LCURLY); case '}': return (RCURLY); case ',': return (COMMA); case '"': nameidx = 0; the_lexer_state = STRING_STATE; goto again; case '@': nameidx = 0; the_lexer_state = HELPER_STATE; goto again; case '/': c = getc (ifp); if (feof (ifp)) return (EOF); if (c == '/') { the_lexer_state = CPP_COMMENT_STATE; goto again; } else if (c == '*') { the_lexer_state = C_COMMENT_STATE; goto again; } else { fprintf (stderr, "unknown token /%c at line %d\n", c, the_lexer_linenumber); return (BARF); } case '\\': c = getc (ifp); if (feof (ifp)) return (EOF); /* Note fallthrough... */ default: if (isalpha (c) || c == '_') { namebuf [0] = c; nameidx = 1; the_lexer_state = NAME_STATE; goto again; } else if (isdigit(c)) { namebuf [0] = c; nameidx = 1; the_lexer_state = NUMBER_STATE; goto again; } fprintf (stderr, "unknown token %c at line %d\n", c, the_lexer_linenumber); return (BARF); } /* * NAME state -- eat the rest of a name */ case NAME_STATE: c = getc (ifp); if (feof (ifp)) return (EOF); if (!isalnum (c) && c != '_') { ungetc (c, ifp); namebuf [nameidx] = 0; the_lexer_state = START_STATE; return (name_check (namebuf, &yylval)); } if (nameidx >= (MAXNAME-1)) { fprintf(stderr, "lex input buffer overflow...\n"); exit(1); } namebuf [nameidx++] = c; goto again; /* * NUMBER state -- eat the rest of a number */ case NUMBER_STATE: c = getc (ifp); if (feof (ifp)) return (EOF); if (!isdigit (c)) { ungetc (c, ifp); namebuf [nameidx] = 0; the_lexer_state = START_STATE; yylval = (void *) atol(namebuf); return (NUMBER); } if (nameidx >= (MAXNAME-1)) { fprintf(stderr, "lex input buffer overflow...\n"); exit(1); } namebuf [nameidx++] = c; goto again; /* * C_COMMENT state -- eat a peach */ case C_COMMENT_STATE: c = getc (ifp); if (feof (ifp)) return (EOF); if (c == '*') { c = getc (ifp); if (feof (ifp)) return (EOF); if (c == '/') { the_lexer_state = START_STATE; goto again; } } if (c == '\n') the_lexer_linenumber++; goto again; /* * CPP_COMMENT state -- eat a plum */ case CPP_COMMENT_STATE: c = getc (ifp); if (feof (ifp)) return (EOF); if (c == '\n') { the_lexer_linenumber++; the_lexer_state = START_STATE; goto again; } goto again; case STRING_STATE: c = getc (ifp); if (feof (ifp)) return (EOF); switch (c) { case '\\': c = getc (ifp); if (feof (ifp)) return (EOF); namebuf[nameidx++] = c; goto again; case '"': namebuf[nameidx] = 0; yylval = (YYSTYPE) sxerox (namebuf); the_lexer_state = START_STATE; return (STRING); default: if (c == '\n') the_lexer_linenumber++; if (nameidx >= (MAXNAME-1)) { fprintf(stderr, "lex input buffer overflow...\n"); exit(1); } namebuf[nameidx++] = c; goto again; } break; case HELPER_STATE: c = getc (ifp); if (feof (ifp)) return (EOF); switch (c) { case '\\': c = getc (ifp); if (feof (ifp)) return (EOF); namebuf[nameidx] = c; goto again; case '@': namebuf[nameidx] = 0; yylval = (YYSTYPE) sxerox (namebuf); the_lexer_state = START_STATE; return (HELPER_STRING); default: if (c == '\n') the_lexer_linenumber++; /* * CPP makes it approximately impossible to * type "#define FOO 123", so we provide a * lexical trick to achieve that result */ if (c == '$') c = '#'; if (nameidx >= (MAXNAME-1)) { fprintf(stderr, "lex input buffer overflow...\n"); exit(1); } namebuf[nameidx++] = c; goto again; } break; case LINE_PRAGMA_STATE: /* We're only interested in lines of the form # 259 "foo.c" 17 */ switch (lp_substate) { case LP_INITIAL_WHITESPACE: /* no number seen yet */ c = getc(ifp); if (feof(ifp)) return(EOF); if (c >= '0' && c <= '9') { namebuf[nameidx++] = c; lp_substate = LP_LINE_NUMBER; } else if (c == '\n') { goto lp_end_of_line; } else if (c != ' ' && c != '\t') { /* Nothing */ } else { lp_substate = LP_OTHER; } goto again; case LP_LINE_NUMBER: /* eating linenumber */ c = getc(ifp); if (feof(ifp)) return(EOF); if (c >= '0' && c <= '9') { namebuf[nameidx++] = c; } else if (c == ' ' || c == '\t') { namebuf[nameidx++] = 0; the_lexer_linenumber = atol(namebuf); lp_substate = LP_PRE_FILENAME_WHITESPACE; } else if (c == '\n') { goto lp_end_of_line; } else { lp_substate = LP_OTHER; } goto again; case LP_PRE_FILENAME_WHITESPACE: /* awaiting filename */ c = getc(ifp); if (feof(ifp)) return(EOF); if (c == '"') { lp_substate = LP_FILENAME; nameidx = 0; } else if (c == ' ' || c == '\t') { /* nothing */ } else if (c == '\n') { goto lp_end_of_line; } else { lp_substate = LP_OTHER; } goto again; case LP_FILENAME: /* eating filename */ c = getc(ifp); if (feof(ifp)) return(EOF); if (c == '"') { lp_substate = LP_POST_FILENAME; namebuf[nameidx] = 0; } else if (c == '\n') { goto lp_end_of_line; /* syntax error... */ } else { namebuf[nameidx++] = c; } goto again; case LP_POST_FILENAME: /* ignoring rest of line */ case LP_OTHER: c = getc(ifp); if (feof(ifp)) return(EOF); if (c == '\n') { if (lp_substate == LP_POST_FILENAME) { if (current_filename_allocated) { current_filename_allocated = 0; free(current_filename); } if (!strcmp(namebuf, "<stdin>")) { current_filename = input_filename; } else { current_filename = sxerox(namebuf); current_filename_allocated = 1; } } lp_end_of_line: the_lexer_state = START_STATE; at_bol = 1; nameidx = 0; } goto again; } break; } fprintf (stderr, "LEXER BUG!\n"); exit (1); /* NOTREACHED */ return (0); } /* * Parse a token and side-effect input_crc * in a whitespace- and comment-insensitive fashion. */ int yylex (void) { /* * Accumulate a crc32-based signature while processing the * input file. The goal is to come up with a magic number * which changes precisely when the original input file changes * but which ignores whitespace changes. */ unsigned long crc = input_crc; int node_type = yylex_1 (); switch (node_type) { case PRIMTYPE: case NAME: case NUMBER: case STRING: case HELPER_STRING: { /* We know these types accumulated token text into namebuf */ /* HELPER_STRING may still contain C comments. Argh. */ crc = crc_eliding_c_comments (namebuf, crc); break; } /* Other node types have no "substate" */ /* This code is written in this curious fashion because we * want the generated CRC to be independent of the particular * values a particular version of lex/bison assigned to various states. */ /* case NAME: crc = CRC16 (crc, 257); break; */ case RPAR: crc = CRC16 (crc, 258); break; case LPAR: crc = CRC16 (crc, 259); break; case SEMI: crc = CRC16 (crc, 260); break; case LBRACK: crc = CRC16 (crc, 261); break; case RBRACK: crc = CRC16 (crc, 262); break; /* case NUMBER: crc = CRC16 (crc, 263); break; */ /* case PRIMTYPE: crc = CRC16 (crc, 264); break; */ case BARF: crc = CRC16 (crc, 265); break; case TPACKED: crc = CRC16 (crc, 266); break; case DEFINE: crc = CRC16 (crc, 267); break; case LCURLY: crc = CRC16 (crc, 268); break; case RCURLY: crc = CRC16 (crc, 269); break; /* case STRING: crc = CRC16 (crc, 270); break; */ case UNION: crc = CRC16 (crc, 271); break; /* case HELPER_STRING: crc = CRC16 (crc, 272); break; */ case COMMA: crc = CRC16 (crc, 273); break; case NOVERSION: crc = CRC16 (crc, 274); break; case MANUAL_PRINT: crc = CRC16 (crc, 275); break; case MANUAL_ENDIAN: crc = CRC16 (crc, 276); break; case TYPEONLY: crc = CRC16 (crc, 278); break; case DONT_TRACE: crc = CRC16 (crc, 279); break; case EOF: crc = CRC16 (crc, ~0); break; /* hysterical compatibility */ default: fprintf(stderr, "yylex: node_type %d missing state CRC cookie\n", node_type); exit(1); } input_crc = crc; return (node_type); } /* * name_check -- see if the name we just ate * matches a known keyword. If so, set yylval * to a new instance of <subclass of node>, and return PARSER_MACRO * * Otherwise, set yylval to sxerox (s) and return NAME */ static struct keytab { char *name; enum node_subclass subclass_id; } keytab [] = /* Keep the table sorted, binary search used below! */ { {"define", NODE_DEFINE}, {"dont_trace", NODE_DONT_TRACE}, {"f64", NODE_F64}, {"i16", NODE_I16}, {"i32", NODE_I32}, {"i64", NODE_I64}, {"i8", NODE_I8}, {"manual_endian", NODE_MANUAL_ENDIAN}, {"manual_print", NODE_MANUAL_PRINT}, {"noversion", NODE_NOVERSION}, {"packed", NODE_PACKED}, {"typeonly", NODE_TYPEONLY}, {"u16", NODE_U16}, {"u32", NODE_U32}, {"u64", NODE_U64}, {"u8", NODE_U8}, {"union", NODE_UNION}, {"uword", NODE_UWORD}, }; static int name_check (const char *s, YYSTYPE *token_value) { enum node_subclass subclass_id; int top, bot, mid; int result; for (top = 0, bot = (sizeof(keytab) / sizeof(struct keytab))-1; bot >= top; ) { mid = (top + bot) / 2; result = name_compare (s, keytab[mid].name); if (result < 0) bot = mid - 1; else if (result > 0) top = mid + 1; else { subclass_id = keytab[mid].subclass_id; switch (subclass_id) { case NODE_U8: case NODE_U16: case NODE_U32: case NODE_U64: case NODE_I8: case NODE_I16: case NODE_I32: case NODE_I64: case NODE_F64: case NODE_UWORD: *token_value = make_node(subclass_id); return (PRIMTYPE); case NODE_PACKED: *token_value = make_node(subclass_id); return (TPACKED); case NODE_DEFINE: *token_value = make_node(subclass_id); return(DEFINE); case NODE_MANUAL_PRINT: *token_value = (YYSTYPE) NODE_FLAG_MANUAL_PRINT; return (MANUAL_PRINT); case NODE_MANUAL_ENDIAN: *token_value = (YYSTYPE) NODE_FLAG_MANUAL_ENDIAN; return (MANUAL_ENDIAN); case NODE_TYPEONLY: *token_value = (YYSTYPE) NODE_FLAG_TYPEONLY; return(TYPEONLY); case NODE_DONT_TRACE: *token_value = (YYSTYPE) NODE_FLAG_DONT_TRACE; return(DONT_TRACE); case NODE_NOVERSION: return(NOVERSION); case NODE_UNION: return(UNION); default: fprintf (stderr, "fatal: keytab botch!\n"); exit (1); } } } *token_value = (YYSTYPE) sxerox (s); return (NAME); } /* * sxerox */ char *sxerox (const char *s) { int len = strlen (s); char *rv; rv = (char *) malloc (len+1); strcpy (rv, s); return (rv); } /* * name_compare */ int name_compare (const char *s1, const char *s2) { char c1, c2; while (*s1 && *s2) { c1 = *s1++; c2 = *s2++; c1 = tolower (c1); c2 = tolower (c2); if (c1 < c2) return (-1); else if (c1 > c2) return (1); } if (*s1 < *s2) return (-1); else if (*s1 > *s2) return (1); return (0); }