1 /// \file
2 /// Provides a number of useful functions that are roughly equivalent
3 /// to java HashTable and List for the purposes of Antlr 3 C runtime.
4 /// Also useable by the C programmer for things like symbol tables pointers
5 /// and so on.
6 ///
7 ///
8 
9 // [The "BSD licence"]
10 // Copyright (c) 2005-2009 Jim Idle, Temporal Wave LLC
11 // http://www.temporal-wave.com
12 // http://www.linkedin.com/in/jimidle
13 //
14 // All rights reserved.
15 //
16 // Redistribution and use in source and binary forms, with or without
17 // modification, are permitted provided that the following conditions
18 // are met:
19 // 1. Redistributions of source code must retain the above copyright
20 //    notice, this list of conditions and the following disclaimer.
21 // 2. Redistributions in binary form must reproduce the above copyright
22 //    notice, this list of conditions and the following disclaimer in the
23 //    documentation and/or other materials provided with the distribution.
24 // 3. The name of the author may not be used to endorse or promote products
25 //    derived from this software without specific prior written permission.
26 //
27 // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 
38 #include    <antlr3.h>
39 
40 #include "antlr3collections.h"
41 
42 // Interface functions for hash table
43 //
44 
45 // String based keys
46 //
47 static void					antlr3HashDelete    (pANTLR3_HASH_TABLE table, void * key);
48 static void *				antlr3HashGet	(pANTLR3_HASH_TABLE table, void * key);
49 static pANTLR3_HASH_ENTRY   antlr3HashRemove    (pANTLR3_HASH_TABLE table, void * key);
50 static ANTLR3_INT32			antlr3HashPut	(pANTLR3_HASH_TABLE table, void * key, void * element, void (ANTLR3_CDECL *freeptr)(void *));
51 
52 // Integer based keys (Lists and so on)
53 //
54 static void					antlr3HashDeleteI   (pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key);
55 static void *				antlr3HashGetI	(pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key);
56 static pANTLR3_HASH_ENTRY   antlr3HashRemoveI   (pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key);
57 static ANTLR3_INT32			antlr3HashPutI	(pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key, void * element, void (ANTLR3_CDECL *freeptr)(void *));
58 
59 static void					antlr3HashFree	(pANTLR3_HASH_TABLE table);
60 static ANTLR3_UINT32	    antlr3HashSize	(pANTLR3_HASH_TABLE table);
61 
62 // -----------
63 
64 // Interface functions for enumeration
65 //
66 static int	    antlr3EnumNext	    (pANTLR3_HASH_ENUM en, pANTLR3_HASH_KEY * key, void ** data);
67 static void	    antlr3EnumFree	    (pANTLR3_HASH_ENUM en);
68 
69 // Interface functions for List
70 //
71 static void				antlr3ListFree	(pANTLR3_LIST list);
72 static void				antlr3ListDelete(pANTLR3_LIST list, ANTLR3_INTKEY key);
73 static void *			antlr3ListGet	(pANTLR3_LIST list, ANTLR3_INTKEY key);
74 static ANTLR3_INT32		antlr3ListPut	(pANTLR3_LIST list, ANTLR3_INTKEY key, void * element, void (ANTLR3_CDECL *freeptr)(void *));
75 static ANTLR3_INT32		antlr3ListAdd   (pANTLR3_LIST list, void * element, void (ANTLR3_CDECL *freeptr)(void *));
76 static void *			antlr3ListRemove(pANTLR3_LIST list, ANTLR3_INTKEY key);
77 static ANTLR3_UINT32	antlr3ListSize	(pANTLR3_LIST list);
78 
79 // Interface functions for Stack
80 //
81 static void				antlr3StackFree	(pANTLR3_STACK  stack);
82 static void *			antlr3StackPop	(pANTLR3_STACK	stack);
83 static void *			antlr3StackGet	(pANTLR3_STACK	stack, ANTLR3_INTKEY key);
84 static ANTLR3_BOOLEAN	antlr3StackPush	(pANTLR3_STACK	stack, void * element, void (ANTLR3_CDECL *freeptr)(void *));
85 static ANTLR3_UINT32	antlr3StackSize	(pANTLR3_STACK	stack);
86 static void *			antlr3StackPeek	(pANTLR3_STACK	stack);
87 
88 // Interface functions for vectors
89 //
90 static	void ANTLR3_CDECL	antlr3VectorFree	(pANTLR3_VECTOR vector);
91 static	void				antlr3VectorDel		(pANTLR3_VECTOR vector, ANTLR3_UINT32 entry);
92 static	void *				antlr3VectorGet		(pANTLR3_VECTOR vector, ANTLR3_UINT32 entry);
93 static	void *				antrl3VectorRemove	(pANTLR3_VECTOR vector, ANTLR3_UINT32 entry);
94 static	void				antlr3VectorClear	(pANTLR3_VECTOR vector);
95 static	ANTLR3_UINT32		antlr3VectorAdd		(pANTLR3_VECTOR vector, void * element, void (ANTLR3_CDECL *freeptr)(void *));
96 static	ANTLR3_UINT32		antlr3VectorSet		(pANTLR3_VECTOR vector, ANTLR3_UINT32 entry, void * element, void (ANTLR3_CDECL *freeptr)(void *), ANTLR3_BOOLEAN freeExisting);
97 static	ANTLR3_UINT32		antlr3VectorSize    (pANTLR3_VECTOR vector);
98 static	ANTLR3_BOOLEAN      antlr3VectorSwap	(pANTLR3_VECTOR vector, ANTLR3_UINT32 entry1, ANTLR3_UINT32 entry2);
99 
100 static  ANTLR3_BOOLEAN      newPool             (pANTLR3_VECTOR_FACTORY factory);
101 static  void				closeVectorFactory  (pANTLR3_VECTOR_FACTORY factory);
102 static	pANTLR3_VECTOR		newVector			(pANTLR3_VECTOR_FACTORY factory);
103 static	void				returnVector		(pANTLR3_VECTOR_FACTORY factory, pANTLR3_VECTOR vector);
104 
105 
106 // Interface functions for int TRIE
107 //
108 static	pANTLR3_TRIE_ENTRY	intTrieGet		(pANTLR3_INT_TRIE trie, ANTLR3_INTKEY key);
109 static	ANTLR3_BOOLEAN		intTrieDel		(pANTLR3_INT_TRIE trie, ANTLR3_INTKEY key);
110 static	ANTLR3_BOOLEAN		intTrieAdd		(pANTLR3_INT_TRIE trie, ANTLR3_INTKEY key, ANTLR3_UINT32 type, ANTLR3_INTKEY intType, void * data, void (ANTLR3_CDECL *freeptr)(void *));
111 static	void				intTrieFree		(pANTLR3_INT_TRIE trie);
112 
113 
114 // Interface functions for topological sorter
115 //
116 static  void            addEdge          (pANTLR3_TOPO topo, ANTLR3_UINT32 edge, ANTLR3_UINT32 dependency);
117 static  pANTLR3_UINT32  sortToArray      (pANTLR3_TOPO topo);
118 static  void            sortVector       (pANTLR3_TOPO topo, pANTLR3_VECTOR v);
119 static  void            freeTopo         (pANTLR3_TOPO topo);
120 
121 // Local function to advance enumeration structure pointers
122 //
123 static void antlr3EnumNextEntry(pANTLR3_HASH_ENUM en);
124 
125 pANTLR3_HASH_TABLE
antlr3HashTableNew(ANTLR3_UINT32 sizeHint)126 antlr3HashTableNew(ANTLR3_UINT32 sizeHint)
127 {
128 	// All we have to do is create the hashtable tracking structure
129 	// and allocate memory for the requested number of buckets.
130 	//
131 	pANTLR3_HASH_TABLE	table;
132 
133 	ANTLR3_UINT32	bucket;	// Used to traverse the buckets
134 
135 	table   = (pANTLR3_HASH_TABLE)ANTLR3_MALLOC(sizeof(ANTLR3_HASH_TABLE));
136 
137 	// Error out if no memory left
138 	if	(table	== NULL)
139 	{
140 		return	NULL;
141 	}
142 
143 	// Allocate memory for the buckets
144 	//
145 	table->buckets = (pANTLR3_HASH_BUCKET) ANTLR3_MALLOC((size_t) (sizeof(ANTLR3_HASH_BUCKET) * sizeHint));
146 
147 	if	(table->buckets == NULL)
148 	{
149 		ANTLR3_FREE((void *)table);
150 		return	NULL;
151 	}
152 
153 	// Modulo of the table, (bucket count).
154 	//
155 	table->modulo   = sizeHint;
156 
157 	table->count    = 0;	    /* Nothing in there yet ( I hope)	*/
158 
159 	/* Initialize the buckets to empty
160 	*/
161 	for	(bucket = 0; bucket < sizeHint; bucket++)
162 	{
163 		table->buckets[bucket].entries = NULL;
164 	}
165 
166 	/* Exclude duplicate entries by default
167 	*/
168 	table->allowDups	= ANTLR3_FALSE;
169 
170     /* Assume that keys should by strduped before they are
171      * entered in the table.
172      */
173     table->doStrdup     = ANTLR3_TRUE;
174 
175 	/* Install the interface
176 	*/
177 
178 	table->get		=  antlr3HashGet;
179 	table->put		=  antlr3HashPut;
180 	table->del		=  antlr3HashDelete;
181 	table->remove	=  antlr3HashRemove;
182 
183 	table->getI		=  antlr3HashGetI;
184 	table->putI		=  antlr3HashPutI;
185 	table->delI		=  antlr3HashDeleteI;
186 	table->removeI	=  antlr3HashRemoveI;
187 
188 	table->size		=  antlr3HashSize;
189 	table->free		=  antlr3HashFree;
190 
191 	return  table;
192 }
193 
194 static void
antlr3HashFree(pANTLR3_HASH_TABLE table)195 antlr3HashFree(pANTLR3_HASH_TABLE table)
196 {
197     ANTLR3_UINT32	bucket;	/* Used to traverse the buckets	*/
198 
199     pANTLR3_HASH_BUCKET	thisBucket;
200     pANTLR3_HASH_ENTRY	entry;
201     pANTLR3_HASH_ENTRY	nextEntry;
202 
203     /* Free the table, all buckets and all entries, and all the
204      * keys and data (if the table exists)
205      */
206     if	(table	!= NULL)
207     {
208 	for	(bucket = 0; bucket < table->modulo; bucket++)
209 	{
210 	    thisBucket	= &(table->buckets[bucket]);
211 
212 	    /* Allow sparse tables, though we don't create them as such at present
213 	     */
214 	    if	( thisBucket != NULL)
215 	    {
216 		entry	= thisBucket->entries;
217 
218 		/* Search all entries in the bucket and free them up
219 		 */
220 		while	(entry != NULL)
221 		{
222 		    /* Save next entry - we do not want to access memory in entry after we
223 		     * have freed it.
224 		     */
225 		    nextEntry	= entry->nextEntry;
226 
227 		    /* Free any data pointer, this only happens if the user supplied
228 		     * a pointer to a routine that knwos how to free the structure they
229 		     * added to the table.
230 		     */
231 		    if	(entry->free != NULL)
232 		    {
233 			entry->free(entry->data);
234 		    }
235 
236 		    /* Free the key memory - we know that we allocated this
237 		     */
238 		    if	(entry->keybase.type == ANTLR3_HASH_TYPE_STR && entry->keybase.key.sKey != NULL)
239 		    {
240 			ANTLR3_FREE(entry->keybase.key.sKey);
241 		    }
242 
243 		    /* Free this entry
244 		     */
245 		    ANTLR3_FREE(entry);
246 		    entry   = nextEntry;    /* Load next pointer to see if we shoud free it */
247 		}
248 		/* Invalidate the current pointer
249 		 */
250 		thisBucket->entries = NULL;
251 	    }
252 	}
253 
254 	/* Now we can free the bucket memory
255 	 */
256 	ANTLR3_FREE(table->buckets);
257     }
258 
259     /* Now we free teh memory for the table itself
260      */
261     ANTLR3_FREE(table);
262 }
263 
264 /** return the current size of the hash table
265  */
antlr3HashSize(pANTLR3_HASH_TABLE table)266 static ANTLR3_UINT32	antlr3HashSize	    (pANTLR3_HASH_TABLE table)
267 {
268     return  table->count;
269 }
270 
271 /** Remove a numeric keyed entry from a hash table if it exists,
272  *  no error if it does not exist.
273  */
antlr3HashRemoveI(pANTLR3_HASH_TABLE table,ANTLR3_INTKEY key)274 static pANTLR3_HASH_ENTRY   antlr3HashRemoveI   (pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key)
275 {
276     ANTLR3_UINT32	    hash;
277     pANTLR3_HASH_BUCKET	    bucket;
278     pANTLR3_HASH_ENTRY	    entry;
279     pANTLR3_HASH_ENTRY	    * nextPointer;
280 
281     /* First we need to know the hash of the provided key
282      */
283     hash    = (ANTLR3_UINT32)(key % (ANTLR3_INTKEY)(table->modulo));
284 
285     /* Knowing the hash, we can find the bucket
286      */
287     bucket  = table->buckets + hash;
288 
289     /* Now, we traverse the entries in the bucket until
290      * we find the key or the end of the entries in the bucket.
291      * We track the element prior to the one we are examining
292      * as we need to set its next pointer to the next pointer
293      * of the entry we are deleting (if we find it).
294      */
295     entry	    =   bucket->entries;    /* Entry to examine					    */
296     nextPointer	    = & bucket->entries;    /* Where to put the next pointer of the deleted entry   */
297 
298     while   (entry != NULL)
299     {
300 	/* See if this is the entry we wish to delete
301 	 */
302 	if  (entry->keybase.key.iKey == key)
303 	{
304 	    /* It was the correct entry, so we set the next pointer
305 	     * of the previous entry to the next pointer of this
306 	     * located one, which takes it out of the chain.
307 	     */
308 	    (*nextPointer)		= entry->nextEntry;
309 
310 	    table->count--;
311 
312 	    return entry;
313 	}
314 	else
315 	{
316 	    /* We found an entry but it wasn't the one that was wanted, so
317 	     * move to the next one, if any.
318 	     */
319 	    nextPointer	= & (entry->nextEntry);	    /* Address of the next pointer in the current entry	    */
320 	    entry	= entry->nextEntry;	    /* Address of the next element in the bucket (if any)   */
321 	}
322     }
323 
324     return NULL;  /* Not found */
325 }
326 
327 /** Remove the element in the hash table for a particular
328  *  key value, if it exists - no error if it does not.
329  */
330 static pANTLR3_HASH_ENTRY
antlr3HashRemove(pANTLR3_HASH_TABLE table,void * key)331 antlr3HashRemove(pANTLR3_HASH_TABLE table, void * key)
332 {
333     ANTLR3_UINT32	    hash;
334     pANTLR3_HASH_BUCKET	    bucket;
335     pANTLR3_HASH_ENTRY	    entry;
336     pANTLR3_HASH_ENTRY	    * nextPointer;
337 
338     /* First we need to know the hash of the provided key
339      */
340     hash    = antlr3Hash(key, (ANTLR3_UINT32)strlen((const char *)key));
341 
342     /* Knowing the hash, we can find the bucket
343      */
344     bucket  = table->buckets + (hash % table->modulo);
345 
346     /* Now, we traverse the entries in the bucket until
347      * we find the key or the end of the entires in the bucket.
348      * We track the element prior to the one we are exmaining
349      * as we need to set its next pointer to the next pointer
350      * of the entry we are deleting (if we find it).
351      */
352     entry	    =   bucket->entries;    /* Entry to examine					    */
353     nextPointer	    = & bucket->entries;    /* Where to put the next pointer of the deleted entry   */
354 
355     while   (entry != NULL)
356     {
357 	/* See if this is the entry we wish to delete
358 	 */
359 	if  (strcmp((const char *)key, (const char *)entry->keybase.key.sKey) == 0)
360 	{
361 	    /* It was the correct entry, so we set the next pointer
362 	     * of the previous entry to the next pointer of this
363 	     * located one, which takes it out of the chain.
364 	     */
365 	    (*nextPointer)		= entry->nextEntry;
366 
367 	    /* Release the key - if we allocated that
368 	     */
369         if (table->doStrdup == ANTLR3_TRUE)
370         {
371             ANTLR3_FREE(entry->keybase.key.sKey);
372         }
373 	    entry->keybase.key.sKey	= NULL;
374 
375 	    table->count--;
376 
377 	    return entry;
378 	}
379 	else
380 	{
381 	    /* We found an entry but it wasn't the one that was wanted, so
382 	     * move to the next one, if any.
383 	     */
384 	    nextPointer	= & (entry->nextEntry);	    /* Address of the next pointer in the current entry	    */
385 	    entry	= entry->nextEntry;	    /* Address of the next element in the bucket (if any)   */
386 	}
387     }
388 
389     return NULL;  /* Not found */
390 }
391 
392 /** Takes the element with the supplied key out of the list, and deletes the data
393  *  calling the supplied free() routine if any.
394  */
395 static void
antlr3HashDeleteI(pANTLR3_HASH_TABLE table,ANTLR3_INTKEY key)396 antlr3HashDeleteI    (pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key)
397 {
398     pANTLR3_HASH_ENTRY	entry;
399 
400     entry = antlr3HashRemoveI(table, key);
401 
402     /* Now we can free the elements and the entry in order
403      */
404     if	(entry != NULL && entry->free != NULL)
405     {
406 	/* Call programmer supplied function to release this entry data
407 	 */
408 	entry->free(entry->data);
409 	entry->data = NULL;
410     }
411     /* Finally release the space for this entry block.
412      */
413     ANTLR3_FREE(entry);
414 }
415 
416 /** Takes the element with the supplied key out of the list, and deletes the data
417  *  calling the supplied free() routine if any.
418  */
419 static void
antlr3HashDelete(pANTLR3_HASH_TABLE table,void * key)420 antlr3HashDelete    (pANTLR3_HASH_TABLE table, void * key)
421 {
422     pANTLR3_HASH_ENTRY	entry;
423 
424     entry = antlr3HashRemove(table, key);
425 
426     /* Now we can free the elements and the entry in order
427      */
428     if	(entry != NULL && entry->free != NULL)
429     {
430 	/* Call programmer supplied function to release this entry data
431 	 */
432 	entry->free(entry->data);
433 	entry->data = NULL;
434     }
435     /* Finally release the space for this entry block.
436      */
437     ANTLR3_FREE(entry);
438 }
439 
440 /** Return the element pointer in the hash table for a particular
441  *  key value, or NULL if it don't exist (or was itself NULL).
442  */
443 static void *
antlr3HashGetI(pANTLR3_HASH_TABLE table,ANTLR3_INTKEY key)444 antlr3HashGetI(pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key)
445 {
446     ANTLR3_UINT32	    hash;
447     pANTLR3_HASH_BUCKET	    bucket;
448     pANTLR3_HASH_ENTRY	    entry;
449 
450     /* First we need to know the hash of the provided key
451      */
452     hash    = (ANTLR3_UINT32)(key % (ANTLR3_INTKEY)(table->modulo));
453 
454     /* Knowing the hash, we can find the bucket
455      */
456     bucket  = table->buckets + hash;
457 
458     /* Now we can inspect the key at each entry in the bucket
459      * and see if we have a match.
460      */
461     entry   = bucket->entries;
462 
463     while   (entry != NULL)
464     {
465 	if  (entry->keybase.key.iKey == key)
466 	{
467 	    /* Match was found, return the data pointer for this entry
468 	     */
469 	    return  entry->data;
470 	}
471 	entry = entry->nextEntry;
472     }
473 
474     /* If we got here, then we did not find the key
475      */
476     return  NULL;
477 }
478 
479 /** Return the element pointer in the hash table for a particular
480  *  key value, or NULL if it don't exist (or was itself NULL).
481  */
482 static void *
antlr3HashGet(pANTLR3_HASH_TABLE table,void * key)483 antlr3HashGet(pANTLR3_HASH_TABLE table, void * key)
484 {
485     ANTLR3_UINT32	    hash;
486     pANTLR3_HASH_BUCKET	    bucket;
487     pANTLR3_HASH_ENTRY	    entry;
488 
489 
490     /* First we need to know the hash of the provided key
491      */
492     hash    = antlr3Hash(key, (ANTLR3_UINT32)strlen((const char *)key));
493 
494     /* Knowing the hash, we can find the bucket
495      */
496     bucket  = table->buckets + (hash % table->modulo);
497 
498     /* Now we can inspect the key at each entry in the bucket
499      * and see if we have a match.
500      */
501     entry   = bucket->entries;
502 
503     while   (entry != NULL)
504     {
505 	if  (strcmp((const char *)key, (const char *)entry->keybase.key.sKey) == 0)
506 	{
507 	    /* Match was found, return the data pointer for this entry
508 	     */
509 	    return  entry->data;
510 	}
511 	entry = entry->nextEntry;
512     }
513 
514     /* If we got here, then we did not find the key
515      */
516     return  NULL;
517 }
518 
519 /** Add the element pointer in to the table, based upon the
520  *  hash of the provided key.
521  */
522 static	ANTLR3_INT32
antlr3HashPutI(pANTLR3_HASH_TABLE table,ANTLR3_INTKEY key,void * element,void (ANTLR3_CDECL * freeptr)(void *))523 antlr3HashPutI(pANTLR3_HASH_TABLE table, ANTLR3_INTKEY key, void * element, void (ANTLR3_CDECL *freeptr)(void *))
524 {
525 	ANTLR3_UINT32	    hash;
526 	pANTLR3_HASH_BUCKET	    bucket;
527 	pANTLR3_HASH_ENTRY	    entry;
528 	pANTLR3_HASH_ENTRY	    * newPointer;
529 
530 	/* First we need to know the hash of the provided key
531 	*/
532 	hash    = (ANTLR3_UINT32)(key % (ANTLR3_INTKEY)(table->modulo));
533 
534 	/* Knowing the hash, we can find the bucket
535 	*/
536 	bucket  = table->buckets + hash;
537 
538 	/* Knowing the bucket, we can traverse the entries until we
539 	* we find a NULL pointer or we find that this is already
540 	* in the table and duplicates were not allowed.
541 	*/
542 	newPointer	= &bucket->entries;
543 
544 	while   (*newPointer !=  NULL)
545 	{
546 		/* The value at new pointer is pointing to an existing entry.
547 		* If duplicates are allowed then we don't care what it is, but
548 		* must reject this add if the key is the same as the one we are
549 		* supplied with.
550 		*/
551 		if  (table->allowDups == ANTLR3_FALSE)
552 		{
553 			if	((*newPointer)->keybase.key.iKey == key)
554 			{
555 				return	ANTLR3_ERR_HASHDUP;
556 			}
557 		}
558 
559 		/* Point to the next entry pointer of the current entry we
560 		* are traversing, if it is NULL we will create our new
561 		* structure and point this to it.
562 		*/
563 		newPointer = &((*newPointer)->nextEntry);
564 	}
565 
566 	/* newPointer is now pointing at the pointer where we need to
567 	* add our new entry, so let's crate the entry and add it in.
568 	*/
569 	entry   = (pANTLR3_HASH_ENTRY)ANTLR3_MALLOC((size_t)sizeof(ANTLR3_HASH_ENTRY));
570 
571 	if	(entry == NULL)
572 	{
573 		return	ANTLR3_ERR_NOMEM;
574 	}
575 
576 	entry->data			= element;		/* Install the data element supplied			*/
577 	entry->free			= freeptr;		/* Function that knows how to release the entry		*/
578 	entry->keybase.type		= ANTLR3_HASH_TYPE_INT;	/* Indicate the key type stored here for when we free	*/
579 	entry->keybase.key.iKey	= key;			/* Record the key value					*/
580 	entry->nextEntry		= NULL;			/* Ensure that the forward pointer ends the chain	*/
581 
582 	*newPointer	= entry;    /* Install the next entry in this bucket	*/
583 
584 	table->count++;
585 
586 	return  ANTLR3_SUCCESS;
587 }
588 
589 
590 /** Add the element pointer in to the table, based upon the
591  *  hash of the provided key.
592  */
593 static	ANTLR3_INT32
antlr3HashPut(pANTLR3_HASH_TABLE table,void * key,void * element,void (ANTLR3_CDECL * freeptr)(void *))594 antlr3HashPut(pANTLR3_HASH_TABLE table, void * key, void * element, void (ANTLR3_CDECL *freeptr)(void *))
595 {
596 	ANTLR3_UINT32	    hash;
597 	pANTLR3_HASH_BUCKET	    bucket;
598 	pANTLR3_HASH_ENTRY	    entry;
599 	pANTLR3_HASH_ENTRY	    * newPointer;
600 
601 	/* First we need to know the hash of the provided key
602 	*/
603 	hash    = antlr3Hash(key, (ANTLR3_UINT32)strlen((const char *)key));
604 
605 	/* Knowing the hash, we can find the bucket
606 	*/
607 	bucket  = table->buckets + (hash % table->modulo);
608 
609 	/* Knowign the bucket, we can traverse the entries until we
610 	* we find a NULL pointer ofr we find that this is already
611 	* in the table and duplicates were not allowed.
612 	*/
613 	newPointer	= &bucket->entries;
614 
615 	while   (*newPointer !=  NULL)
616 	{
617 		/* The value at new pointer is pointing to an existing entry.
618 		* If duplicates are allowed then we don't care what it is, but
619 		* must reject this add if the key is the same as the one we are
620 		* supplied with.
621 		*/
622 		if  (table->allowDups == ANTLR3_FALSE)
623 		{
624 			if	(strcmp((const char*) key, (const char *)(*newPointer)->keybase.key.sKey) == 0)
625 			{
626 				return	ANTLR3_ERR_HASHDUP;
627 			}
628 		}
629 
630 		/* Point to the next entry pointer of the current entry we
631 		* are traversing, if it is NULL we will create our new
632 		* structure and point this to it.
633 		*/
634 		newPointer = &((*newPointer)->nextEntry);
635 	}
636 
637 	/* newPointer is now poiting at the pointer where we need to
638 	* add our new entry, so let's crate the entry and add it in.
639 	*/
640 	entry   = (pANTLR3_HASH_ENTRY)ANTLR3_MALLOC((size_t)sizeof(ANTLR3_HASH_ENTRY));
641 
642 	if	(entry == NULL)
643 	{
644 		return	ANTLR3_ERR_NOMEM;
645 	}
646 
647 	entry->data			= element;					/* Install the data element supplied				*/
648 	entry->free			= freeptr;					/* Function that knows how to release the entry	    */
649 	entry->keybase.type	= ANTLR3_HASH_TYPE_STR;     /* Indicate the key type stored here for free()	    */
650     if  (table->doStrdup == ANTLR3_TRUE)
651     {
652         entry->keybase.key.sKey	= ANTLR3_STRDUP(key);	/* Record the key value								*/
653     }
654     else
655     {
656         entry->keybase.key.sKey	= (pANTLR3_UINT8)key;                  /* Record the key value								*/
657     }
658 	entry->nextEntry		= NULL;					/* Ensure that the forward pointer ends the chain   */
659 
660 	*newPointer	= entry;    /* Install the next entry in this bucket	*/
661 
662 	table->count++;
663 
664 	return  ANTLR3_SUCCESS;
665 }
666 
667 /** \brief Creates an enumeration structure to traverse the hash table.
668  *
669  * \param table Table to enumerate
670  * \return Pointer to enumeration structure.
671  */
672 pANTLR3_HASH_ENUM
antlr3EnumNew(pANTLR3_HASH_TABLE table)673 antlr3EnumNew	(pANTLR3_HASH_TABLE table)
674 {
675     pANTLR3_HASH_ENUM	en;
676 
677     /* Allocate structure memory
678      */
679     en    = (pANTLR3_HASH_ENUM) ANTLR3_MALLOC((size_t)sizeof(ANTLR3_HASH_ENUM));
680 
681     /* Check that the allocation was good
682      */
683     if	(en == NULL)
684     {
685 	return	(pANTLR3_HASH_ENUM) ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
686     }
687 
688     /* Initialize the start pointers
689     */
690     en->table	= table;
691     en->bucket	= 0;				/* First bucket		    */
692     en->entry	= en->table->buckets->entries;	/* First entry to return    */
693 
694     /* Special case in that the first bucket may not have anything in it
695      * but the antlr3EnumNext() function expects that the en->entry is
696      * set to the next valid pointer. Hence if it is not a valid element
697      * pointer, attempt to find the next one that is, (table may be empty
698      * of course.
699      */
700     if	(en->entry == NULL)
701     {
702 	antlr3EnumNextEntry(en);
703     }
704 
705     /* Install the interface
706      */
707     en->free	=  antlr3EnumFree;
708     en->next	=  antlr3EnumNext;
709 
710     /* All is good
711      */
712     return  en;
713 }
714 
715 /** \brief Return the next entry in the hashtable being traversed by the supplied
716  *         enumeration.
717  *
718  * \param[in] en Pointer to the enumeration tracking structure
719  * \param key	 Pointer to void pointer, where the key pointer is returned.
720  * \param data	 Pointer to void pointer where the data pointer is returned.
721  * \return
722  *	- ANTLR3_SUCCESS if there was a next key
723  *	- ANTLR3_FAIL	 if there were no more keys
724  *
725  * \remark
726  *  No checking of input structure is performed!
727  */
728 static int
antlr3EnumNext(pANTLR3_HASH_ENUM en,pANTLR3_HASH_KEY * key,void ** data)729 antlr3EnumNext	(pANTLR3_HASH_ENUM en, pANTLR3_HASH_KEY * key, void ** data)
730 {
731     /* If the current entry is valid, then use it
732      */
733     if  (en->bucket >= en->table->modulo)
734     {
735         /* Already exhausted the table
736          */
737         return	ANTLR3_FAIL;
738     }
739 
740     /* Pointers are already set to the current entry to return, or
741      * we would not be at this point in the logic flow.
742      */
743     *key	= &(en->entry->keybase);
744     *data	= en->entry->data;
745 
746     /* Return pointers are set up, so now we move the element
747      * pointer to the next in the table (if any).
748      */
749     antlr3EnumNextEntry(en);
750 
751     return	ANTLR3_SUCCESS;
752 }
753 
754 /** \brief Local function to advance the entry pointer of an enumeration
755  * structure to the next valid entry (if there is one).
756  *
757  * \param[in] enum Pointer to ANTLR3 enumeration structure returned by antlr3EnumNew()
758  *
759  * \remark
760  *   - The function always leaves the pointers pointing at a valid entry if there
761  *     is one, so if the entry pointer is NULL when this function exits, there were
762  *     no more entries in the table.
763  */
764 static void
antlr3EnumNextEntry(pANTLR3_HASH_ENUM en)765 antlr3EnumNextEntry(pANTLR3_HASH_ENUM en)
766 {
767     pANTLR3_HASH_BUCKET	bucket;
768 
769     /* See if the current entry pointer is valid first of all
770      */
771     if	(en->entry != NULL)
772     {
773 	/* Current entry was a valid point, see if there is another
774 	 * one in the chain.
775 	 */
776 	if  (en->entry->nextEntry != NULL)
777 	{
778 	    /* Next entry in the enumeration is just the next entry
779 	     * in the chain.
780 	     */
781 	    en->entry = en->entry->nextEntry;
782 	    return;
783 	}
784     }
785 
786     /* There were no more entries in the current bucket, if there are
787      * more buckets then chase them until we find an entry.
788      */
789     en->bucket++;
790 
791     while   (en->bucket < en->table->modulo)
792     {
793 	/* There was one more bucket, see if it has any elements in it
794 	 */
795 	bucket	= en->table->buckets + en->bucket;
796 
797 	if  (bucket->entries != NULL)
798 	{
799 	    /* There was an entry in this bucket, so we can use it
800 	     * for the next entry in the enumeration.
801 	     */
802 	    en->entry	= bucket->entries;
803 	    return;
804 	}
805 
806 	/* There was nothing in the bucket we just examined, move to the
807 	 * next one.
808 	 */
809 	en->bucket++;
810     }
811 
812     /* Here we have exhausted all buckets and the enumeration pointer will
813      * have its bucket count = table->modulo which signifies that we are done.
814      */
815 }
816 
817 /** \brief Frees up the memory structures that represent a hash table
818  *  enumeration.
819  * \param[in] enum Pointer to ANTLR3 enumeration structure returned by antlr3EnumNew()
820  */
821 static void
antlr3EnumFree(pANTLR3_HASH_ENUM en)822 antlr3EnumFree	(pANTLR3_HASH_ENUM en)
823 {
824     /* Nothing to check, we just free it.
825      */
826     ANTLR3_FREE(en);
827 }
828 
829 /** Given an input key of arbitrary length, return a hash value of
830  *  it. This can then be used (with suitable modulo) to index other
831  *  structures.
832  */
833 ANTLR3_API ANTLR3_UINT32
antlr3Hash(void * key,ANTLR3_UINT32 keylen)834 antlr3Hash(void * key, ANTLR3_UINT32 keylen)
835 {
836     /* Accumulate the hash value of the key
837      */
838     ANTLR3_UINT32   hash;
839     pANTLR3_UINT8   keyPtr;
840     ANTLR3_UINT32   i1;
841 
842     hash    = 0;
843     keyPtr  = (pANTLR3_UINT8) key;
844 
845     /* Iterate the key and accumulate the hash
846      */
847     while(keylen > 0)
848     {
849 	hash = (hash << 4) + (*(keyPtr++));
850 
851 	if ((i1=hash&0xf0000000) != 0)
852 	{
853 		hash = hash ^ (i1 >> 24);
854 		hash = hash ^ i1;
855 	}
856 	keylen--;
857     }
858 
859     return  hash;
860 }
861 
862 ANTLR3_API  pANTLR3_LIST
antlr3ListNew(ANTLR3_UINT32 sizeHint)863 antlr3ListNew	(ANTLR3_UINT32 sizeHint)
864 {
865     pANTLR3_LIST    list;
866 
867     /* Allocate memory
868      */
869     list    = (pANTLR3_LIST)ANTLR3_MALLOC((size_t)sizeof(ANTLR3_LIST));
870 
871     if	(list == NULL)
872     {
873 	return	(pANTLR3_LIST)ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
874     }
875 
876     /* Now we need to add a new table
877      */
878     list->table	= antlr3HashTableNew(sizeHint);
879 
880     if	(list->table == (pANTLR3_HASH_TABLE)ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM))
881     {
882 	return	(pANTLR3_LIST)ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
883     }
884 
885     /* Allocation was good, install interface
886      */
887     list->free	    =  antlr3ListFree;
888     list->del	    =  antlr3ListDelete;
889     list->get	    =  antlr3ListGet;
890     list->add	    =  antlr3ListAdd;
891     list->remove    =  antlr3ListRemove;
892     list->put	    =  antlr3ListPut;
893     list->size	    =  antlr3ListSize;
894 
895     return  list;
896 }
897 
antlr3ListSize(pANTLR3_LIST list)898 static ANTLR3_UINT32	antlr3ListSize	    (pANTLR3_LIST list)
899 {
900     return  list->table->size(list->table);
901 }
902 
903 static void
antlr3ListFree(pANTLR3_LIST list)904 antlr3ListFree	(pANTLR3_LIST list)
905 {
906     /* Free the hashtable that stores the list
907      */
908     list->table->free(list->table);
909 
910     /* Free the allocation for the list itself
911      */
912     ANTLR3_FREE(list);
913 }
914 
915 static void
antlr3ListDelete(pANTLR3_LIST list,ANTLR3_INTKEY key)916 antlr3ListDelete    (pANTLR3_LIST list, ANTLR3_INTKEY key)
917 {
918     list->table->delI(list->table, key);
919 }
920 
921 static void *
antlr3ListGet(pANTLR3_LIST list,ANTLR3_INTKEY key)922 antlr3ListGet	    (pANTLR3_LIST list, ANTLR3_INTKEY key)
923 {
924     return list->table->getI(list->table, key);
925 }
926 
927 /** Add the supplied element to the list, at the next available key
928  */
antlr3ListAdd(pANTLR3_LIST list,void * element,void (ANTLR3_CDECL * freeptr)(void *))929 static ANTLR3_INT32	antlr3ListAdd   (pANTLR3_LIST list, void * element, void (ANTLR3_CDECL *freeptr)(void *))
930 {
931     ANTLR3_INTKEY   key;
932 
933     key	    = list->table->size(list->table) + 1;
934     return list->put(list, key, element, freeptr);
935 }
936 
937 /** Remove from the list, but don't free the element, just send it back to the
938  *  caller.
939  */
940 static	void *
antlr3ListRemove(pANTLR3_LIST list,ANTLR3_INTKEY key)941 antlr3ListRemove	    (pANTLR3_LIST list, ANTLR3_INTKEY key)
942 {
943     pANTLR3_HASH_ENTRY	    entry;
944 
945     entry = list->table->removeI(list->table, key);
946 
947     if	(entry != NULL)
948     {
949         return  entry->data;
950     }
951     else
952     {
953 	return	NULL;
954     }
955 }
956 
957 static	ANTLR3_INT32
antlr3ListPut(pANTLR3_LIST list,ANTLR3_INTKEY key,void * element,void (ANTLR3_CDECL * freeptr)(void *))958 antlr3ListPut	    (pANTLR3_LIST list, ANTLR3_INTKEY key, void * element, void (ANTLR3_CDECL *freeptr)(void *))
959 {
960     return  list->table->putI(list->table, key, element, freeptr);
961 }
962 
963 ANTLR3_API  pANTLR3_STACK
antlr3StackNew(ANTLR3_UINT32 sizeHint)964 antlr3StackNew	(ANTLR3_UINT32 sizeHint)
965 {
966     pANTLR3_STACK   stack;
967 
968     /* Allocate memory
969      */
970     stack    = (pANTLR3_STACK)ANTLR3_MALLOC((size_t)sizeof(ANTLR3_STACK));
971 
972     if	(stack == NULL)
973     {
974 	return	(pANTLR3_STACK)ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
975     }
976 
977     /* Now we need to add a new table
978      */
979     stack->vector   = antlr3VectorNew(sizeHint);
980     stack->top	    = NULL;
981 
982     if	(stack->vector == (pANTLR3_VECTOR)ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM))
983     {
984 	return	(pANTLR3_STACK)ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
985     }
986 
987     /* Looks good, now add the interface
988      */
989     stack->get	=  antlr3StackGet;
990     stack->free	=  antlr3StackFree;
991     stack->pop	=  antlr3StackPop;
992     stack->push	=  antlr3StackPush;
993     stack->size	=  antlr3StackSize;
994     stack->peek	=  antlr3StackPeek;
995 
996     return  stack;
997 }
998 
antlr3StackSize(pANTLR3_STACK stack)999 static ANTLR3_UINT32	antlr3StackSize	    (pANTLR3_STACK stack)
1000 {
1001     return  stack->vector->count;
1002 }
1003 
1004 
1005 static void
antlr3StackFree(pANTLR3_STACK stack)1006 antlr3StackFree	(pANTLR3_STACK  stack)
1007 {
1008     /* Free the list that supports the stack
1009      */
1010     stack->vector->free(stack->vector);
1011     stack->vector   = NULL;
1012     stack->top	    = NULL;
1013 
1014     ANTLR3_FREE(stack);
1015 }
1016 
1017 static void *
antlr3StackPop(pANTLR3_STACK stack)1018 antlr3StackPop	(pANTLR3_STACK	stack)
1019 {
1020     // Delete the element that is currently at the top of the stack
1021     //
1022     stack->vector->del(stack->vector, stack->vector->count - 1);
1023 
1024     // And get the element that is the now the top of the stack (if anything)
1025     // NOTE! This is not quite like a 'real' stack, which would normally return you
1026     // the current top of the stack, then remove it from the stack.
1027     // TODO: Review this, it is correct for follow sets which is what this was done for
1028     //       but is not as obvious when using it as a 'real'stack.
1029     //
1030     stack->top = stack->vector->get(stack->vector, stack->vector->count - 1);
1031     return stack->top;
1032 }
1033 
1034 static void *
antlr3StackGet(pANTLR3_STACK stack,ANTLR3_INTKEY key)1035 antlr3StackGet	(pANTLR3_STACK stack, ANTLR3_INTKEY key)
1036 {
1037     return  stack->vector->get(stack->vector, (ANTLR3_UINT32)key);
1038 }
1039 
1040 static void *
antlr3StackPeek(pANTLR3_STACK stack)1041 antlr3StackPeek	(pANTLR3_STACK	stack)
1042 {
1043     return  stack->top;
1044 }
1045 
1046 static ANTLR3_BOOLEAN
antlr3StackPush(pANTLR3_STACK stack,void * element,void (ANTLR3_CDECL * freeptr)(void *))1047 antlr3StackPush	(pANTLR3_STACK stack, void * element, void (ANTLR3_CDECL *freeptr)(void *))
1048 {
1049     stack->top	= element;
1050     return (ANTLR3_BOOLEAN)(stack->vector->add(stack->vector, element, freeptr));
1051 }
1052 
1053 ANTLR3_API  pANTLR3_VECTOR
antlr3VectorNew(ANTLR3_UINT32 sizeHint)1054 antlr3VectorNew	(ANTLR3_UINT32 sizeHint)
1055 {
1056 	pANTLR3_VECTOR  vector;
1057 
1058 
1059 	// Allocate memory for the vector structure itself
1060 	//
1061 	vector  = (pANTLR3_VECTOR) ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_VECTOR)));
1062 
1063 	if	(vector == NULL)
1064 	{
1065 		return	(pANTLR3_VECTOR)ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
1066 	}
1067 
1068 	// Now fill in the defaults
1069 	//
1070     antlr3SetVectorApi(vector, sizeHint);
1071 
1072 	// And everything is hunky dory
1073 	//
1074 	return  vector;
1075 }
1076 
1077 ANTLR3_API void
antlr3SetVectorApi(pANTLR3_VECTOR vector,ANTLR3_UINT32 sizeHint)1078 antlr3SetVectorApi  (pANTLR3_VECTOR vector, ANTLR3_UINT32 sizeHint)
1079 {
1080     ANTLR3_UINT32   initialSize;
1081 
1082     // Allow vectors to be guessed by ourselves, so input size can be zero
1083     //
1084     if	(sizeHint > ANTLR3_VECTOR_INTERNAL_SIZE)
1085     {
1086         initialSize = sizeHint;
1087     }
1088     else
1089     {
1090         initialSize = ANTLR3_VECTOR_INTERNAL_SIZE;
1091     }
1092 
1093     if  (sizeHint > ANTLR3_VECTOR_INTERNAL_SIZE)
1094     {
1095         vector->elements	= (pANTLR3_VECTOR_ELEMENT)ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_VECTOR_ELEMENT) * initialSize));
1096     }
1097     else
1098     {
1099         vector->elements    = vector->internal;
1100     }
1101 
1102     if	(vector->elements == NULL)
1103     {
1104         ANTLR3_FREE(vector);
1105         return;
1106     }
1107 
1108     // Memory allocated successfully
1109     //
1110     vector->count			= 0;			// No entries yet of course
1111     vector->elementsSize    = initialSize;  // Available entries
1112 
1113     // Now we can install the API
1114     //
1115     vector->add	    = antlr3VectorAdd;
1116     vector->del	    = antlr3VectorDel;
1117     vector->get	    = antlr3VectorGet;
1118     vector->free    = antlr3VectorFree;
1119     vector->set	    = antlr3VectorSet;
1120     vector->remove  = antrl3VectorRemove;
1121     vector->clear   = antlr3VectorClear;
1122     vector->size    = antlr3VectorSize;
1123     vector->swap    = antlr3VectorSwap;
1124 
1125     // Assume that this is not a factory made vector
1126     //
1127     vector->factoryMade	= ANTLR3_FALSE;
1128 }
1129 
1130 // Clear the entries in a vector.
1131 // Clearing the vector leaves its capacity the same but
1132 // it walks the entries first to see if any of them
1133 // have a free routine that must be called.
1134 //
1135 static	void
antlr3VectorClear(pANTLR3_VECTOR vector)1136 antlr3VectorClear	(pANTLR3_VECTOR vector)
1137 {
1138 	ANTLR3_UINT32   entry;
1139 
1140 	// We must traverse every entry in the vector and if it has
1141 	// a pointer to a free function then we call it with the
1142 	// the entry pointer
1143 	//
1144 	for	(entry = 0; entry < vector->count; entry++)
1145 	{
1146 		if  (vector->elements[entry].freeptr != NULL)
1147 		{
1148 			vector->elements[entry].freeptr(vector->elements[entry].element);
1149 		}
1150 		vector->elements[entry].freeptr    = NULL;
1151 		vector->elements[entry].element    = NULL;
1152 	}
1153 
1154 	// Having called any free pointers, we just reset the entry count
1155 	// back to zero.
1156 	//
1157 	vector->count	= 0;
1158 }
1159 
1160 static
antlr3VectorFree(pANTLR3_VECTOR vector)1161 void	ANTLR3_CDECL	antlr3VectorFree    (pANTLR3_VECTOR vector)
1162 {
1163 	ANTLR3_UINT32   entry;
1164 
1165 	// We must traverse every entry in the vector and if it has
1166 	// a pointer to a free function then we call it with the
1167 	// the entry pointer
1168 	//
1169 	for	(entry = 0; entry < vector->count; entry++)
1170 	{
1171 		if  (vector->elements[entry].freeptr != NULL)
1172 		{
1173 			vector->elements[entry].freeptr(vector->elements[entry].element);
1174 		}
1175 		vector->elements[entry].freeptr    = NULL;
1176 		vector->elements[entry].element    = NULL;
1177 	}
1178 
1179 	if	(vector->factoryMade == ANTLR3_FALSE)
1180 	{
1181 		// The entries are freed, so free the element allocation
1182 		//
1183         if  (vector->elementsSize > ANTLR3_VECTOR_INTERNAL_SIZE)
1184         {
1185             ANTLR3_FREE(vector->elements);
1186         }
1187 		vector->elements = NULL;
1188 
1189 		// Finally, free the allocation for the vector itself
1190 		//
1191 		ANTLR3_FREE(vector);
1192 	}
1193 }
1194 
antlr3VectorDel(pANTLR3_VECTOR vector,ANTLR3_UINT32 entry)1195 static	void		antlr3VectorDel	    (pANTLR3_VECTOR vector, ANTLR3_UINT32 entry)
1196 {
1197 	// Check this is a valid request first
1198 	//
1199 	if	(entry >= vector->count)
1200 	{
1201 		return;
1202 	}
1203 
1204 	// Valid request, check for free pointer and call it if present
1205 	//
1206 	if	(vector->elements[entry].freeptr != NULL)
1207 	{
1208 		vector->elements[entry].freeptr(vector->elements[entry].element);
1209 		vector->elements[entry].freeptr    = NULL;
1210 	}
1211 
1212 	if	(entry == vector->count - 1)
1213 	{
1214 		// Ensure the pointer is never reused by accident, but otherwise just
1215 		// decrement the pointer.
1216 		//
1217 		vector->elements[entry].element    = NULL;
1218 	}
1219 	else
1220 	{
1221 		// Need to shuffle trailing pointers back over the deleted entry
1222 		//
1223 		ANTLR3_MEMMOVE(vector->elements + entry, vector->elements + entry + 1, sizeof(ANTLR3_VECTOR_ELEMENT) * (vector->count - entry - 1));
1224 	}
1225 
1226 	// One less entry in the vector now
1227 	//
1228 	vector->count--;
1229 }
1230 
antlr3VectorGet(pANTLR3_VECTOR vector,ANTLR3_UINT32 entry)1231 static	void *		antlr3VectorGet     (pANTLR3_VECTOR vector, ANTLR3_UINT32 entry)
1232 {
1233 	// Ensure this is a valid request
1234 	//
1235 	if	(entry < vector->count)
1236 	{
1237 		return	vector->elements[entry].element;
1238 	}
1239 	else
1240 	{
1241 		// I know nothing, Mr. Fawlty!
1242 		//
1243 		return	NULL;
1244 	}
1245 }
1246 
1247 /// Remove the entry from the vector, but do not free any entry, even if it has
1248 /// a free pointer.
1249 ///
antrl3VectorRemove(pANTLR3_VECTOR vector,ANTLR3_UINT32 entry)1250 static	void *		antrl3VectorRemove  (pANTLR3_VECTOR vector, ANTLR3_UINT32 entry)
1251 {
1252 	void * element;
1253 
1254 	// Check this is a valid request first
1255 	//
1256 	if	(entry >= vector->count)
1257 	{
1258 		return NULL;
1259 	}
1260 
1261 	// Valid request, return the sorted pointer
1262 	//
1263 
1264 	element				    = vector->elements[entry].element;
1265 
1266 	if	(entry == vector->count - 1)
1267 	{
1268 		// Ensure the pointer is never reused by accident, but otherwise just
1269 		// decrement the pointer.
1270 		///
1271 		vector->elements[entry].element    = NULL;
1272 		vector->elements[entry].freeptr    = NULL;
1273 	}
1274 	else
1275 	{
1276 		// Need to shuffle trailing pointers back over the deleted entry
1277 		//
1278 		ANTLR3_MEMMOVE(vector->elements + entry, vector->elements + entry + 1, sizeof(ANTLR3_VECTOR_ELEMENT) * (vector->count - entry - 1));
1279 	}
1280 
1281 	// One less entry in the vector now
1282 	//
1283 	vector->count--;
1284 
1285 	return  element;
1286 }
1287 
1288 static  ANTLR3_BOOLEAN
antlr3VectorResize(pANTLR3_VECTOR vector,ANTLR3_UINT32 hint)1289 antlr3VectorResize  (pANTLR3_VECTOR vector, ANTLR3_UINT32 hint)
1290 {
1291 	ANTLR3_UINT32	newSize;
1292 
1293 	// Need to resize the element pointers. We double the allocation
1294 	// we already have unless asked for a specific increase.
1295     //
1296     if (hint == 0 || hint < vector->elementsSize)
1297     {
1298         newSize = vector->elementsSize * 2;
1299     }
1300     else
1301     {
1302         newSize = hint * 2;
1303     }
1304 
1305     // Now we know how many we need, so we see if we have just expanded
1306     // past the built in vector elements or were already past that
1307     //
1308     if  (vector->elementsSize > ANTLR3_VECTOR_INTERNAL_SIZE)
1309     {
1310         // We were already larger than the internal size, so we just
1311         // use realloc so that the pointers are copied for us
1312         //
1313 		pANTLR3_VECTOR_ELEMENT newElements = (pANTLR3_VECTOR_ELEMENT)ANTLR3_REALLOC(vector->elements, (sizeof(ANTLR3_VECTOR_ELEMENT)* newSize));
1314 		if (newElements == NULL)
1315 		{
1316 			// realloc failed, but the old allocation is still there
1317 			return ANTLR3_FALSE;
1318 		}
1319         vector->elements = newElements;
1320     }
1321     else
1322     {
1323         // The current size was less than or equal to the internal array size and as we always start
1324         // with a size that is at least the maximum internal size, then we must need to allocate new memory
1325         // for external pointers. We don't want to take the time to calculate if a requested element
1326         // is part of the internal or external entries, so we copy the internal ones to the new space
1327         //
1328         vector->elements	= (pANTLR3_VECTOR_ELEMENT)ANTLR3_MALLOC((sizeof(ANTLR3_VECTOR_ELEMENT)* newSize));
1329 		if (vector->elements == NULL)
1330 		{
1331 			// malloc failed
1332 			return ANTLR3_FALSE;
1333 		}
1334         ANTLR3_MEMCPY(vector->elements, vector->internal, ANTLR3_VECTOR_INTERNAL_SIZE * sizeof(ANTLR3_VECTOR_ELEMENT));
1335     }
1336 
1337 	vector->elementsSize	= newSize;
1338 	return ANTLR3_TRUE;
1339 }
1340 
1341 /// Add the supplied pointer and freeing function pointer to the list,
1342 /// expanding the vector if needed.
1343 ///
antlr3VectorAdd(pANTLR3_VECTOR vector,void * element,void (ANTLR3_CDECL * freeptr)(void *))1344 static	ANTLR3_UINT32    antlr3VectorAdd	    (pANTLR3_VECTOR vector, void * element, void (ANTLR3_CDECL *freeptr)(void *))
1345 {
1346 	// Do we need to resize the vector table?
1347 	//
1348 	if	(vector->count == vector->elementsSize)
1349 	{
1350 		// Give no hint, we let it add 1024 or double it
1351 		if (!antlr3VectorResize(vector, 0))
1352 		{
1353 			// Resize failed
1354 			return 0;
1355 		}
1356 	}
1357 
1358 	// Insert the new entry
1359 	//
1360 	vector->elements[vector->count].element	= element;
1361 	vector->elements[vector->count].freeptr	= freeptr;
1362 
1363 	vector->count++;	    // One more element counted
1364 
1365 	return  (ANTLR3_UINT32)(vector->count);
1366 
1367 }
1368 
1369 /// Replace the element at the specified entry point with the supplied
1370 /// entry.
1371 ///
1372 static	ANTLR3_UINT32
antlr3VectorSet(pANTLR3_VECTOR vector,ANTLR3_UINT32 entry,void * element,void (ANTLR3_CDECL * freeptr)(void *),ANTLR3_BOOLEAN freeExisting)1373 antlr3VectorSet	    (pANTLR3_VECTOR vector, ANTLR3_UINT32 entry, void * element, void (ANTLR3_CDECL *freeptr)(void *), ANTLR3_BOOLEAN freeExisting)
1374 {
1375 
1376 	// If the vector is currently not big enough, then we expand it
1377 	//
1378 	if (entry >= vector->elementsSize)
1379 	{
1380 		// We will get at least this many
1381 		if (!antlr3VectorResize(vector, entry))
1382 		{
1383 			// Resize failed
1384 			return 0;
1385 		}
1386 	}
1387 
1388 	// Valid request, replace the current one, freeing any prior entry if told to
1389 	//
1390 	if	(		entry < vector->count						// If actually replacing an element
1391 			&&	freeExisting								// And told to free any existing element
1392 			&&	vector->elements[entry].freeptr != NULL		// And the existing element has a free pointer
1393 		)
1394 	{
1395 		vector->elements[entry].freeptr(vector->elements[entry].element);
1396 	}
1397 
1398 	// Install the new pointers
1399 	//
1400 	vector->elements[entry].freeptr	= freeptr;
1401 	vector->elements[entry].element	= element;
1402 
1403 	if (entry >= vector->count)
1404 	{
1405 		vector->count = entry + 1;
1406 	}
1407 	return  (ANTLR3_UINT32)(entry);	    // Indicates the replacement was successful
1408 
1409 }
1410 
1411 /// Replace the element at the specified entry point with the supplied
1412 /// entry.
1413 ///
1414 static	ANTLR3_BOOLEAN
antlr3VectorSwap(pANTLR3_VECTOR vector,ANTLR3_UINT32 entry1,ANTLR3_UINT32 entry2)1415 antlr3VectorSwap	    (pANTLR3_VECTOR vector, ANTLR3_UINT32 entry1, ANTLR3_UINT32 entry2)
1416 {
1417 
1418     void               * tempEntry;
1419     void (ANTLR3_CDECL *freeptr)(void *);
1420 
1421 	// If the vector is currently not big enough, then we do nothing
1422 	//
1423 	if (entry1 >= vector->elementsSize || entry2 >= vector->elementsSize)
1424 	{
1425         return ANTLR3_FALSE;
1426 	}
1427 
1428 	// Valid request, swap them
1429 	//
1430     tempEntry   = vector->elements[entry1].element;
1431     freeptr     = vector->elements[entry1].freeptr;
1432 
1433 	// Install the new pointers
1434 	//
1435     vector->elements[entry1].freeptr	= vector->elements[entry2].freeptr;
1436 	vector->elements[entry1].element	= vector->elements[entry2].element;
1437 
1438 	vector->elements[entry2].freeptr	= freeptr;
1439 	vector->elements[entry2].element	= tempEntry;
1440 
1441 	return  ANTLR3_TRUE;
1442 
1443 }
1444 
antlr3VectorSize(pANTLR3_VECTOR vector)1445 static	ANTLR3_UINT32   antlr3VectorSize    (pANTLR3_VECTOR vector)
1446 {
1447     return  vector->count;
1448 }
1449 
1450 #ifdef ANTLR3_WINDOWS
1451 #pragma warning	(push)
1452 #pragma warning (disable : 4100)
1453 #endif
1454 /// Vector factory creation
1455 ///
1456 ANTLR3_API pANTLR3_VECTOR_FACTORY
antlr3VectorFactoryNew(ANTLR3_UINT32 sizeHint)1457 antlr3VectorFactoryNew	    (ANTLR3_UINT32 sizeHint)
1458 {
1459 	pANTLR3_VECTOR_FACTORY  factory;
1460 
1461 	// Allocate memory for the factory
1462 	//
1463 	factory = (pANTLR3_VECTOR_FACTORY)ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_VECTOR_FACTORY)));
1464 
1465 	if	(factory == NULL)
1466 	{
1467 		return	NULL;
1468 	}
1469 
1470 	// Factory memory is good, so create a new vector pool
1471 	//
1472     factory->pools      = NULL;
1473     factory->thisPool   = -1;
1474 
1475     newPool(factory);
1476 
1477     // Initialize the API, ignore the hint as this algorithm does
1478     // a better job really.
1479     //
1480     antlr3SetVectorApi(&(factory->unTruc), ANTLR3_VECTOR_INTERNAL_SIZE);
1481 
1482     factory->unTruc.factoryMade = ANTLR3_TRUE;
1483 
1484 	// Install the factory API
1485 	//
1486 	factory->close			= closeVectorFactory;
1487 	factory->newVector		= newVector;
1488 	factory->returnVector	= returnVector;
1489 
1490 	// Create a stack to accumulate reusable vectors
1491 	//
1492 	factory->freeStack		= antlr3StackNew(16);
1493 	return  factory;
1494 }
1495 #ifdef ANTLR3_WINDOWS
1496 #pragma warning	(pop)
1497 #endif
1498 
1499 static	void
returnVector(pANTLR3_VECTOR_FACTORY factory,pANTLR3_VECTOR vector)1500 returnVector		(pANTLR3_VECTOR_FACTORY factory, pANTLR3_VECTOR vector)
1501 {
1502 	// First we need to clear out anything that is still in the vector
1503 	//
1504 	vector->clear(vector);
1505 
1506 	// We have a free stack available so we can add the vector we were
1507 	// given into the free chain. The vector has to have come from this
1508 	// factory, so we already know how to release its memory when it
1509 	// dies by virtue of the factory being closed.
1510 	//
1511 	factory->freeStack->push(factory->freeStack, vector, NULL);
1512 
1513 	// TODO: remove this line once happy printf("Returned vector %08X to the pool, stack size is %d\n", vector, factory->freeStack->size(factory->freeStack));
1514 }
1515 
1516 static ANTLR3_BOOLEAN
newPool(pANTLR3_VECTOR_FACTORY factory)1517 newPool(pANTLR3_VECTOR_FACTORY factory)
1518 {
1519 	pANTLR3_VECTOR *newPools;
1520 
1521     /* Increment factory count
1522      */
1523     ++factory->thisPool;
1524 
1525     /* Ensure we have enough pointers allocated
1526      */
1527 	newPools = (pANTLR3_VECTOR *)
1528 		ANTLR3_REALLOC(	(void *)factory->pools,	    /* Current pools pointer (starts at NULL)	*/
1529 					(ANTLR3_UINT32)((factory->thisPool + 1) * sizeof(pANTLR3_VECTOR *))	/* Memory for new pool pointers */
1530 					);
1531 	if (newPools == NULL)
1532 	{
1533 		// realloc failed, but we still have the old allocation
1534 		--factory->thisPool;
1535 		return ANTLR3_FALSE;
1536 	}
1537 	factory->pools = newPools;
1538 
1539     /* Allocate a new pool for the factory
1540      */
1541     factory->pools[factory->thisPool]	=
1542 			    (pANTLR3_VECTOR)
1543 				ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_VECTOR) * ANTLR3_FACTORY_VPOOL_SIZE));
1544 	if (factory->pools[factory->thisPool] == NULL)
1545 	{
1546 		// malloc failed
1547 		--factory->thisPool;
1548 		return ANTLR3_FALSE;
1549 	}
1550 
1551 
1552     /* Reset the counters
1553      */
1554     factory->nextVector	= 0;
1555 
1556     /* Done
1557      */
1558     return ANTLR3_TRUE;
1559 }
1560 
1561 static  void
closeVectorFactory(pANTLR3_VECTOR_FACTORY factory)1562 closeVectorFactory  (pANTLR3_VECTOR_FACTORY factory)
1563 {
1564     pANTLR3_VECTOR      pool;
1565     ANTLR3_INT32        poolCount;
1566     ANTLR3_UINT32       limit;
1567     ANTLR3_UINT32       vector;
1568     pANTLR3_VECTOR      check;
1569 
1570 	// First see if we have a free chain stack to release?
1571 	//
1572 	if	(factory->freeStack != NULL)
1573 	{
1574 		factory->freeStack->free(factory->freeStack);
1575 	}
1576 
1577     /* We iterate the vector pools one at a time
1578      */
1579     for (poolCount = 0; poolCount <= factory->thisPool; poolCount++)
1580     {
1581         /* Pointer to current pool
1582          */
1583         pool = factory->pools[poolCount];
1584 
1585         /* Work out how many tokens we need to check in this pool.
1586          */
1587         limit = (poolCount == factory->thisPool ? factory->nextVector : ANTLR3_FACTORY_VPOOL_SIZE);
1588 
1589         /* Marginal condition, we might be at the start of a brand new pool
1590          * where the nextToken is 0 and nothing has been allocated.
1591          */
1592         if (limit > 0)
1593         {
1594             /* We have some vectors allocated from this pool
1595              */
1596             for (vector = 0; vector < limit; vector++)
1597             {
1598                 /* Next one in the chain
1599                  */
1600                 check = pool + vector;
1601 
1602                 // Call the free function on each of the vectors in the pool,
1603                 // which in turn will cause any elements it holds that also have a free
1604                 // pointer to be freed. However, because any vector may be in any other
1605                 // vector, we don't free the element allocations yet. We do that in a
1606                 // a specific pass, coming up next. The vector free function knows that
1607                 // this is a factory allocated pool vector and so it won't free things it
1608                 // should not.
1609                 //
1610                 check->free(check);
1611             }
1612         }
1613     }
1614 
1615     /* We iterate the vector pools one at a time once again, but this time
1616      * we are going to free up any allocated element pointers. Note that we are doing this
1617      * so that we do not try to release vectors twice. When building ASTs we just copy
1618      * the vectors all over the place and they may be embedded in this vector pool
1619      * numerous times.
1620      */
1621     for (poolCount = 0; poolCount <= factory->thisPool; poolCount++)
1622     {
1623         /* Pointer to current pool
1624          */
1625         pool = factory->pools[poolCount];
1626 
1627         /* Work out how many tokens we need to check in this pool.
1628          */
1629         limit = (poolCount == factory->thisPool ? factory->nextVector : ANTLR3_FACTORY_VPOOL_SIZE);
1630 
1631         /* Marginal condition, we might be at the start of a brand new pool
1632          * where the nextToken is 0 and nothing has been allocated.
1633          */
1634         if (limit > 0)
1635         {
1636             /* We have some vectors allocated from this pool
1637              */
1638             for (vector = 0; vector < limit; vector++)
1639             {
1640                 /* Next one in the chain
1641                  */
1642                 check = pool + vector;
1643 
1644                 // Anything in here should be factory made, but we do this just
1645                 // to triple check. We just free up the elements if they were
1646                 // allocated beyond the internal size.
1647                 //
1648                 if (check->factoryMade == ANTLR3_TRUE && check->elementsSize > ANTLR3_VECTOR_INTERNAL_SIZE)
1649                 {
1650                     ANTLR3_FREE(check->elements);
1651                     check->elements = NULL;
1652                 }
1653             }
1654         }
1655 
1656         // We can now free this pool allocation as we have called free on every element in every vector
1657         // and freed any memory for pointers the grew beyond the internal size limit.
1658         //
1659         ANTLR3_FREE(factory->pools[poolCount]);
1660         factory->pools[poolCount] = NULL;
1661     }
1662 
1663     /* All the pools are deallocated we can free the pointers to the pools
1664      * now.
1665      */
1666     ANTLR3_FREE(factory->pools);
1667 
1668     /* Finally, we can free the space for the factory itself
1669      */
1670     ANTLR3_FREE(factory);
1671 
1672 }
1673 
1674 static pANTLR3_VECTOR
newVector(pANTLR3_VECTOR_FACTORY factory)1675 newVector(pANTLR3_VECTOR_FACTORY factory)
1676 {
1677     pANTLR3_VECTOR vector;
1678 
1679 	// If we have anything on the re claim stack, reuse it
1680 	//
1681 	vector = (pANTLR3_VECTOR)factory->freeStack->peek(factory->freeStack);
1682 
1683 	if  (vector != NULL)
1684 	{
1685 		// Cool we got something we could reuse
1686 		//
1687 		factory->freeStack->pop(factory->freeStack);
1688 
1689 		// TODO: remove this line once happy printf("Reused vector %08X from stack, size is now %d\n", vector, factory->freeStack->size(factory->freeStack));
1690 		return vector;
1691 
1692 	}
1693 
1694 	// See if we need a new vector pool before allocating a new
1695     // one
1696     //
1697     if (factory->nextVector >= ANTLR3_FACTORY_VPOOL_SIZE)
1698     {
1699         // We ran out of vectors in the current pool, so we need a new pool
1700         //
1701         if (!newPool(factory))
1702 		{
1703 			// new pool creation failed
1704 			return NULL;
1705 		}
1706     }
1707 
1708     // Assuming everything went well (we are trying for performance here so doing minimal
1709     // error checking. Then we can work out what the pointer is to the next vector.
1710     //
1711     vector = factory->pools[factory->thisPool] + factory->nextVector;
1712     factory->nextVector++;
1713 
1714     // We have our token pointer now, so we can initialize it to the predefined model.
1715     //
1716     antlr3SetVectorApi(vector, ANTLR3_VECTOR_INTERNAL_SIZE);
1717     vector->factoryMade = ANTLR3_TRUE;
1718 
1719     // We know that the pool vectors are created at the default size, which means they
1720     // will start off using their internal entry pointers. We must initialize our pool vector
1721     // to point to its own internal entry table and not the pre-made one.
1722     //
1723     vector->elements = vector->internal;
1724 
1725 		// TODO: remove this line once happy printf("Used a new vector at %08X from the pools as nothing on the reusue stack\n", vector);
1726 
1727     // And we are done
1728     //
1729     return vector;
1730 }
1731 
1732 /** Array of left most significant bit positions for an 8 bit
1733  *  element provides an efficient way to find the highest bit
1734  *  that is set in an n byte value (n>0). Assuming the values will all hit the data cache,
1735  *  coding without conditional elements should allow branch
1736  *  prediction to work well and of course a parallel instruction cache
1737  *  will whip through this. Otherwise we must loop shifting a one
1738  *  bit and masking. The values we tend to be placing in out integer
1739  *  patricia trie are usually a lot lower than the 64 bits we
1740  *  allow for the key allows. Hence there is a lot of redundant looping and
1741  *  shifting in a while loop. Whereas, the lookup table is just
1742  *  a few ands and indirect lookups, while testing for 0. This
1743  *  is likely to be done in parallel on many processors available
1744  *  when I wrote this. If this code survives as long as yacc, then
1745  *  I may already be dead by the time you read this and maybe there is
1746  *  a single machine instruction to perform the operation. What
1747  *  else are you going to do with all those transistors? Jim 2007
1748  *
1749  * The table is probably obvious but it is just the number 0..7
1750  * of the MSB in each integer value 0..256
1751  */
1752 static ANTLR3_UINT8 bitIndex[256] =
1753 {
1754     0,													// 0 - Just for padding
1755     0,													// 1
1756     1, 1,												// 2..3
1757     2, 2, 2, 2,											// 4..7
1758     3, 3, 3, 3, 3, 3, 3, 3,								// 8+
1759     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,	    // 16+
1760     5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,	    // 32+
1761 	5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1762     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,	    // 64+
1763 	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
1764 	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
1765 	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
1766     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,	    // 128+
1767 	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1768 	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1769 	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1770 	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1771 	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1772 	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1773 	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
1774 };
1775 
1776 /** Rather than use the bit index of a trie node to shift
1777  *  0x01 left that many times, then & with the result, it is
1778  *  faster to use the bit index as an index into this table
1779  *  which holds precomputed masks for any of the 64 bits
1780  *  we need to mask off singly. The data values will stay in
1781  *  cache while ever a trie is in heavy use, such as in
1782  *  memoization. It is also pretty enough to be ASCII art.
1783  */
1784 static ANTLR3_UINT64 bitMask[64] =
1785 {
1786     0x0000000000000001ULL, 0x0000000000000002ULL, 0x0000000000000004ULL, 0x0000000000000008ULL,
1787     0x0000000000000010ULL, 0x0000000000000020ULL, 0x0000000000000040ULL, 0x0000000000000080ULL,
1788     0x0000000000000100ULL, 0x0000000000000200ULL, 0x0000000000000400ULL, 0x0000000000000800ULL,
1789     0x0000000000001000ULL, 0x0000000000002000ULL, 0x0000000000004000ULL, 0x0000000000008000ULL,
1790     0x0000000000010000ULL, 0x0000000000020000ULL, 0x0000000000040000ULL, 0x0000000000080000ULL,
1791     0x0000000000100000ULL, 0x0000000000200000ULL, 0x0000000000400000ULL, 0x0000000000800000ULL,
1792     0x0000000001000000ULL, 0x0000000002000000ULL, 0x0000000004000000ULL, 0x0000000008000000ULL,
1793     0x0000000010000000ULL, 0x0000000020000000ULL, 0x0000000040000000ULL, 0x0000000080000000ULL,
1794     0x0000000100000000ULL, 0x0000000200000000ULL, 0x0000000400000000ULL, 0x0000000800000000ULL,
1795     0x0000001000000000ULL, 0x0000002000000000ULL, 0x0000004000000000ULL, 0x0000008000000000ULL,
1796     0x0000010000000000ULL, 0x0000020000000000ULL, 0x0000040000000000ULL, 0x0000080000000000ULL,
1797     0x0000100000000000ULL, 0x0000200000000000ULL, 0x0000400000000000ULL, 0x0000800000000000ULL,
1798     0x0001000000000000ULL, 0x0002000000000000ULL, 0x0004000000000000ULL, 0x0008000000000000ULL,
1799     0x0010000000000000ULL, 0x0020000000000000ULL, 0x0040000000000000ULL, 0x0080000000000000ULL,
1800     0x0100000000000000ULL, 0x0200000000000000ULL, 0x0400000000000000ULL, 0x0800000000000000ULL,
1801     0x1000000000000000ULL, 0x2000000000000000ULL, 0x4000000000000000ULL, 0x8000000000000000ULL
1802 };
1803 
1804 /* INT TRIE Implementation of depth 64 bits, being the number of bits
1805  * in a 64 bit integer.
1806  */
1807 
1808 pANTLR3_INT_TRIE
antlr3IntTrieNew(ANTLR3_UINT32 depth)1809 antlr3IntTrieNew(ANTLR3_UINT32 depth)
1810 {
1811 	pANTLR3_INT_TRIE	trie;
1812 
1813 	trie    = (pANTLR3_INT_TRIE) ANTLR3_CALLOC(1, sizeof(ANTLR3_INT_TRIE));	/* Base memory required	*/
1814 
1815 	if (trie == NULL)
1816 	{
1817 		return	(pANTLR3_INT_TRIE) ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
1818 	}
1819 
1820 	/* Now we need to allocate the root node. This makes it easier
1821 	 * to use the tree as we don't have to do anything special
1822 	 * for the root node.
1823 	 */
1824 	trie->root	= (pANTLR3_INT_TRIE_NODE) ANTLR3_CALLOC(1, sizeof(ANTLR3_INT_TRIE));
1825 
1826 	if (trie->root == NULL)
1827 	{
1828 		ANTLR3_FREE(trie);
1829 		return	(pANTLR3_INT_TRIE) ANTLR3_FUNC_PTR(ANTLR3_ERR_NOMEM);
1830 	}
1831 
1832 	trie->add	= intTrieAdd;
1833 	trie->del	= intTrieDel;
1834 	trie->free	= intTrieFree;
1835 	trie->get	= intTrieGet;
1836 
1837 	/* Now we seed the root node with the index being the
1838 	 * highest left most bit we want to test, which limits the
1839 	 * keys in the trie. This is the trie 'depth'. The limit for
1840 	 * this implementation is 63 (bits 0..63).
1841 	 */
1842 	trie->root->bitNum = depth;
1843 
1844 	/* And as we have nothing in here yet, we set both child pointers
1845 	 * of the root node to point back to itself.
1846 	 */
1847 	trie->root->leftN	= trie->root;
1848 	trie->root->rightN	= trie->root;
1849 	trie->count			= 0;
1850 
1851 	/* Finally, note that the key for this root node is 0 because
1852 	 * we use calloc() to initialise it.
1853 	 */
1854 
1855 	return trie;
1856 }
1857 
1858 /** Search the int Trie and return a pointer to the first bucket indexed
1859  *  by the key if it is contained in the trie, otherwise NULL.
1860  */
1861 static	pANTLR3_TRIE_ENTRY
intTrieGet(pANTLR3_INT_TRIE trie,ANTLR3_INTKEY key)1862 intTrieGet	(pANTLR3_INT_TRIE trie, ANTLR3_INTKEY key)
1863 {
1864 	pANTLR3_INT_TRIE_NODE    thisNode;
1865 	pANTLR3_INT_TRIE_NODE    nextNode;
1866 
1867 	if (trie->count == 0)
1868 	{
1869 		return NULL;	    /* Nothing in this trie yet	*/
1870 	}
1871 	/* Starting at the root node in the trie, compare the bit index
1872 	 * of the current node with its next child node (starts left from root).
1873 	 * When the bit index of the child node is greater than the bit index of the current node
1874 	 * then by definition (as the bit index decreases as we descent the trie)
1875 	 * we have reached a 'backward' pointer. A backward pointer means we
1876 	 * have reached the only node that can be reached by the bits given us so far
1877 	 * and it must either be the key we are looking for, or if not then it
1878 	 * means the entry was not in the trie, and we return NULL. A backward pointer
1879 	 * points back in to the tree structure rather than down (deeper) within the
1880 	 * tree branches.
1881 	 */
1882 	thisNode	= trie->root;		/* Start at the root node		*/
1883 	nextNode	= thisNode->leftN;	/* Examine the left node from the root	*/
1884 
1885 	/* While we are descending the tree nodes...
1886 	 */
1887 	while (thisNode->bitNum > nextNode->bitNum)
1888 	{
1889 		/* Next node now becomes the new 'current' node
1890 		 */
1891 		thisNode    = nextNode;
1892 
1893 		/* We now test the bit indicated by the bitmap in the next node
1894 		 * in the key we are searching for. The new next node is the
1895 		 * right node if that bit is set and the left node it is not.
1896 		 */
1897 		if (key & bitMask[nextNode->bitNum])
1898 		{
1899 			nextNode = nextNode->rightN;	/* 1 is right	*/
1900 		}
1901 		else
1902 		{
1903 			nextNode = nextNode->leftN;		/* 0 is left	*/
1904 		}
1905 	}
1906 
1907 	/* Here we have reached a node where the bitMap index is lower than
1908 	 * its parent. This means it is pointing backward in the tree and
1909 	 * must therefore be a terminal node, being the only point than can
1910 	 * be reached with the bits seen so far. It is either the actual key
1911 	 * we wanted, or if that key is not in the trie it is another key
1912 	 * that is currently the only one that can be reached by those bits.
1913 	 * That situation would obviously change if the key was to be added
1914 	 * to the trie.
1915 	 *
1916 	 * Hence it only remains to test whether this is actually the key or not.
1917 	 */
1918 	if (nextNode->key == key)
1919 	{
1920 		/* This was the key, so return the entry pointer
1921 		 */
1922 		return	nextNode->buckets;
1923 	}
1924 	else
1925 	{
1926 		return	NULL;	/* That key is not in the trie (note that we set the pointer to -1 if no payload) */
1927 	}
1928 }
1929 
1930 
1931 static	ANTLR3_BOOLEAN
intTrieDel(pANTLR3_INT_TRIE trie,ANTLR3_INTKEY key)1932 intTrieDel	(pANTLR3_INT_TRIE trie, ANTLR3_INTKEY key)
1933 {
1934     pANTLR3_INT_TRIE_NODE   p;
1935 
1936     p=trie->root;
1937 
1938     return ANTLR3_FALSE;
1939 }
1940 
1941 /** Add an entry into the INT trie.
1942  *  Basically we descend the trie as we do when searching it, which will
1943  *  locate the only node in the trie that can be reached by the bit pattern of the
1944  *  key. If the key is actually at that node, then if the trie accepts duplicates
1945  *  we add the supplied data in a new chained bucket to that data node. If it does
1946  *  not accept duplicates then we merely return FALSE in case the caller wants to know
1947  *  whether the key was already in the trie.
1948  *  If the node we locate is not the key we are looking to add, then we insert a new node
1949  *  into the trie with a bit index of the leftmost differing bit and the left or right
1950  *  node pointing to itself or the data node we are inserting 'before'.
1951  */
1952 static	ANTLR3_BOOLEAN
intTrieAdd(pANTLR3_INT_TRIE trie,ANTLR3_INTKEY key,ANTLR3_UINT32 type,ANTLR3_INTKEY intVal,void * data,void (ANTLR3_CDECL * freeptr)(void *))1953 intTrieAdd	(pANTLR3_INT_TRIE trie, ANTLR3_INTKEY key, ANTLR3_UINT32 type, ANTLR3_INTKEY intVal, void * data, void (ANTLR3_CDECL *freeptr)(void *))
1954 {
1955 	pANTLR3_INT_TRIE_NODE   thisNode;
1956 	pANTLR3_INT_TRIE_NODE   nextNode;
1957 	pANTLR3_INT_TRIE_NODE   entNode;
1958 	ANTLR3_UINT32			depth;
1959 	pANTLR3_TRIE_ENTRY	    newEnt;
1960 	pANTLR3_TRIE_ENTRY	    nextEnt;
1961 	ANTLR3_INTKEY		    xorKey;
1962 
1963 	/* Cache the bit depth of this trie, which is always the highest index,
1964 	 * which is in the root node
1965 	 */
1966 	depth   = trie->root->bitNum;
1967 
1968 	thisNode	= trie->root;		/* Start with the root node	    */
1969 	nextNode	= trie->root->leftN;	/* And assume we start to the left  */
1970 
1971 	/* Now find the only node that can be currently reached by the bits in the
1972 	 * key we are being asked to insert.
1973 	 */
1974 	while (thisNode->bitNum  > nextNode->bitNum)
1975 	{
1976 		/* Still descending the structure, next node becomes current.
1977 		 */
1978 		thisNode = nextNode;
1979 
1980 		if (key & bitMask[nextNode->bitNum])
1981 		{
1982 			/* Bit at the required index was 1, so travers the right node from here
1983 			 */
1984 			nextNode = nextNode->rightN;
1985 		}
1986 		else
1987 		{
1988 			/* Bit at the required index was 0, so we traverse to the left
1989 			 */
1990 			nextNode = nextNode->leftN;
1991 		}
1992 	}
1993 	/* Here we have located the only node that can be reached by the
1994 	 * bits in the requested key. It could in fact be that key or the node
1995 	 * we need to use to insert the new key.
1996 	 */
1997 	if (nextNode->key == key)
1998 	{
1999 		/* We have located an exact match, but we will only append to the bucket chain
2000 		 * if this trie accepts duplicate keys.
2001 		 */
2002 		if (trie->allowDups ==ANTLR3_TRUE)
2003 		{
2004 			/* Yes, we are accepting duplicates
2005 			 */
2006 			newEnt = (pANTLR3_TRIE_ENTRY)ANTLR3_CALLOC(1, sizeof(ANTLR3_TRIE_ENTRY));
2007 
2008 			if (newEnt == NULL)
2009 			{
2010 				/* Out of memory, all we can do is return the fact that the insert failed.
2011 				 */
2012 				return	ANTLR3_FALSE;
2013 			}
2014 
2015 			/* Otherwise insert this in the chain
2016 			*/
2017 			newEnt->type	= type;
2018 			newEnt->freeptr	= freeptr;
2019 			if (type == ANTLR3_HASH_TYPE_STR)
2020 			{
2021 				newEnt->data.ptr = data;
2022 			}
2023 			else
2024 			{
2025 				newEnt->data.intVal = intVal;
2026 			}
2027 
2028 			/* We want to be able to traverse the stored elements in the order that they were
2029 			 * added as duplicate keys. We might need to revise this opinion if we end up having many duplicate keys
2030 			 * as perhaps reverse order is just as good, so long as it is ordered.
2031 			 */
2032 			nextEnt = nextNode->buckets;
2033 			while (nextEnt->next != NULL)
2034 			{
2035 				nextEnt = nextEnt->next;
2036 			}
2037 			nextEnt->next = newEnt;
2038 
2039 			trie->count++;
2040 			return  ANTLR3_TRUE;
2041 		}
2042 		else
2043 		{
2044 			/* We found the key is already there and we are not allowed duplicates in this
2045 			 * trie.
2046 			 */
2047 			return  ANTLR3_FALSE;
2048 		}
2049 	}
2050 
2051 	/* Here we have discovered the only node that can be reached by the bits in the key
2052 	 * but we have found that this node is not the key we need to insert. We must find the
2053 	 * the leftmost bit by which the current key for that node and the new key we are going
2054 	 * to insert, differ. While this nested series of ifs may look a bit strange, experimentation
2055 	 * showed that it allows a machine code path that works well with predicated execution
2056 	 */
2057 	xorKey = (key ^ nextNode->key);   /* Gives 1 bits only where they differ then we find the left most 1 bit*/
2058 
2059 	/* Most common case is a 32 bit key really
2060 	 */
2061 #ifdef	ANTLR3_USE_64BIT
2062 	if	(xorKey & 0xFFFFFFFF00000000)
2063 	{
2064 		if  (xorKey & 0xFFFF000000000000)
2065 		{
2066 			if	(xorKey & 0xFF00000000000000)
2067 			{
2068 				depth = 56 + bitIndex[((xorKey & 0xFF00000000000000)>>56)];
2069 			}
2070 			else
2071 			{
2072 				depth = 48 + bitIndex[((xorKey & 0x00FF000000000000)>>48)];
2073 			}
2074 		}
2075 		else
2076 		{
2077 			if	(xorKey & 0x0000FF0000000000)
2078 			{
2079 				depth = 40 + bitIndex[((xorKey & 0x0000FF0000000000)>>40)];
2080 			}
2081 			else
2082 			{
2083 				depth = 32 + bitIndex[((xorKey & 0x000000FF00000000)>>32)];
2084 			}
2085 		}
2086 	}
2087 	else
2088 #endif
2089 	{
2090 		if  (xorKey & 0x00000000FFFF0000)
2091 		{
2092 			if	(xorKey & 0x00000000FF000000)
2093 			{
2094 				depth = 24 + bitIndex[((xorKey & 0x00000000FF000000)>>24)];
2095 			}
2096 			else
2097 			{
2098 				depth = 16 + bitIndex[((xorKey & 0x0000000000FF0000)>>16)];
2099 			}
2100 		}
2101 		else
2102 		{
2103 			if	(xorKey & 0x000000000000FF00)
2104 			{
2105 				depth = 8 + bitIndex[((xorKey & 0x0000000000000FF00)>>8)];
2106 			}
2107 			else
2108 			{
2109 				depth = bitIndex[xorKey & 0x00000000000000FF];
2110 			}
2111 		}
2112 	}
2113 
2114     /* We have located the leftmost differing bit, indicated by the depth variable. So, we know what
2115      * bit index we are to insert the new entry at. There are two cases, being where the two keys
2116      * differ at a bit position that is not currently part of the bit testing, where they differ on a bit
2117      * that is currently being skipped in the indexed comparisons, and where they differ on a bit
2118      * that is merely lower down in the current bit search. If the bit index went bit 4, bit 2 and they differ
2119      * at bit 3, then we have the "skipped" bit case. But if that chain was Bit 4, Bit 2 and they differ at bit 1
2120      * then we have the easy bit <pun>.
2121      *
2122      * So, set up to descend the tree again, but this time looking for the insert point
2123      * according to whether we skip the bit that differs or not.
2124      */
2125     thisNode	= trie->root;
2126     entNode	= trie->root->leftN;
2127 
2128     /* Note the slight difference in the checks here to cover both cases
2129      */
2130     while (thisNode->bitNum > entNode->bitNum && entNode->bitNum > depth)
2131     {
2132 	/* Still descending the structure, next node becomes current.
2133 	 */
2134 	thisNode = entNode;
2135 
2136 	if (key & bitMask[entNode->bitNum])
2137 	{
2138 	    /* Bit at the required index was 1, so traverse the right node from here
2139 	     */
2140 	    entNode = entNode->rightN;
2141 	}
2142 	else
2143 	{
2144 	    /* Bit at the required index was 0, so we traverse to the left
2145 	     */
2146 	    entNode = entNode->leftN;
2147 	}
2148     }
2149 
2150     /* We have located the correct insert point for this new key, so we need
2151      * to allocate our entry and insert it etc.
2152      */
2153     nextNode	= (pANTLR3_INT_TRIE_NODE)ANTLR3_CALLOC(1, sizeof(ANTLR3_INT_TRIE_NODE));
2154     if (nextNode == NULL)
2155     {
2156 	/* All that work and no memory - bummer.
2157 	 */
2158 	return	ANTLR3_FALSE;
2159     }
2160 
2161     /* Build a new entry block for the new node
2162      */
2163     newEnt = (pANTLR3_TRIE_ENTRY)ANTLR3_CALLOC(1, sizeof(ANTLR3_TRIE_ENTRY));
2164 
2165     if (newEnt == NULL)
2166     {
2167 	/* Out of memory, all we can do is return the fact that the insert failed.
2168 	 */
2169 	return	ANTLR3_FALSE;
2170     }
2171 
2172     /* Otherwise enter this in our new node
2173     */
2174     newEnt->type	= type;
2175     newEnt->freeptr	= freeptr;
2176     if (type == ANTLR3_HASH_TYPE_STR)
2177     {
2178 	newEnt->data.ptr = data;
2179     }
2180     else
2181     {
2182 	newEnt->data.intVal = intVal;
2183     }
2184     /* Install it
2185      */
2186     nextNode->buckets	= newEnt;
2187     nextNode->key	= key;
2188     nextNode->bitNum	= depth;
2189 
2190     /* Work out the right and left pointers for this new node, which involve
2191      * terminating with the current found node either right or left according
2192      * to whether the current index bit is 1 or 0
2193      */
2194     if (key & bitMask[depth])
2195     {
2196 	nextNode->leftN	    = entNode;	    /* Terminates at previous position	*/
2197 	nextNode->rightN    = nextNode;	    /* Terminates with itself		*/
2198     }
2199     else
2200     {
2201 	nextNode->rightN   = entNode;	    /* Terminates at previous position	*/
2202 	nextNode->leftN    = nextNode;	    /* Terminates with itself		*/
2203     }
2204 
2205     /* Finally, we need to change the pointers at the node we located
2206      * for inserting. If the key bit at its index is set then the right
2207      * pointer for that node becomes the newly created node, otherwise the left
2208      * pointer does.
2209      */
2210     if (key & bitMask[thisNode->bitNum] )
2211     {
2212 	thisNode->rightN    = nextNode;
2213     }
2214     else
2215     {
2216 	thisNode->leftN	    = nextNode;
2217     }
2218 
2219     /* Et voila
2220      */
2221     trie->count++;
2222     return  ANTLR3_TRUE;
2223 
2224 }
2225 /** Release memory allocated to this tree.
2226  *  Basic algorithm is that we do a depth first left descent and free
2227  *  up any nodes that are not backward pointers.
2228  */
2229 static void
freeIntNode(pANTLR3_INT_TRIE_NODE node)2230 freeIntNode(pANTLR3_INT_TRIE_NODE node)
2231 {
2232     pANTLR3_TRIE_ENTRY	thisEntry;
2233     pANTLR3_TRIE_ENTRY	nextEntry;
2234 
2235     /* If this node has a left pointer that is not a back pointer
2236      * then recursively call to free this
2237      */
2238     if (node->bitNum > node->leftN->bitNum)
2239     {
2240 	/* We have a left node that needs descending, so do it.
2241 	 */
2242 	freeIntNode(node->leftN);
2243     }
2244 
2245     /* The left nodes from here should now be dealt with, so
2246      * we need to descend any right nodes that are not back pointers
2247      */
2248     if (node->bitNum > node->rightN->bitNum)
2249     {
2250 	/* There are some right nodes to descend and deal with.
2251 	 */
2252 	freeIntNode(node->rightN);
2253     }
2254 
2255     /* Now all the children are dealt with, we can destroy
2256      * this node too
2257      */
2258     thisEntry	= node->buckets;
2259 
2260     while (thisEntry != NULL)
2261     {
2262 	nextEntry   = thisEntry->next;
2263 
2264 	/* Do we need to call a custom free pointer for this string entry?
2265 	 */
2266 	if (thisEntry->type == ANTLR3_HASH_TYPE_STR && thisEntry->freeptr != NULL)
2267 	{
2268 	    thisEntry->freeptr(thisEntry->data.ptr);
2269 	}
2270 
2271 	/* Now free the data for this bucket entry
2272 	 */
2273 	ANTLR3_FREE(thisEntry);
2274 	thisEntry = nextEntry;	    /* See if there are any more to free    */
2275     }
2276 
2277     /* The bucket entry is now gone, so we can free the memory for
2278      * the entry itself.
2279      */
2280     ANTLR3_FREE(node);
2281 
2282     /* And that should be it for everything under this node and itself
2283      */
2284 }
2285 
2286 /** Called to free all nodes and the structure itself.
2287  */
2288 static	void
intTrieFree(pANTLR3_INT_TRIE trie)2289 intTrieFree	(pANTLR3_INT_TRIE trie)
2290 {
2291     /* Descend from the root and free all the nodes
2292      */
2293     freeIntNode(trie->root);
2294 
2295     /* the nodes are all gone now, so we need only free the memory
2296      * for the structure itself
2297      */
2298     ANTLR3_FREE(trie);
2299 }
2300 
2301 
2302 /**
2303  * Allocate and initialize a new ANTLR3 topological sorter, which can be
2304  * used to define edges that identify numerical node indexes that depend on other
2305  * numerical node indexes, which can then be sorted topologically such that
2306  * any node is sorted after all its dependent nodes.
2307  *
2308  * Use:
2309  *
2310  * /verbatim
2311 
2312   pANTLR3_TOPO topo;
2313   topo = antlr3NewTopo();
2314 
2315   if (topo == NULL) { out of memory }
2316 
2317   topo->addEdge(topo, 3, 0); // Node 3 depends on node 0
2318   topo->addEdge(topo, 0, 1); // Node - depends on node 1
2319   topo->sortVector(topo, myVector); // Sort the vector in place (node numbers are the vector entry numbers)
2320 
2321  * /verbatim
2322  */
2323 ANTLR3_API pANTLR3_TOPO
antlr3TopoNew()2324 antlr3TopoNew()
2325 {
2326     pANTLR3_TOPO topo = (pANTLR3_TOPO)ANTLR3_MALLOC(sizeof(ANTLR3_TOPO));
2327 
2328     if  (topo == NULL)
2329     {
2330         return NULL;
2331     }
2332 
2333     // Initialize variables
2334     //
2335 
2336     topo->visited   = NULL;                 // Don't know how big it is yet
2337     topo->limit     = 1;                    // No edges added yet
2338     topo->edges     = NULL;                 // No edges added yet
2339     topo->sorted    = NULL;                 // Nothing sorted at the start
2340     topo->cycle     = NULL;                 // No cycles at the start
2341     topo->cycleMark = 0;                    // No cycles at the start
2342     topo->hasCycle  = ANTLR3_FALSE;         // No cycle at the start
2343 
2344     // API
2345     //
2346     topo->addEdge       = addEdge;
2347     topo->sortToArray   = sortToArray;
2348     topo->sortVector    = sortVector;
2349     topo->free          = freeTopo;
2350 
2351     return topo;
2352 }
2353 // Topological sorter
2354 //
2355 static  void
addEdge(pANTLR3_TOPO topo,ANTLR3_UINT32 edge,ANTLR3_UINT32 dependency)2356 addEdge          (pANTLR3_TOPO topo, ANTLR3_UINT32 edge, ANTLR3_UINT32 dependency)
2357 {
2358     ANTLR3_UINT32   i;
2359     ANTLR3_UINT32   maxEdge;
2360     pANTLR3_BITSET  edgeDeps;
2361 
2362     if (edge>dependency)
2363     {
2364         maxEdge = edge;
2365     }
2366     else
2367     {
2368         maxEdge = dependency;
2369     }
2370     // We need to add an edge to says that the node indexed by 'edge' is
2371     // dependent on the node indexed by 'dependency'
2372     //
2373 
2374     // First see if we have enough room in the edges array to add the edge?
2375     //
2376     if (topo->edges == NULL)
2377     {
2378         // We don't have any edges yet, so create an array to hold them
2379         //
2380         topo->edges = (pANTLR3_BITSET*)ANTLR3_CALLOC(sizeof(pANTLR3_BITSET) * (maxEdge + 1), 1);
2381         if (topo->edges == NULL)
2382         {
2383             return;
2384         }
2385 
2386         // Set the limit to what we have now
2387         //
2388         topo->limit = maxEdge + 1;
2389     }
2390     else if (topo->limit <= maxEdge)
2391     {
2392         // WE have some edges but not enough
2393         //
2394         topo->edges = (pANTLR3_BITSET*)ANTLR3_REALLOC(topo->edges, sizeof(pANTLR3_BITSET) * (maxEdge + 1));
2395         if (topo->edges == NULL)
2396         {
2397             return;
2398         }
2399 
2400         // Initialize the new bitmaps to ;indicate we have no edges defined yet
2401         //
2402         for (i = topo->limit; i <= maxEdge; i++)
2403         {
2404             *((topo->edges) + i) = NULL;
2405         }
2406 
2407         // Set the limit to what we have now
2408         //
2409         topo->limit = maxEdge + 1;
2410     }
2411 
2412     // If the edge was flagged as depending on itself, then we just
2413     // do nothing as it means this routine was just called to add it
2414     // in to the list of nodes.
2415     //
2416     if  (edge == dependency)
2417     {
2418         return;
2419     }
2420 
2421     // Pick up the bit map for the requested edge
2422     //
2423     edgeDeps = *((topo->edges) + edge);
2424 
2425     if  (edgeDeps == NULL)
2426     {
2427         // No edges are defined yet for this node
2428         //
2429         edgeDeps                = antlr3BitsetNew(0);
2430         *((topo->edges) + edge) = edgeDeps;
2431         if (edgeDeps == NULL )
2432         {
2433             return;  // Out of memory
2434         }
2435     }
2436 
2437     // Set the bit in the bitmap that corresponds to the requested
2438     // dependency.
2439     //
2440     edgeDeps->add(edgeDeps, dependency);
2441 
2442     // And we are all set
2443     //
2444     return;
2445 }
2446 
2447 
2448 /**
2449  * Given a starting node, descend its dependent nodes (ones that it has edges
2450  * to) until we find one without edges. Having found a node without edges, we have
2451  * discovered the bottom of a depth first search, which we can then ascend, adding
2452  * the nodes in order from the bottom, which gives us the dependency order.
2453  */
2454 static void
DFS(pANTLR3_TOPO topo,ANTLR3_UINT32 node)2455 DFS(pANTLR3_TOPO topo, ANTLR3_UINT32 node)
2456 {
2457     pANTLR3_BITSET edges;
2458 
2459     // Guard against a revisit and check for cycles
2460     //
2461     if  (topo->hasCycle == ANTLR3_TRUE)
2462     {
2463         return; // We don't do anything else if we found a cycle
2464     }
2465 
2466     if  (topo->visited->isMember(topo->visited, node))
2467     {
2468         // Check to see if we found a cycle. To do this we search the
2469         // current cycle stack and see if we find this node already in the stack.
2470         //
2471         ANTLR3_UINT32   i;
2472 
2473         for (i=0; i<topo->cycleMark; i++)
2474         {
2475             if  (topo->cycle[i] == node)
2476             {
2477                 // Stop! We found a cycle in the input, so rejig the cycle
2478                 // stack so that it only contains the cycle and set the cycle flag
2479                 // which will tell the caller what happened
2480                 //
2481                 ANTLR3_UINT32 l;
2482 
2483                 for (l = i; l < topo->cycleMark; l++)
2484                 {
2485                     topo->cycle[l - i] = topo->cycle[l];    // Move to zero base in the cycle list
2486                 }
2487 
2488                 // Recalculate the limit
2489                 //
2490                 topo->cycleMark -= i;
2491 
2492                 // Signal disaster
2493                 //
2494                 topo->hasCycle = ANTLR3_TRUE;
2495             }
2496         }
2497         return;
2498     }
2499 
2500     // So far, no cycles have been found and we have not visited this node yet,
2501     // so this node needs to go into the cycle stack before we continue
2502     // then we will take it out of the stack once we have descended all its
2503     // dependencies.
2504     //
2505     topo->cycle[topo->cycleMark++] = node;
2506 
2507     // First flag that we have visited this node
2508     //
2509     topo->visited->add(topo->visited, node);
2510 
2511     // Now, if this node has edges, then we want to ensure we visit
2512     // them all before we drop through and add this node into the sorted
2513     // list.
2514     //
2515     edges = *((topo->edges) + node);
2516     if  (edges != NULL)
2517     {
2518         // We have some edges, so visit each of the edge nodes
2519         // that have not already been visited.
2520         //
2521         ANTLR3_UINT32   numBits;	    // How many bits are in the set
2522         ANTLR3_UINT32   i;
2523         ANTLR3_UINT32   range;
2524 
2525         numBits = edges->numBits(edges);
2526         range   = edges->size(edges);   // Number of set bits
2527 
2528         // Stop if we exahust the bit list or have checked the
2529         // number of edges that this node refers to (so we don't
2530         // check bits at the end that cannot possibly be set).
2531         //
2532         for (i=0; i<= numBits && range > 0; i++)
2533         {
2534             if  (edges->isMember(edges, i))
2535             {
2536                 range--;        // About to check another one
2537 
2538                 // Found an edge, make sure we visit and descend it
2539                 //
2540                 DFS(topo, i);
2541             }
2542         }
2543     }
2544 
2545     // At this point we will have visited all the dependencies
2546     // of this node and they will be ordered (even if there are cycles)
2547     // So we just add the node into the sorted list at the
2548     // current index position.
2549     //
2550     topo->sorted[topo->limit++] = node;
2551 
2552     // Remove this node from the cycle list if we have not detected a cycle
2553     //
2554     if  (topo->hasCycle == ANTLR3_FALSE)
2555     {
2556         topo->cycleMark--;
2557     }
2558 
2559     return;
2560 }
2561 
2562 static  pANTLR3_UINT32
sortToArray(pANTLR3_TOPO topo)2563 sortToArray      (pANTLR3_TOPO topo)
2564 {
2565     ANTLR3_UINT32 v;
2566     ANTLR3_UINT32 oldLimit;
2567 
2568     // Guard against being called with no edges defined
2569     //
2570     if  (topo->edges == NULL)
2571     {
2572         return NULL;
2573     }
2574     // First we need a vector to populate with enough
2575     // entries to accommodate the sorted list and another to accommodate
2576     // the maximum cycle we could detect which is all nodes such as 0->1->2->3->0
2577     //
2578     topo->sorted    = (pANTLR3_UINT32)ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
2579 	if (topo->sorted == NULL)
2580 	{
2581 		return NULL;
2582 	}
2583     topo->cycle     = (pANTLR3_UINT32)ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
2584 	if (topo->cycle == NULL)
2585 	{
2586 		return NULL;
2587 	}
2588 
2589     // Next we need an empty bitset to show whether we have visited a node
2590     // or not. This is the bit that gives us linear time of course as we are essentially
2591     // dropping through the nodes in depth first order and when we get to a node that
2592     // has no edges, we pop back up the stack adding the nodes we traversed in reverse
2593     // order.
2594     //
2595     topo->visited   = antlr3BitsetNew(0);
2596 
2597     // Now traverse the nodes as if we were just going left to right, but
2598     // then descend each node unless it has already been visited.
2599     //
2600     oldLimit    = topo->limit;     // Number of nodes to traverse linearly
2601     topo->limit = 0;               // Next entry in the sorted table
2602 
2603     for (v = 0; v < oldLimit; v++)
2604     {
2605         // If we did not already visit this node, then descend it until we
2606         // get a node without edges or arrive at a node we have already visited.
2607         //
2608         if  (topo->visited->isMember(topo->visited, v) == ANTLR3_FALSE)
2609         {
2610             // We have not visited this one so descend it
2611             //
2612             DFS(topo, v);
2613         }
2614 
2615         // Break the loop if we detect a cycle as we have no need to go any
2616         // further
2617         //
2618         if  (topo->hasCycle == ANTLR3_TRUE)
2619         {
2620             break;
2621         }
2622     }
2623 
2624     // Reset the limit to the number we recorded as if we hit a
2625     // cycle, then limit will have stopped at the node where we
2626     // discovered the cycle, but in order to free the edge bitmaps
2627     // we need to know how many we may have allocated and traverse them all.
2628     //
2629     topo->limit = oldLimit;
2630 
2631     // Having traversed all the nodes we were given, we
2632     // are guaranteed to have ordered all the nodes or detected a
2633     // cycle.
2634     //
2635     return topo->sorted;
2636 }
2637 
2638 static  void
sortVector(pANTLR3_TOPO topo,pANTLR3_VECTOR v)2639 sortVector       (pANTLR3_TOPO topo, pANTLR3_VECTOR v)
2640 {
2641     // To sort a vector, we first perform the
2642     // sort to an array, then use the results to reorder the vector
2643     // we are given. This is just a convenience routine that allows you to
2644     // sort the children of a tree node into topological order before or
2645     // during an AST walk. This can be useful for optimizations that require
2646     // dag reorders and also when the input stream defines things that are
2647     // interdependent and you want to walk the list of the generated trees
2648     // for those things in topological order so you can ignore the interdependencies
2649     // at that point.
2650     //
2651     ANTLR3_UINT32 i;
2652 
2653     // Used as a lookup index to find the current location in the vector of
2654     // the vector entry that was originally at position [0], [1], [2] etc
2655     //
2656     pANTLR3_UINT32  vIndex;
2657 
2658     // Sort into an array, then we can use the array that is
2659     // stored in the topo
2660     //
2661     if  (topo->sortToArray(topo) == 0)
2662     {
2663         return;     // There were no edges
2664     }
2665 
2666     if  (topo->hasCycle == ANTLR3_TRUE)
2667     {
2668         return;  // Do nothing if we detected a cycle
2669     }
2670 
2671     // Ensure that the vector we are sorting is at least as big as the
2672     // the input sequence we were asked to sort. It does not matter if it is
2673     // bigger as that probably just means that nodes numbered higher than the
2674     // limit had no dependencies and so can be left alone.
2675     //
2676     if  (topo->limit > v->count)
2677     {
2678         // We can only sort the entries that we have dude! The caller is
2679         // responsible for ensuring the vector is the correct one and is the
2680         // correct size etc.
2681         //
2682         topo->limit = v->count;
2683     }
2684     // We need to know the locations of each of the entries
2685     // in the vector as we don't want to duplicate them in a new vector. We
2686     // just use an indirection table to get the vector entry for a particular sequence
2687     // according to where we moved it last. Then we can just swap vector entries until
2688     // we are done :-)
2689     //
2690     vIndex = (pANTLR3_UINT32)ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
2691 	if (vIndex == NULL)
2692 	{
2693 		// malloc failed
2694 		return;
2695 	}
2696 
2697     // Start index, each vector entry is located where you think it is
2698     //
2699     for (i = 0; i < topo->limit; i++)
2700     {
2701         vIndex[i] = i;
2702     }
2703 
2704     // Now we traverse the sorted array and moved the entries of
2705     // the vector around according to the sort order and the indirection
2706     // table we just created. The index telsl us where in the vector the
2707     // original element entry n is now located via vIndex[n].
2708     //
2709     for (i=0; i < topo->limit; i++)
2710     {
2711         ANTLR3_UINT32   ind;
2712 
2713         // If the vector entry at i is already the one that it
2714         // should be, then we skip moving it of course.
2715         //
2716         if  (vIndex[topo->sorted[i]] == i)
2717         {
2718             continue;
2719         }
2720 
2721         // The vector entry at i, should be replaced with the
2722         // vector entry indicated by topo->sorted[i]. The vector entry
2723         // at topo->sorted[i] may have already been swapped out though, so we
2724         // find where it is now and move it from there to i.
2725         //
2726         ind     = vIndex[topo->sorted[i]];
2727         v->swap(v, i, ind);
2728 
2729         // Update our index. The element at i is now the one we wanted
2730         // to be sorted here and the element we swapped out is now the
2731         // element that was at i just before we swapped it. If you are lost now
2732         // don't worry about it, we are just reindexing on the fly is all.
2733         //
2734         vIndex[topo->sorted[i]] = i;
2735         vIndex[i] = ind;
2736     }
2737 
2738     // Having traversed all the entries, we have sorted the vector in place.
2739     //
2740     ANTLR3_FREE(vIndex);
2741     return;
2742 }
2743 
2744 static  void
freeTopo(pANTLR3_TOPO topo)2745 freeTopo             (pANTLR3_TOPO topo)
2746 {
2747     ANTLR3_UINT32   i;
2748 
2749     // Free the result vector
2750     //
2751     if  (topo->sorted != NULL)
2752     {
2753         ANTLR3_FREE(topo->sorted);
2754         topo->sorted = NULL;
2755     }
2756 
2757     // Free the visited map
2758     //
2759     if  (topo->visited != NULL)
2760     {
2761 
2762         topo->visited->free(topo->visited);
2763         topo->visited = NULL;
2764     }
2765 
2766     // Free any edgemaps
2767     //
2768     if  (topo->edges != NULL)
2769     {
2770         pANTLR3_BITSET edgeList;
2771 
2772 
2773         for (i=0; i<topo->limit; i++)
2774         {
2775             edgeList = *((topo->edges) + i);
2776             if  (edgeList != NULL)
2777             {
2778                 edgeList->free(edgeList);
2779             }
2780         }
2781 
2782         ANTLR3_FREE(topo->edges);
2783     }
2784     topo->edges = NULL;
2785 
2786     // Free any cycle map
2787     //
2788     if  (topo->cycle != NULL)
2789     {
2790         ANTLR3_FREE(topo->cycle);
2791     }
2792 
2793     ANTLR3_FREE(topo);
2794 }
2795