Example #1
0
int main(int argc, char *argv[]) {

	HashTable ht = newHashTable(65535);
	
	HashTable_put(ht, "1", "two");
	HashTable_put(ht, "2", "three");
	HashTable_put(ht, "3", "five");
	HashTable_put(ht, "4", "seven");
	HashTable_put(ht, "5", "eleven");
	HashTable_put(ht, "6", "thirteen");
	HashTable_put(ht, "7", "seventeen");

	HashTable_remove(ht, "1");
	HashTable_remove(ht, "2");
	HashTable_remove(ht, "6");
	HashTable_remove(ht, "7");

	HashTable_put(ht, "3", "not allowed");

	printf("%s\n", HashTable_get(ht, "1"));
	printf("%s\n", HashTable_get(ht, "2"));
	printf("%s\n", HashTable_get(ht, "3"));
	printf("%s\n", HashTable_get(ht, "4"));
	printf("%s\n", HashTable_get(ht, "5"));
	printf("%s\n", HashTable_get(ht, "6"));
	printf("%s\n", HashTable_get(ht, "7"));

	printf("size: %d\n", HashTable_size(ht));	

	freeHashTable(&ht);

	return 0;
}
Example #2
0
int main(int argc, char **argv)
{
    int i;

    struct Hashtable hash_table;
    //Allocate memory for a new hash table
    newHashTable(&hash_table, HASHTABLE_LENGTH);
    printf("New hash table containing no values\n");
    //Print the hash table containing no values
    for(i=0;i<HASHTABLE_LENGTH;i++){
        print_ll(&(hash_table.table[i]));
    }
    putchar('\n');
    //Insert several values into the hash table
    insert(&hash_table, "Hello World");
    insert(&hash_table, "Hello World");
    insert(&hash_table, "Hel World");
    insert(&hash_table, "GoodBye");
    insert(&hash_table, "GoodBye");
    insert(&hash_table, "wangbang");
    insert(&hash_table, "Holachola");
    insert(&hash_table, "antidis");

    printf("Test values inserted printing full hash_table...\n");
    //Print the list again 
    for(i=0;i<HASHTABLE_LENGTH;i++){
        print_ll(&(hash_table.table[i]));
    }
    //Deallocate memory
    freeHashTable(&hash_table);
}
Example #3
0
void test_phase4(void){
	struct pptoken *token;
	struct list *source;
	struct list *p1;
	struct list *p2;
	struct list *p3;
	struct list *p4;
	struct hash_table *macros;

	//source = sourceCharsFromFile("tests/trigraphs.c");
	//source = sourceCharsFromFile("tests/doubledefine.c");
	//source = sourceCharsFromFile("tests/recursivedefine.c");
	source = sourceCharsFromFile("tests/functionmacro.c");
	p1 = phase1(source);
	p2 = phase2(p1);
	p3 = phase3(p2);

	macros = newHashTable();
	assert(macros != NULL);

	p4 = phase4(macros, p3);

	while(listDequeue(p4, (void**)&token) == 0){
		fputs(token->whiteSpace, stdout);
		if(token->name != PPTN_EOF){
			putchar('{');
			printf("\033[35m");
			fputs(token->lexeme, stdout);
			printf("\033[39m");
			putchar('}');
		} else {
			break;
		}
	}
}
Example #4
0
int main(void){
    //initialize stuff
    init_zobrist();
    srand(time(NULL));
    //create a new board
    Board_t* goal = newBoard();
    //create a new visited cache
    HashTable_t* visited = newHashTable(32);
    //create a cloned state of the board and scrable it
    Board_t* scrabled = cloneBoard(goal);
    scramble_times(scrabled, TIMES_TO_SCRAMBLE);

    printf("Starting search...\n");
    SearchNode_t* root = newSearchNode(scrabled, 0, NULL);
    SearchNode_t* result = idf_search(root, goal, visited, 30);

    //print out the search
    if(result!=NULL){
        printf("Search Path:\n");
        printSearchNode(result);
    }
    else
        printf("Search failed.\n");

    //clean up
    deleteSearchNode(root, visited);
    assert(TOTAL_SEARCH_NODES==0);
    assert(TOTAL_HASH_NODES==0);
    deleteHashTable(visited);
    deleteBoard(goal);
    return 0;
}
 vector<ListNode*> rehashing(vector<ListNode*> hashTable) {
     int cap = hashTable.size();
     vector<ListNode*> newHashTable(cap * 2);
     map<int, ListNode*> tailMapper;
     
     for (int i = 0; i < cap; i ++) {
         if (hashTable[i] != NULL) {
             ListNode *cur = hashTable[i];
             while (cur) {
                 int code = hash(cur->val, cap * 2);
                 ListNode *newNode = new ListNode(cur->val);
                 if (newHashTable[code]) {
                     tailMapper[code]->next = newNode;
                 } else {
                     newHashTable[code] = newNode;
                 }
                 
                 tailMapper[code] = newNode;
                 cur = cur->next;
             }
         }
     }
     
     return newHashTable;
 }
Example #6
0
void test_phase4(void){
	struct phase1 p1;
	struct phase2 p2;
	struct phase3 p3;
	struct phase4 p4;
	struct pptoken token;

	//p1.sourceFile = fopen("phase3.c", "r");
	//p1.sourceFile = fopen("tests/defines.c", "r");
	p1.sourceFile = fopen("tests/define.c", "r");
	phase1Init(&p1);

	p2.p1 = &p1;
	phase2Init(&p2);

	p3.p2 = &p2;
	phase3Init(&p3);

	p4.p3 = &p3;
	p4.symbolTable = newHashTable();
	phase4Init(&p4);

	token = phase4NextToken(&p4);
	while(token.name != PPTN_EOF){
		printf("%s", token.whiteSpace);
		printf("%s", token.lexeme);
		token = phase4NextToken(&p4);
	}
}
/**************************************************************************
 * public functions
 **************************************************************************/
int
initPreload (preloadConfig_t *preloadConfig, rodsEnv *myPreloadRodsEnv, rodsArguments_t *myPreloadRodsArgs) {
    rodsLog (LOG_DEBUG, "initPreload: MyPreloadConfig.preload = %d", preloadConfig->preload);
    rodsLog (LOG_DEBUG, "initPreload: MyPreloadConfig.clearCache = %d", preloadConfig->clearCache);
    rodsLog (LOG_DEBUG, "initPreload: MyPreloadConfig.cachePath = %s", preloadConfig->cachePath);
    rodsLog (LOG_DEBUG, "initPreload: MyPreloadConfig.cacheMaxSize = %lld", preloadConfig->cacheMaxSize);
    rodsLog (LOG_DEBUG, "initPreload: MyPreloadConfig.preloadMinSize = %lld", preloadConfig->preloadMinSize);
    rodsLog (LOG_DEBUG, "initPreload: empty space = %lld", getEmptypSpace(preloadConfig->cachePath));

    // copy given configuration
    memcpy(&PreloadConfig, preloadConfig, sizeof(preloadConfig_t));
    PreloadRodsEnv = myPreloadRodsEnv;
    PreloadRodsArgs = myPreloadRodsArgs;

    // init hashtables
    PreloadThreadTable = newHashTable(NUM_PRELOAD_THREAD_HASH_SLOT);
    PreloadFileHandleTable = newHashTable(NUM_PRELOAD_FILEHANDLE_HASH_SLOT);

    // init lists
    PreloadThreadList = newConcurrentList();

    // init lock
    INIT_LOCK(PreloadLock);

    _preparePreloadCacheDir(preloadConfig->cachePath);

    if(preloadConfig->clearCache) {
        // clear all cache
        _removeAllCaches();
    } else {
        // remove incomplete preload caches
        _removeAllIncompleteCaches();
    }

    return (0);
}
Example #8
0
int main() {
    int capacity = 11, i;
    HashTablePtr t = newHashTable(capacity, hashInt, compare);
    HashNodePtr node;
    putIntoHashTable(t, 1, 1);
    putIntoHashTable(t, 2, 2);
    putIntoHashTable(t, 3, 3);
    putIntoHashTable(t, 4, 4);
    putIntoHashTable(t, 5, 5);
    printHashTable(t);
    for(i = 0; i <= 5; i++) {
        HashNodePtr node = getFromHashTable(t, i);
        if(node) {
            printf("key %d values %d\n", node->key, node->value);
        } else {
            printf("cann't find key %d\n", i);
        }
    }
    for(i = 11; i <= 16; i++) {
        HashNodePtr node = getFromHashTable(t, i);
        if(node) {
            printf("key %d values %d\n", node->key, node->value);
        } else {
            printf("cann't find key %d\n", i);
        }
    }
    removeFromHashTable(t, 2);
    removeFromHashTable(t, 3);
    printHashTable(t);
    putIntoHashTable(t, 2, 2);
    putIntoHashTable(t, 13, 13);
    putIntoHashTable(t, 24, 24);
    printHashTable(t);
    removeFromHashTable(t, 2);
    printHashTable(t);
    node = getFromHashTable(t, 13);
    printf("key %d values %d\n", node->key, node->value);
    node = getFromHashTable(t, 24);
    printf("key %d values %d\n", node->key, node->value);
    putIntoHashTable(t, 35, 35);
    printHashTable(t);
    freeHashTable(t);
    return 0;
}
Example #9
0
void 
hTabAddItemLong (hTab ** htab, int key, void *pkey, void *item)
{
  hashtItem *htip;
  hashtItem *last;

  if (!(*htab))
    *htab = newHashTable (DEFAULT_HTAB_SIZE);

  if (key > (*htab)->size)
    {
      int i;
      (*htab)->table = Safe_realloc ((*htab)->table,
				     (key * 2 + 2) * sizeof (hashtItem *));
      for (i = (*htab)->size + 1; i <= (key * 2 + 1); i++)
	(*htab)->table[i] = NULL;
      (*htab)->size = key * 2 + 1;
    }

  /* update the key */
  if ((*htab)->maxKey < key)
    (*htab)->maxKey = key;

  if ((*htab)->minKey > key)
    (*htab)->minKey = key;

  /* create the item */
  htip = _newHashtItem (key, pkey, item);

  /* if there is a clash then goto end of chain */
  if ((last = (*htab)->table[key]))
    {
      while (last->next)
	last = last->next;
      last->next = htip;
    }
  else
    /* else just add it */
    (*htab)->table[key] = htip;
  (*htab)->nItems++;
}
Example #10
0
File: hashtable.c Project: HJvT/hat
void
rehash(HashTable* h)
{
  if (h->outOfMemory==0) {
    HashTable* h2 = newHashTable(h->size+h->incrementSize);
    HashElement *e,*l;
    unsigned long sz,hash,i=0;
    
    if (h2==NULL) {
      h->outOfMemory=1;
    } else {
      sz=h2->size;
      // make increment of new table same as old
      h2->incrementSize=h->incrementSize;
      while (i<h->size) {
	l = h->hashArray[i];   // get list from old hash table
	h->hashArray[i]=NULL;
	while (l!=NULL) {      // process every entry from old list 
	  e = l;               // process first list element
	  l = l->next;         // get the tail of the list
          // hash value for entry to be processed
	  hash = ((unsigned long) e->value) % sz;
	  e->next = h2->hashArray[hash]; // append entries to new list
	  h2->hashArray[hash]=e;         // set list in new hash table
	}
	i++;
      }
      // swap old and new hash table (to keep pointers to old table valid!)
      l=(HashElement*) h->hashArray;
      // move new hashArray to old hashTable
      h->hashArray = h2->hashArray;
      // set temporary hashTable to old hashArray
      h2->hashArray= (HashElement**)l;
      h2->size = h->size;           // set temporary hashTable size to old size
      h->size = sz;                 // set hash table size to new size
      h->rehashAt = h->size-(h->size/10); // set new rehash size: 90%
      // get rid of temporary table, now holding old hashArray
      freeHashTable(h2);
    }
  }
}
Example #11
0
/*-----------------------------------------------------------------*/
hTab *
hTabFromTable (hTab * htab)
{
  hTab *nhtab;
  hashtItem *htip;
  int key;

  if (!htab)
    return NULL;

  nhtab = newHashTable (htab->size);

  for (key = htab->minKey; key <= htab->maxKey; key++)
    {

      for (htip = htab->table[key]; htip; htip = htip->next)
	hTabAddItem (&nhtab, htip->key, htip->item);
    }

  return nhtab;
}
Example #12
0
void initMe(void)
{

	symbolTable = newHashTable(SYMBOL_TABLE_SIZE);
}
Example #13
0
/*
 * Restore a Cache struct from buf into a malloc'd buffer.
 * This function returns NULL if failed to acquire or release the mutex.
 * It first create a local copy of buf's data section and pointer pointers section. This part needs synchronization.
 * Then it works on its local copy, which does not need synchronization.
 */
Cache *restoreCache( const char* _inst_name ) {
    mutex_type *mutex;
    lockReadMutex(_inst_name, &mutex);
    unsigned char *buf = prepareNonServerSharedMemory( _inst_name );
    if (buf == NULL) {
        return NULL;
    }
    Cache *cache = ( Cache * ) buf;
    unsigned char *bufCopy;
    unsigned char *pointers;
    size_t pointersSize;
    unsigned char *bufMapped;

    unsigned char *pointersCopy;
    unsigned char *pointersMapped;
    size_t dataSize;
    dataSize = cache->dataSize;
    bufCopy = ( unsigned char * )malloc( dataSize );
    if ( bufCopy == NULL ) {
        rodsLog( LOG_ERROR, "Cannot allocate object buffer of size %lld" , dataSize);
        unlockReadMutex(_inst_name, &mutex);
        return NULL;
    }
    memcpy( bufCopy, buf, cache->dataSize );
    Cache *cacheCopy = ( Cache * ) bufCopy;
    pointersMapped = cacheCopy->pointers;
    bufMapped = cacheCopy->address;
    pointersSize = bufMapped + SHMMAX - pointersMapped;
    pointersCopy = ( unsigned char * )malloc( pointersSize );
    if ( pointersCopy == NULL ) {
        free( bufCopy );
        rodsLog( LOG_ERROR, "Cannot allocate pointer pointer buffer of size %lld", pointersSize);
        detachSharedMemory( _inst_name );
        unlockReadMutex(_inst_name, &mutex);
        return NULL;
    }
    memcpy( pointersCopy, pointersMapped + ( buf - bufMapped ), pointersSize );
    detachSharedMemory( _inst_name );
    unlockReadMutex(_inst_name, &mutex);
    pointers = pointersCopy;
    /*    bufCopy = (unsigned char *)malloc(cache->dataSize);

        if(bufCopy == NULL) {
            return NULL;
        }
        memcpy(bufCopy, buf, cache->dataSize);

        bufMapped = cache->address;

        long diffBuf = buf - bufMapped;
        pointers = cache->pointers + diffBuf;
        pointersSize = pointers - buf; */
    long diff = bufCopy - bufMapped;
    long pointerDiff = diff;
    applyDiff( pointers, pointersSize, diff, pointerDiff );
    free( pointersCopy );

#ifdef RE_CACHE_CHECK
    Hashtable *objectMap = newHashTable( 100 );
    cacheChkEnv( cacheCopy->coreFuncDescIndex, cacheCopy, ( CacheChkFuncType * ) cacheChkNode, objectMap );
    cacheChkRuleSet( cacheCopy->coreRuleSet, cacheCopy, objectMap );
#endif
    return cacheCopy;
}
Example #14
0
/* Copy the data stored in a Cache struct into a continuously allocated memory block in *p.
 * All sub structure status are either uninitialized or compressed, which meaning that they are not allocated separately and therefore should not be deallocated.
 * Only coreRuleSet and coreFuncDescIndex are copied.
 * Starting from *p+size backwards, a list of pointers to pointers in the copied data structures are stored.
 * There pointers are used to quickly access all pointers in the stored data structures so that they can be offset when they are copied to a new memory address.
 * This function returns NULL if it runs out of memory allocated between in *p and *p+size.
 * The rule engine status is also set to uninitialized. */
Cache *copyCache( unsigned char **p, size_t size, Cache *ptr ) {
    /* size should be large enough and divisible by ALIGNMENT */
    if (size < DEFAULT_BLOCK_SIZE || 0 != size % REGION_ALIGNMENT) {
        return NULL;
    }

    unsigned char *buf = *p;
    unsigned char *pointers0 = buf + size;

    /* shared objects */
    unsigned char **pointers = &pointers0;
    int generatePtrDesc = 1;

    allocateInBuffer( Cache, ecopy, ptr );

    MK_POINTER( &( ecopy->address ) );
    MK_POINTER( &( ecopy->pointers ) );

    // objectMap will use a hash table size that is twice the number of objects being held (to favor speed).
    // Example: The shared memory region has a size of SHMMAX (see shared_memory.hpp). SHMMAX == 30000000.
    // The upper bound of the passed-in size is the shared memory region size.
    // With an average compiled object size of 75 bytes (taken over sample of 9000 lines of rule code), SHMMAX / 75 = 400000 objects.
    // The maximum size of the hash table should be twice the objects that can fit in shared memory (400000 * 2 = 800000).
    // The ratio of the shared memory region size to the maximum hash table size is 30000000 / 800000 = 37.5
    // Since the calculations are based on an average size, the ratio is rounded to 40 to avoid imbuing too much significance.
    // The size of the hash table for a cache of the passed-in size, then, should be the size of the cache divided by the ratio.
    // hashtable size upper limit == cache size upper limit / 40 == 30000000 / 40 < 800000
    const int SHMEM_TO_MAX_HASHTABLE_SIZE_RATIO{40};
    Hashtable *objectMap = newHashTable(size / SHMEM_TO_MAX_HASHTABLE_SIZE_RATIO);

    MK_PTR( RuleSet, coreRuleSet );
    ecopy->coreRuleSetStatus = COMPRESSED;
    ecopy->appRuleSet = NULL;
    ecopy->appRuleSetStatus = UNINITIALIZED;
    ecopy->extRuleSet = NULL;
    ecopy->extRuleSetStatus = UNINITIALIZED;
    MK_PTR_TAPP( Env, coreFuncDescIndex, PARAM( Node ) );
    ecopy->coreFuncDescIndexStatus = COMPRESSED; /* The coreFuncDescIndex is stored in a continuously allocated memory block in *buf */
    ecopy->appFuncDescIndex = NULL;
    ecopy->appFuncDescIndexStatus = UNINITIALIZED;
    ecopy->extFuncDescIndex = NULL;
    ecopy->extFuncDescIndexStatus = UNINITIALIZED;
    ecopy->dataSize = ( *p - buf );
    ecopy->address = buf;
    ecopy->pointers = pointers0;
    ecopy->cacheSize = size;
    ecopy->cacheStatus = INITIALIZED;
    ecopy->appRegion = NULL;
    ecopy->appRegionStatus = UNINITIALIZED;
    ecopy->coreRegion = NULL;
    ecopy->coreRegionStatus = UNINITIALIZED;
    ecopy->extRegion = NULL;
    ecopy->extRegionStatus = UNINITIALIZED;
    ecopy->sysRegion = NULL;
    ecopy->sysRegionStatus = UNINITIALIZED;
    ecopy->sysFuncDescIndex = NULL;
    ecopy->sysFuncDescIndexStatus = UNINITIALIZED;
    ecopy->ruleEngineStatus = UNINITIALIZED;
    MK_VAR_ARRAY_IN_STRUCT( char, ruleBase );

    deleteHashTable( objectMap, nop );

    return ecopy;
}
Example #15
0
//	Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch
int main () {

    //Create the hash table we are going to use
    HashTable h = newHashTable();
    //Open up a dictionary of words to use from the start
    FILE * input = fopen("dictionary.txt", "r");
    if (input == NULL) return EXIT_FAILURE;

    //Malloc some space for the strings we are reading in from the dictionary
    char ** temp = malloc(sizeof(char*) * MAX_DICT_SIZE);
    int k = 0;
    for (k = 0; k < MAX_DICT_SIZE; k++) {
        temp[k] = malloc(sizeof(char) * MAX_STRING_LENGTH);
    }

    //Read in everything from the dictionary
    int i = 1;
    int j = 0;
    temp[j][0] = fgetc(input);
    while (temp[j][i-1] != EOF) {
        temp[j][i] = fgetc(input);
        if (temp[j][i] == '\n') {
            temp[j][i] = '\0';
            if (hashTableContains(temp[j], h)) {
                printf("\nSeen %s\n", temp[j]);
            } else {
                printf("\nNot seen %s\n", temp[j]);
                printf("Adding: %s\n", temp[j]);
                put(temp[j], h);
            }
            assert(hashTableContains(temp[j], h));
            i = 0;
            j++;
            temp[j][0] = fgetc(input);
        }
        i++;
    }
    //close the dictionary
    fclose(input);

    /* TODO: read in some strings from the user using scanf
             until they enter an empty string
             or until the dictionary is full
    */

//j is each string
//i is each character in a string
    while (fgets(temp[j],MAX_STRING_LENGTH,stdin) != NULL && j < MAX_DICT_SIZE) {

        //temp[j][i] = *s;

        if (temp[j][i] == '\n') {
            temp[j][i] = '\0';
            if (hashTableContains(temp[j], h)) {
                printf("\nSeen %s\n", temp[j]);
            } else {
                printf("\nNot seen %s\n", temp[j]);
                printf("Adding: %s\n", temp[j]);
                put(temp[j], h);
            }
            assert(hashTableContains(temp[j], h));
            i = 0;
            j++;
            //temp[j][0] = *s;
            //temp[j][0] = fgets(temp[j][i],MAX_STRING_LENGTH,stdin);
        }
        i++;


    }


    /*
                tell them if we have ever seen them before
                add them to the hash table
        */


    //free all the strings we have malloc'ed
    for (k=0; k < MAX_DICT_SIZE; k++) {
        free(temp[k]);
    }
    free(temp);

    //delete the hash table we used
    h = deleteHashTable(h);

    //exit
    return EXIT_SUCCESS;
}
Example #16
0
int main(int argc, char *argv[])
{
    char *fname;     // name of dictionary file
    FILE *wordf;     // handle for dictionary file
	Item word;       // current word from file
    int size = 7919; // default size of hash table
    HashTable htab;  // the hash table
	int nwords;      // # words read and stored
    int nfound;      // # words found during search tests

	// set up parameters
	switch (argc) {
	case 2: fname = argv[1]; break;
	case 3: fname = argv[1]; size = atoi(argv[2]); break;
    default: fname = NULL; usage(argv[0]); break;
	}

    // access the word file
	if (eq(fname,"-")) {
		wordf = stdin;
		printf("Reading words from stdin\n");
	}
	else {
    	wordf = fopen(fname,"r");
    	if (wordf == NULL) {
        	printf("Can't open %s\n",fname);
        	exit(1);
    	}
    	printf("Reading words from %s\n",fname);
	}

	// build hash table, containing all words from file
	nwords = 0; nfound = 0;
    htab = newHashTable(size);
	while ((word = ItemGet(wordf)) != NULL) {
		if (eq(word,"")) { dropItem(word); continue; }
		HashTableInsert(htab,word);
		nwords++;
		if (HashTableSearch(htab,word) != NULL)
			nfound++;
		dropItem(word);
	}

	// examine hash table
	HashTableStats(htab);

	// tests
	// warning: we are assuming that "!aaaaaa!" etc.
	// do not occur in the input; this is not guaranteed
	assert(nfound == nwords);
	assert(HashTableSearch(htab,"!aaaaaa!") == NULL) ;
	assert(HashTableSearch(htab,"!xxxxxx!") == NULL) ;
	assert(HashTableSearch(htab,"!yyyyyy!") == NULL) ;
	assert(HashTableSearch(htab,"!zzzzzz!") == NULL) ;
	printf("Testing completed OK\n");

	// clean up
	fclose(wordf);
    dropHashTable(htab);
    return 0;
}
Example #17
0
int processXMsg( int streamId, char *readmsg,
                 RuleEngineEventParam *param, Node *node,
                 Env *env, ruleExecInfo_t *rei ) {

    char myhdr[HEADER_TYPE_LEN];
    char mymsg[MAX_NAME_LEN];
    char *outStr = NULL;
    int i, n;
    int iLevel, wCnt;
    int  ruleInx = 0;
    Region *r;
    Res *res;
    rError_t errmsg;
    errmsg.len = 0;
    errmsg.errMsg = NULL;
    r = make_region( 0, NULL );
    ParserContext *context = newParserContext( &errmsg, r );
    Pointer *e = newPointer2( readmsg );
    int rulegen = 1;
    int found;
    int grdf[2];
    int cmd = 0;
    int smallW;

    snprintf( myhdr, HEADER_TYPE_LEN - 1,   "idbug:%s", param->actionName );
    memset( mymsg, 0, sizeof( mymsg ) );

    PARSER_BEGIN( DbgCmd )
    TRY( DbgCmd )
    TTEXT2( "n", "next" );
    cmd = REDEBUG_STEP_OVER;
    OR( DbgCmd )
    TTEXT2( "s", "step" );
    cmd = REDEBUG_NEXT;
    OR( DbgCmd )
    TTEXT2( "f", "finish" );
    cmd = REDEBUG_STEP_OUT;
    OR( DbgCmd )
    TTEXT2( "b", "break" );
    TRY( Param )
    TTYPE( TK_TEXT );
    int breakPointsInx2;
    for ( breakPointsInx2 = 0; breakPointsInx2 < 100; breakPointsInx2++ ) {
        if ( breakPoints[breakPointsInx2].actionName == NULL ) {
            break;
        }
    }
    if ( breakPointsInx2 == 100 ) {
        _writeXMsg( streamId, myhdr, "Maximum breakpoint count reached. Breakpoint not set.\n" );
        cmd = REDEBUG_WAIT;
    }
    else {
        breakPoints[breakPointsInx2].actionName = strdup( token->text );
        char * base_ptr = NULL;
        TRY( loc )
        TTYPE( TK_TEXT );
        base_ptr = ( char * ) malloc( sizeof( token->text ) + 2 );
        base_ptr[0] = 'f';
        strcpy( base_ptr + 1, token->text );
        TTEXT( ":" );
        TTYPE( TK_INT );
        breakPoints[breakPointsInx2].base = strdup( base_ptr );
        breakPoints[breakPointsInx2].line = atoi( token->text );
        rodsLong_t range[2];
        char rulesFileName[MAX_NAME_LEN];
        getRuleBasePath( base_ptr, rulesFileName );

        FILE *file;
        /* char errbuf[ERR_MSG_LEN]; */
        file = fopen( rulesFileName, "r" );
        if ( file == NULL ) {
            free( context );
            deletePointer( e );
            free( base_ptr );
            return RULES_FILE_READ_ERROR;
        }
        Pointer *p = newPointer( file, base_ptr );


        if ( getLineRange( p, breakPoints[breakPointsInx2].line, range ) == 0 ) {
            breakPoints[breakPointsInx2].start = range[0];
            breakPoints[breakPointsInx2].finish = range[1];
        }
        else {
            breakPoints[breakPointsInx2].actionName = NULL;
        }
        deletePointer( p );
        OR( loc )
        TTYPE( TK_INT );
        if ( node != NULL ) {
            breakPoints[breakPointsInx2].base = strdup( node->base );
            breakPoints[breakPointsInx2].line = atoi( token->text );
            rodsLong_t range[2];
            Pointer *p = newPointer2( breakPoints[breakPointsInx2].base );
            if ( getLineRange( p, breakPoints[breakPointsInx2].line, range ) == 0 ) {
                breakPoints[breakPointsInx2].start = range[0];
                breakPoints[breakPointsInx2].finish = range[1];
            }
            else {
                breakPoints[breakPointsInx2].actionName = NULL;
            }
            deletePointer( p );
        }
        else {
            breakPoints[breakPointsInx2].actionName = NULL;
        }
        OR( loc )
        /* breakPoints[breakPointsInx].base = NULL; */
        END_TRY( loc )

        free( base_ptr );
        if ( breakPoints[breakPointsInx2].actionName != NULL )
            snprintf( mymsg, MAX_NAME_LEN, "Breakpoint %i  set at %s\n", breakPointsInx2,
                      breakPoints[breakPointsInx2].actionName );
        else {
            snprintf( mymsg, MAX_NAME_LEN, "Cannot set breakpoint, source not available\n" );
        }
        _writeXMsg( streamId, myhdr, mymsg );
        if ( breakPointsInx <= breakPointsInx2 ) {
            breakPointsInx = breakPointsInx2 + 1;
        }
        cmd = REDEBUG_WAIT;
    }
    OR( Param )
    NEXT_TOKEN_BASIC;
    _writeXMsg( streamId, myhdr, "Unknown parameter type.\n" );
    cmd = REDEBUG_WAIT;
    OR( Param )
    _writeXMsg( streamId, myhdr, "Debugger command \'break\' requires at least one argument.\n" );
    cmd = REDEBUG_WAIT;
    END_TRY( Param )

    OR( DbgCmd )
    TRY( Where )
    TTEXT2( "w", "where" );
    smallW = 1;
    OR( Where )
    TTEXT2( "W", "Where" );
    smallW = 0;
    END_TRY( Where )
    wCnt = 20;
    OPTIONAL_BEGIN( Param )
    TTYPE( TK_INT );
    wCnt = atoi( token->text );
    OPTIONAL_END( Param )
    iLevel = 0;

    i = reDebugStackCurrPtr - 1;
    while ( i >= 0 && wCnt > 0 ) {
        if ( !smallW || ( reDebugPCType( ( RuleEngineEvent ) reDebugStackCurr[i].label ) & 1 ) != 0 ) {
            snprintf( myhdr, HEADER_TYPE_LEN - 1,   "idbug: Level %3i", iLevel );
            char msg[HEADER_TYPE_LEN - 1];
            RuleEngineEventParam param;
            param.ruleIndex = 0;
            param.actionName = reDebugStackCurr[i].step;
            printRuleEngineEventLabel( msg, HEADER_TYPE_LEN - 1, ( RuleEngineEvent ) reDebugStackCurr[i].label, &param );
            _writeXMsg( streamId,  myhdr, msg );
            if ( reDebugStackCurr[i].label != EXEC_ACTION_BEGIN ) {
                iLevel++;
            }
            wCnt--;
        }
        i--;
    }
    OR( DbgCmd )
    TTEXT2( "l", "list" );
    TRY( Param )
    TTEXT2( "r", "rule" );
    TRY( ParamParam )
    TTYPE( TK_TEXT );

    mymsg[0] = '\n';
    mymsg[1] = '\0';
    snprintf( myhdr, HEADER_TYPE_LEN - 1,   "idbug: Listing %s", token->text );
    RuleIndexListNode *node;
    found = 0;
    while ( findNextRule2( token->text, ruleInx, &node ) != NO_MORE_RULES_ERR ) {
        found = 1;
        if ( node->secondaryIndex ) {
            n = node->condIndex->valIndex->len;
            int i;
            for ( i = 0; i < n; i++ ) {
                Bucket *b = node->condIndex->valIndex->buckets[i];
                while ( b != NULL ) {
                    RuleDesc *rd = getRuleDesc( *( int * )b->value );
                    char buf[MAX_RULE_LEN];
                    ruleToString( buf, MAX_RULE_LEN, rd );
                    snprintf( mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ), "%i: %s\n%s\n", node->ruleIndex, rd->node->base[0] == 's' ? "<source>" : rd->node->base + 1, buf );
                    b = b->next;
                }
            }
        }
        else {
            RuleDesc *rd = getRuleDesc( node->ruleIndex );
            char buf[MAX_RULE_LEN];
            ruleToString( buf, MAX_RULE_LEN, rd );
            snprintf( mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ), "\n  %i: %s\n%s\n", node->ruleIndex, rd->node->base[0] == 's' ? "<source>" : rd->node->base + 1, buf );
        }
        ruleInx ++;
    }
    if ( !found ) {
        snprintf( mymsg, MAX_NAME_LEN, "Rule %s not found\n", token->text );
    }
    _writeXMsg( streamId, myhdr, mymsg );
    cmd = REDEBUG_WAIT;
    OR( ParamParam )
    _writeXMsg( streamId, myhdr, "Debugger command \'list rule\' requires one argument.\n" );
    cmd = REDEBUG_WAIT;
    END_TRY( ParamParam )
    OR( Param )
    TTEXT2( "b", "breakpoints" );
    snprintf( myhdr, HEADER_TYPE_LEN - 1,   "idbug: Listing %s", token->text );
    mymsg[0] = '\n';
    mymsg[1] = '\0';
    for ( i = 0; i < breakPointsInx; i++ ) {
        if ( breakPoints[i].actionName != NULL ) {
            if ( breakPoints[i].base != NULL ) {
                snprintf( mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ), "Breaking at BreakPoint %i:%s %s:%d\n", i , breakPoints[i].actionName, breakPoints[i].base[0] == 's' ? "<source>" : breakPoints[i].base + 1, breakPoints[i].line );
            }
            else {
                snprintf( mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ), "Breaking at BreakPoint %i:%s\n", i , breakPoints[i].actionName );
            }
        }
    }
    _writeXMsg( streamId, myhdr, mymsg );
    cmd = REDEBUG_WAIT;
    OR( Param )
    TTEXT( "*" );
    snprintf( myhdr, HEADER_TYPE_LEN - 1,   "idbug: Listing %s", token->text );
    Env *cenv = env;
    mymsg[0] = '\n';
    mymsg[1] = '\0';
    found = 0;
    while ( cenv != NULL ) {
        n = cenv->current->size;
        for ( i = 0; i < n; i++ ) {
            Bucket *b = cenv->current->buckets[i];
            while ( b != NULL ) {
                if ( b->key[0] == '*' ) { /* skip none * variables */
                    found = 1;
                    char typeString[128];
                    typeToString( ( ( Res * )b->value )->exprType, NULL, typeString, 128 );
                    snprintf( mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ), "%s of type %s\n", b->key, typeString );
                }
                b = b->next;
            }
        }
        cenv = cenv->previous;
    }
    if ( !found ) {
        snprintf( mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ), "<empty>\n" );
    }
    _writeXMsg( streamId, myhdr, mymsg );
    cmd = REDEBUG_WAIT;
    OR( Param )
    syncTokenQueue( e, context );
    skipWhitespace( e );
    ABORT( lookAhead( e, 0 ) != '$' );
    snprintf( myhdr, HEADER_TYPE_LEN - 1,   "idbug: Listing %s", token->text );
    mymsg[0] = '\n';
    mymsg[1] = '\0';
    Hashtable *vars = newHashTable( 100 );
    for ( i = 0; i < coreRuleVarDef .MaxNumOfDVars; i++ ) {
        if ( lookupFromHashTable( vars, coreRuleVarDef.varName[i] ) == NULL ) {
            snprintf( &mymsg[strlen( mymsg )], MAX_NAME_LEN - strlen( mymsg ), "$%s\n", coreRuleVarDef.varName[i] );
            insertIntoHashTable( vars, coreRuleVarDef.varName[i], coreRuleVarDef.varName[i] );
        }
    }
    deleteHashTable( vars, NULL );
    _writeXMsg( streamId, myhdr, mymsg );
    cmd = REDEBUG_WAIT;
    OR( Param )
    NEXT_TOKEN_BASIC;
    _writeXMsg( streamId, myhdr, "Unknown parameter type.\n" );
    cmd = REDEBUG_WAIT;
    OR( Param )
    _writeXMsg( streamId, myhdr, "Debugger command \'list\' requires at least one argument.\n" );
    cmd = REDEBUG_WAIT;
    END_TRY( Param )
    OR( DbgCmd )
    TTEXT2( "c", "continue" );
    cmd = REDEBUG_STEP_CONTINUE;
    OR( DbgCmd )
    TTEXT2( "C", "Continue" );
    cmd = REDEBUG_CONTINUE_VERBOSE;
    OR( DbgCmd )
    TTEXT2( "del", "delete" );
    TRY( Param )
    TTYPE( TK_INT );
    n = atoi( token->text );
    if ( breakPoints[n].actionName != NULL ) {
        free( breakPoints[n].actionName );
        if ( breakPoints[n].base != NULL ) {
            free( breakPoints[n].base );
        }
        breakPoints[n].actionName = NULL;
        breakPoints[n].base = NULL;
        snprintf( mymsg, MAX_NAME_LEN, "Breakpoint %i  deleted\n", n );
    }
    else {
        snprintf( mymsg, MAX_NAME_LEN, "Breakpoint %i  has not been defined\n", n );
    }
    _writeXMsg( streamId, myhdr, mymsg );
    cmd = REDEBUG_WAIT;
    OR( Param )
    _writeXMsg( streamId, myhdr, "Debugger command \'delete\' requires one argument.\n" );
    cmd = REDEBUG_WAIT;
    END_TRY( Param )
    OR( DbgCmd )
    TTEXT2( "p", "print" );
    Node *n = parseTermRuleGen( e, 1, context );
    if ( getNodeType( n ) == N_ERROR ) {
        errMsgToString( context->errmsg, mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ) );
    }
    else {
        snprintf( myhdr, HEADER_TYPE_LEN - 1,   "idbug: Printing " );
        char * ptr = myhdr + strlen( myhdr );
        i = HEADER_TYPE_LEN - 1 - strlen( myhdr );
        termToString( &ptr, &i, 0, MIN_PREC, n, 0 );
        snprintf( ptr, i, "\n" );
        if ( env != NULL ) {
            disableReDebugger( grdf );
            res = computeNode( n, NULL, regionRegionCpEnv( env, r, ( RegionRegionCopyFuncType * ) regionRegionCpNode ), rei, 0, &errmsg, r );
            enableReDebugger( grdf );
            outStr = convertResToString( res );
            snprintf( mymsg, MAX_NAME_LEN, "%s\n", outStr );
            free( outStr );
            if ( getNodeType( res ) == N_ERROR ) {
                errMsgToString( &errmsg, mymsg + strlen( mymsg ), MAX_NAME_LEN - strlen( mymsg ) );
            }
        }
        else {
            snprintf( mymsg, MAX_NAME_LEN, "Runtime environment: <empty>\n" );
        }
    }
    _writeXMsg( streamId, myhdr, mymsg );

    cmd = REDEBUG_WAIT;
    OR( DbgCmd )
    TTEXT2( "d", "discontinue" );
    cmd = REDEBUG_WAIT;
    OR( DbgCmd )
    snprintf( mymsg, MAX_NAME_LEN, "Unknown Action: %s", readmsg );
    _writeXMsg( streamId, myhdr, mymsg );
    cmd = REDEBUG_WAIT;
    END_TRY( DbgCmd )
    PARSER_END( DbgCmd )
    freeRErrorContent( &errmsg );
    region_free( r );
    deletePointer( e );
    free( context );
    return cmd;
}
Example #18
0
HashTable *newStringHashTable() {
  return newHashTable(stringHash, stringEqual);
}
Example #19
0
HashTable *newIntHashTable() { return newHashTable(intHash, intEqual); }