Exemplo n.º 1
0
int test_top ( void )
{
  Stack_t *sp = NULL;  
  Stack_t *sp1 = NULL;
  
  printf("*** test_top\n");

  sp = StackCreate(4);

  (void)push(sp,100);
  (void)push(sp,200);
  (void)push(sp,300);
  (void)push(sp,700);
  StackDump(sp, 0);
  
  printf("\tTest01 return 700 %d\n", top(sp));

  printf("\tTest02 return  -1 %d  NULL stack\n", top(NULL));  

  sp1 = StackCreate(4);  
  printf("\tTest02 return  -1 %d  Empty Stack\n", top(sp1));  

  (void)StackDestroy(sp);
  (void)StackDestroy(sp1);  

  printf("test_top - Ends\n");

  return 0;
}
Exemplo n.º 2
0
void qsort_1 (int *arr, int size) {
  stackT stack;
  stackElementT element, e;
  int k;
  StackInit (&stack, size);
  element.left = 0;
  element.right = size - 1;
  StackPush(&stack, element);
  while (!StackIsEmpty (&stack)) {
    element = StackPop (&stack);
    while (element.left < element.right) {
      if (element.right - element.left < SWITCH_THRESH) {
	insertsort(&arr[element.left], element.right - element.left + 1);
	element.left = element.right;
      } else {
	k = partition(arr, element.left, element.right);
	e.left = element.left;
	e.right = k;
	StackPush(&stack, e);
	element.left = k+1;
      }
    }
  }
  StackDestroy (&stack);
  return;
}
Exemplo n.º 3
0
Arquivo: abp.c Projeto: pbmartins/AlgC
int ABPMultSum (PtABPNode proot, int pvalue)
{
    PtABPNode node = proot;
    PtStack stack;
    int sum = 0;

    if (proot == NULL) {
        Error = ABP_EMPTY;
        return -1;
    }

    if ((stack = StackCreate(sizeof(PtABPNode))) == NULL) {
        Error = NO_MEM;
        return -1;
    }

    StackPush(stack, &node);

    while (!StackIsEmpty(stack)) {
        StackPop(stack, &node);
        if (!(node->Elem % pvalue))
            sum += node->Elem;

        if (node->PtRight != NULL)
            StackPush(stack, &(node->PtRight));
        if (node->PtLeft != NULL)
            StackPush(stack, &(node->PtLeft));
    }

    StackDestroy(&stack);
    Error = OK;
    return sum;
}
Exemplo n.º 4
0
Arquivo: abp.c Projeto: pbmartins/AlgC
void ABPPostOrderRep (PtABPNode proot)  /* travessia em pós-ordem repetitiva - repetitive post-order traversal */
{
	PtABPNode Node = proot, Last = proot; PtStack Stack;

	if (proot == NULL) { Error = ABP_EMPTY; return;	}	/* arvore vazia - empty tree */
	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }

	while (1)	/* enquanto houver elementos para visitar - while there are nodes */
	{
			/* travessia pela esquerda até atingir a folha mais à esquerda - left traversal until the left most leaf */
		while (Node->PtLeft != NULL)
		{ StackPush (Stack, &Node); Node = Node->PtLeft; }

		/* se não tem subarvore direita ou já completou a sua travessia - without right subtree or already completed the traversal */
		while (Node->PtRight == NULL || Node->PtRight == Last)
		{
			printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */
			Last = Node;	/* assinalar último elemento visitado - marking the last visited element */
					/* terminar quando não há mais elementos na pilha - terminate when there are no more elments in the stack */
			if (StackIsEmpty (Stack)) { StackDestroy (&Stack); Error = OK; return; }

			StackPop (Stack, &Node);	/* retirar o elemento anterior - retrieve the preview element */
		}

		StackPush (Stack, &Node);	/* recolocar o elemento na pilha - restore the element in the stack */
		Node = Node->PtRight;	/* iniciar travessia da subarvore direita - start the right subtree traversal */
	}
}
Exemplo n.º 5
0
Arquivo: abp.c Projeto: pbmartins/AlgC
void ABPInOrderRep (PtABPNode proot)  /* travessia em in-ordem repetitiva - repetitive in-order traversal */
{
	PtABPNode Node = proot; PtStack Stack;

	if (proot == NULL) { Error = ABP_EMPTY; return;	} /* arvore vazia - empty tree */
	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }
	StackPush (Stack, &Node);	/* armazenar a raiz - storing the root */

	while (!StackIsEmpty (Stack))
	{
		if (Node != NULL)	/* não é um no externo - not an external node */
		{
			Node = Node->PtLeft;
			StackPush (Stack, &Node);	/* subarvore esquerda - left subtree */
		}
		else	/* é um no externo */
		{
			StackPop (Stack, &Node);	/* retirar e descartar o no externo - retrieve and ignore the external node */
			if (!StackIsEmpty (Stack))
			{
				StackPop (Stack, &Node);	/* recuperar o no anterior - retrieve and preview node */
				printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */
				Node = Node->PtRight;	/* subarvore direita - right subtree */
				StackPush (Stack, &Node);
			}
		}
	}

	StackDestroy (&Stack);	/* destruir a pilha - releasing the stack */
    Error = OK;
}
Exemplo n.º 6
0
Arquivo: abp.c Projeto: pbmartins/AlgC
unsigned int ABPSizeRep (PtABPNode proot)  /* cálculo do número de elementos repetitiva - repetitive number of nodes */
{
	PtABPNode Node = proot; PtStack Stack; unsigned int Number = 0;

	if (proot == NULL) { Error = ABP_EMPTY; return 0;	} /* arvore vazia - empty tree */

	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return 0; }
	StackPush (Stack, &Node);	/* armazenar a raiz - storing the root */

	while (!StackIsEmpty (Stack))	/* enquanto existirem nos - while there are nodes */
	{
		StackPop (Stack, &Node);	/* recuperar o no - retrieve the node */
		Number++;	/* contar o no - counting the node */

		/* armazenar a raiz da subarvore esquerda - storing the left subtree root */
		if (Node->PtLeft != NULL) StackPush (Stack, &Node->PtLeft);

		/* armazenar a raiz da subarvore direita - storing the right subtree root */
		if (Node->PtRight != NULL) StackPush (Stack, &Node->PtRight);
	}

	StackDestroy (&Stack);	/* destruir a pilha - releasing the stack */

    Error = OK;
	return Number;
}
Exemplo n.º 7
0
int CPU_Destroy ( CPU_t* Processor )
{
    if ( IsCPU_Valid ( Processor ) != 0 )
        return -1;

    free ( Processor->CPURegister ); Processor->CPURegister = NULL;
    free ( Processor->RAM ); Processor->RAM = NULL;
    Processor->ProgramCounter = 0;
    Processor->StatusReg = 0;
    StackDestroy ( Processor->CPUStack );
    free ( Processor ); Processor = NULL;
    return 0;
}
Exemplo n.º 8
0
int main(void)
{
  stackT stack;    /* A stack to hold characters. */
  char str[MAX];   /* String entered by user. */
  char *traverse;  /* Pointer used to traverse the string. */

  /*
   * Get a string from the user--don't enter more
   * than 10 characters!
   */
  printf("Enter a string <= 10 chars: ");

  fgets(str, MAX, stdin);  /* Read line, discard newline. */

  /*
   * Initialize the stack.  Make it at least
   * big enough to hold the string we read in.
   */
  StackInit(&stack, strlen(str));

  /*
   * Traverse the string and put each
   * character on the stack.
   */

  for (traverse = str; *traverse != '\0'; traverse++) 
  {
    printf("Pushing: %c on to stack\n", *traverse);
    StackPush(&stack, *traverse);
    printf("Popped: %c from top of stack\n", StackPop(&stack));
  }

  /*
   * Pop each of the characters off of
   * the stack and print them out.
   */

  /*
  printf("\nPopped characters are: ");

  while (!StackIsEmpty(&stack)) {
    printf("%c", StackPop(&stack));
  }
  */

  printf("\n");

  StackDestroy(&stack);

  return 0;
}
Exemplo n.º 9
0
void qsort_3 (int *arr, int size, const int numThreads) {
  //temp vals
  int i;
  //initialize stack
  stackT work;
  stackElementT element = {0, size-1};
  StackInit (&work, 2*(size/SWITCH_THRESH+1));
  StackPush (&work, element);
  //initialize all threads
  pthread_t *threads;
  threads = malloc (numThreads * sizeof(pthread_t));
  /*
  if (posix_memalign((void **)&threads, sizeof(pthread_t), MAX_THRDS*sizeof(pthread_t))) {
    perror("posix_memalign");
    exit(-1);
  }
  */
  int busyThreads = 0;
  struct qsort_3_args shared_arg = {arr, &work, &busyThreads};
  for (i = 0; i < numThreads; i++) {
#ifdef DEBUG
    printf("Creating thread %d\n", i+1);
#endif
    if (pthread_create(&threads[i], NULL, qsort_3_thread, &shared_arg)) {
      perror("pthread_create");
      exit(-1);
    }
  }
#ifdef DEBUG
  printf("Created all threads\n");
#endif
  //destroy all threads
  int status;
  for (i=0; i<numThreads; i++) {
#ifdef DEBUG
    printf("Joining thread %d\n", i+1);
#endif
    pthread_join(threads[i], (void **)&status);
  }
#ifdef DEBUG
  printf("Joined all threads\n");
#endif
  free(threads);
  //destroy stack
  StackDestroy (&work);
  return;
}
Exemplo n.º 10
0
/** Destroys given stacked memory object. 
 *
 *  Operations recorded within the object are not reversed. Their records are just
 *  deallocated.
 *
 *  @param StackedMemory Stacked memory object.
 */
VOID StackedMemoryDestroy(PUTILS_STACK StackedMemory)
{
   PUTILS_STACK_ITEM stackItem = NULL;
   PUTILS_STACKED_MEMORY_RECORD stackRecord = NULL;
   DEBUG_ENTER_FUNCTION("StackedMemory=0x%p", StackedMemory);

   while (!StackEmpty(StackedMemory)) {
      stackItem = StackPopNoFree(StackedMemory);
      stackRecord = CONTAINING_RECORD(stackItem, UTILS_STACKED_MEMORY_RECORD, StackItem);
      HeapMemoryFree(stackRecord);
   }

   StackDestroy(StackedMemory);

   DEBUG_EXIT_FUNCTION_VOID();
   return;
}
Exemplo n.º 11
0
Arquivo: abp.c Projeto: pbmartins/AlgC
int ABPEvenOrderSum (PtABPNode proot)
{
    PtABPNode node = proot;
    PtStack stack;
    int order = 0, sum = 0;
    
    if (proot == NULL) {
        Error = ABP_EMPTY;
        return -1;
    }

    if ((stack = StackCreate(sizeof(PtABPNode))) == NULL) {
        Error = NO_MEM;
        return -1;
    }

    StackPush(stack, &node);

    while(!StackIsEmpty(stack)) {
        if (node != NULL) {
            node = node->PtLeft;
            StackPush(stack, &node);
        } else {
            StackPop(stack, &node);
            if (!StackIsEmpty(stack)) {
                StackPop(stack, &node);
                if (order++ & 1)
                    sum += node->Elem;
                node = node->PtRight;
                StackPush(stack, &node);
            }
        }
    }

    StackDestroy(&stack);
    Error = OK;
    return sum;
}
Exemplo n.º 12
0
Arquivo: abp.c Projeto: pbmartins/AlgC
void ABPPreOrderRep (PtABPNode proot)  /* travessia em pré-ordem repetitiva - repetitive pre-order traversal */
{
	PtABPNode Node = proot; PtStack Stack;

	if (proot == NULL) { Error = ABP_EMPTY; return;	} /* arvore vazia - empty tree */
	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }

	StackPush (Stack, &Node);	/* armazenar a raiz - storing the root */
	while (!StackIsEmpty (Stack))	/* enquanto existirem nos - while there are nodes */
	{
		StackPop (Stack, &Node);	/* recuperar o no - retrieve the node */
		printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */

				/* colocar a raiz da subarvore direita, caso exista - storing the right subtree root if it exists */
		if (Node->PtRight != NULL) StackPush (Stack, &Node->PtRight);

				/* colocar a raiz da subarvore esquerda, caso exista - storing the left subtree root if it exists */
		if (Node->PtLeft != NULL) StackPush (Stack, &Node->PtLeft);
	}

	StackDestroy (&Stack);	/* destruir a pilha - releasing the stack */
    Error = OK;
}
Exemplo n.º 13
0
int test_swap ( void )
{
  Stack_t *sp = NULL;  
  Stack_t *sp1= NULL;
  Stack_t *sp2 = NULL;
  Stack_t *sp3 = NULL;
  Stack_t *sp4 = NULL;
  Stack_t *sp5 = NULL;
  Stack_t *sp6 = NULL;
  Stack_t *sp7 = NULL;
  Stack_t *sp8 = NULL;  
  Stack_t *sp9 = NULL;
  
  printf("test_swap - create <int> stack\n");

  sp = StackCreate(4);
  sp1= StackCreate(4);
  
  (void)push(sp,100);
  (void)push(sp,200);
  (void)push(sp,300);
  (void)push(sp,700);

  (void)push(sp1,101);
  (void)push(sp1,201);
  (void)push(sp1,301);
  (void)push(sp1,701);

  (void)StackDestroy(sp);
  printf("\tTest01 swap - same size, but stack freed -1 = %d\n", swap(sp,sp1));

  /*
   * Test02 positive swap - same size
   */
  sp2 = StackCreate(4);
  sp3 = StackCreate(4);

  (void)push(sp2,1);
  (void)push(sp2,2);
  (void)push(sp2,3);
  (void)push(sp2,4);
  printf("\tTest02 - before sp2\n");
  StackDump(sp2,0);

  (void)push(sp3,5);
  (void)push(sp3,6);
  (void)push(sp3,7);
  (void)push(sp3,8);
  printf("\tTest02 - before sp3\n");
  StackDump(sp3,0);

  printf("Test02 swap same size, but ok 0 = %d\n", swap(sp2,sp3));
  printf("\tTest02 - after sp2\n");
  StackDump(sp2,0);
  printf("\tTest02 - after sp3\n");
  StackDump(sp3,0);

   /*
    * Test04 positive swap - src size is less than dst, will need to increase src
    */
   sp6 = StackCreate(2);  /* src */
   sp7 = StackCreate(4);  /* dst */

   (void)push(sp6,1);
   (void)push(sp6,2);
   printf("\tTest04 - before sp6, size %d\n", size(sp6));
   StackDump(sp6,0);

   (void)push(sp7,3);
   (void)push(sp7,4);
   (void)push(sp7,5);
   (void)push(sp7,4);
   printf("\tTest04 - before sp7, size %d\n", size(sp7));
   StackDump(sp7,0);

   printf("Test04 swap dst size less than src size, but ok 0 = %d\n", swap(sp6,sp7));
   printf("\tTest04 - after sp6, size %d\n", size(sp6));
   StackDump(sp6,0);
   printf("\tTest04 - after sp7, size %d\n", size(sp7));
   StackDump(sp7,0);

   /*
    * Test05 positive swap - dst size is less than src, will need to increase dst
    */
   sp8 = StackCreate(2);  /* dst */
   sp9 = StackCreate(4);  /* src */

   (void)push(sp8,101);
   (void)push(sp8,201);
   printf("\tTest05 - before dst sp8, size %d\n", size(sp8));
   StackDump(sp8,0);

   (void)push(sp9,301);
   (void)push(sp9,401);
   (void)push(sp9,501);
   (void)push(sp9,401);
   printf("\tTest05 - before src sp9, size %d\n", size(sp9));
   StackDump(sp9,0);
   
   printf("Test05 swap dst size less than src size, but ok 0 = %d\n", swap(sp9,sp8));
   printf("\tTest05 - after dst sp8, size %d\n", size(sp8));
   StackDump(sp8,0);
   printf("\tTest05 - after src sp9, size %d\n", size(sp9));
   StackDump(sp9,0);
   
   printf("test_swap - Ends\n");

   StackDestroy(sp );
   StackDestroy(sp1);
   StackDestroy(sp2);
   StackDestroy(sp3);
   StackDestroy(sp4);
   StackDestroy(sp5);
   StackDestroy(sp6);
   StackDestroy(sp7);
   StackDestroy(sp8);
   StackDestroy(sp9);

   return 0;
}
//returns the total number of collided cells
int add_block_1_axis(rb_red_blk_tree *tree, int x1, int y1, int x2, int y2, unsigned int type, int add_amount) {
  circ_tree_node *node_begin, *node_end;
  node_end = get_node(tree, x2, type)->key;  //the end strictly needs to be called before the beginning
  node_begin = get_node(tree, x1, type)->key;
  stk_stack *axis_range = RBEnumerate(tree, node_begin, node_end);

  rb_red_blk_node *rb_node, *rb_node_prev = NULL;
  int temp_collision = 0, collision = 0, prev_pos;

  for (;;) {
    //rb_node_prev = rb_node;
    rb_node = (rb_red_blk_node *) StackPop(axis_range);

    //if (rb_node_prev == NULL)
      rb_node_prev = TreePredecessor(tree, rb_node);
    
    circ_tree_node *node = (circ_tree_node *) rb_node->key;
    circ_tree_node *node_prev;

    if (rb_node_prev == NULL || rb_node_prev == tree->nil)
      node_prev = NULL;
    else
      node_prev = (circ_tree_node *) rb_node_prev->key;

    unsigned int stack_not_empty = StackNotEmpty(axis_range);

    //collision
    if (temp_collision) 
      //if temp collision is non-zero, by definition, node_prev
      //cannot be NULL
      collision += temp_collision * (node->pos - prev_pos);

    prev_pos = node->pos;

    if (type == TOP_LEVEL) {
      if (stack_not_empty) 
	temp_collision = add_block_1_axis(node->data.tree, y1, 0, y2, 0, SECOND_LEVEL, add_amount);
      if ((node_prev != NULL && 
	   !RBTreeCompare(node->data.tree, node_prev->data.tree, 
			  circ_node_equals)) ||
	  (node_prev == NULL && RBIsTreeEmpty(node->data.tree)))
	RBDelete(tree, rb_node);
      
    } else {
      if (stack_not_empty) {
	if (node->data.state > 0 && node->data.state > -add_amount) 
	  //if there is already a block here, and if there would still 
	  //be a block left, assess collision
	  temp_collision = add_amount;
	else
	  temp_collision = 0;
	node->data.state += add_amount;
      }

      //if both nodes are the same
      if ((node_prev != NULL && node_prev->data.state == node->data.state) ||
	  //or the previous node is null and this is zero
	  (node_prev == NULL && node->data.state == 0)) {
	RBDelete(tree, rb_node);
      }
    }

    if (!stack_not_empty)
      break;
  }
  StackDestroy(axis_range, dummy_fun);

  return collision;
}
Exemplo n.º 15
0
// Remove all comments from a valid C program
int main() {
  // Current char.
  int c;
  // Current column and line number.
  int col = 0, line = 1;
  enum ParserState state = kNormalCode;
  Element top_element;
  Stack s;
  StackInit(&s, kStackInitSize);
  int block_comment_start_line =0;
  int block_comment_start_col = 0;

  while ((c = getchar()) != EOF) {
    ++col;
    switch (state) {
      case kNormalCode:
        switch (c) {
          case '/':
            state = kLeadingSlash;
            break;
          case '\'':
            state = kInSingleQuotation;
            break;
          case '"':
            state = kInDoubleQuotation;
            break;
          case '\n':
            col = 0;
            ++line;
            break;
          default:
            CheckBrackets(&s, c);
            break;
        }
        break;
      case kLeadingSlash:
        switch (c) {
          case '*':
            state = kInBlockComment;
            block_comment_start_line = line;
            block_comment_start_col = col;
            break;
          case '/':
            state = kInLineComment;
            break;
          default:
            state = kNormalCode;
        }
        break;
      case kInSingleQuotation:
        switch (c) {
          case '\\':
            state = kEscapeInSingleQuotation;
            break;
          case '\'':
            state = kNormalCode;
            break;
          case '\n':
            // Miss match Quotation marks in this line.
            printf("line %d: error: missing terminating ' character.\n", line);
            ++line;
            state = kNormalCode;
            break;
          default:
            break;
        }
        break;
      case kInDoubleQuotation:
        switch (c) {
          case '\\':
            state = kEscapeInDoubleQuotation;
            break;
          case '"':
            state = kNormalCode;
            break;
          case '\n':
            // Miss match Quotation marks in this line.
            printf("line %d: error: missing terminating \" character.\n", line);
            ++line;
            state = kNormalCode;
            break;
          default:
            break;
        }
        break;
      case kEscapeInSingleQuotation:
        state = kInSingleQuotation;
        break;
      case kEscapeInDoubleQuotation:
        state = kInDoubleQuotation;
        break;
      case kInBlockComment:
        switch (c) {
          case '*':
            state = kTrailingStar;
            break;
          default:
            break;
        }
        break;
      case kTrailingStar:
        switch (c) {
          case '/':
            state = kNormalCode;
            break;
          case '*':
            state = kTrailingStar;
          default:
            state = kInBlockComment;
            break;
        }
        break;
      case kInLineComment:
        switch (c) {
          case '\n':
            state = kNormalCode;
            ++line;
            break;
          default:
            break;
        }
        break;
    }
  }
  switch (state) {
    case kInBlockComment:
      printf("line %d, col %d: error: unterminated comment.\n",
             block_comment_start_line, block_comment_start_col);
      break;
    case kInSingleQuotation:
      printf("line %d: error: missing terminating ' character.\n",
             line);
      break;
    case kInDoubleQuotation:
      printf("line %d: error: missing terminating \" character.\n",
             line);
      break;
    default:
      break;
  }
  while (StackPop(&s, &top_element)) {
    // Not Empty Stack
    printf("line %d, col %d: error: miss match for %c character.\n",
           top_element.line, top_element.col, top_element.c);
  }
  StackDestroy(&s);
  return 0;
}
Exemplo n.º 16
0
int main(int argc, char* argv[], char** envp)
{

	int i = 0;
	int count = 20;
	char *s1 = "abcdefg";
	char *s2 = "g";
	size_t len1 = 0;
	size_t n = 3;
	char dest[20];

	node_t *node1 = NULL;
	node_t *node2 = NULL;
	node_t *node3 = NULL;
	node_t *node4 = NULL;
	node_t *node5 = NULL;
	
	char *t = NULL;	
	
	stack_t *stack = NULL;
	size_t n1 = 1;
	size_t n2 = 2;
	size_t n3 = 3;
	size_t n4 = 4;
	size_t n5 = 5;
	
	/*__________  RecFibonacci  __________*/
	printf("\n[%s %s %d]RecFibonacci\n", __FILE__, __func__, __LINE__);
	
	for (i = 0; i < count; ++i)
	{
		printf("RecFibonacci(%i):%i\n", i , RecFibonacci(i));
	}
	
	/*__________  RecStrlen  __________*/
	printf("\n[%s %s %d]RecStrlen\n", __FILE__, __func__, __LINE__);
	
	len1 = RecStrlen(s1);
	printf("len1:%lu\n", len1);
	
	/*__________  RecStrcmp  __________*/
	printf("\n[%s %s %d]RecStrcmp\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrcmp(s1, s2): %i\n", RecStrcmp(s1, s2));
	
	
	/*__________  RecStrncmp  __________*/
	printf("\n[%s %s %d]RecStrncmp\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrncmp(s1, s2, n): %i\n", RecStrncmp(s1, s2, n));


	/*__________  RecStrstr  __________*/
	printf("\n[%s %s %d]RecStrstr\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrstr(s1, s2):%s\n", RecStrstr(s1, s2));
	
	/*__________  RecStrcpy  __________*/
	printf("\n[%s %s %d]RecStrcpy\n", __FILE__, __func__, __LINE__);
	t = RecStrcpy(dest, s1);
	printf("RecStrcpy(dest, s1):%s		expected result:%s\n", t, dest);
	
	
	/*__________  RecStrcat  __________*/
	printf("\n[%s %s %d]RecStrcat\n", __FILE__, __func__, __LINE__);
	
	printf("RecStrcat(dest, s1):%s		expected result:%s\n", 
			RecStrcat(dest, s1), 						"abcgefgabcdefg");
	
	/*__________  RecSlistFlip  __________*/
	printf("\n[%s %s %d]RecSListFlip\n", __FILE__, __func__, __LINE__);
	
	node5 = SListCreateNode((void*)5, NULL);
	node4 = SListCreateNode((void*)4, node5);
	node3 = SListCreateNode((void*)3, node4);
	node2 = SListCreateNode((void*)2, node3);
	node1 = SListCreateNode((void*)1, node2);
	
	printf("SListCount(node1):%lu\n", SListCount(node1));
	
	RecSListFlip(node1);
	
	printf("SListCount(node1):%lu\n", SListCount(node5));
	
	SListFreeAll(node5);
	
	/*__________  Compere  __________*/
	printf("\n[%s %s %d]Compere\n", __FILE__, __func__, __LINE__);
	
	printf("Compere(&n1, &n2):%i		expected result:1\n", Compere(&n1, &n2));
	
	printf("Compere(&n1, &n1):%i		expected result:1\n", Compere(&n1, &n2));
	
	printf("Compere(&n2, &n1):%i		expected result:0\n", Compere(&n2, &n1));
	/*_________________________  END Compere _______________________*/
	
	
	/*________________________________________________________________*/
	printf("\n[%s %s %d]RecStackSort\n", __FILE__, __func__, __LINE__);
	/*_________________________  RecStackSort  _______________________*/
	
	stack = StackCreate(sizeof(size_t), 5);
	assert(stack);
	
	StackPush(stack, &n3);
	StackPush(stack, &n2);
	StackPush(stack, &n5);
	StackPush(stack, &n4);
	StackPush(stack, &n1);

	RecStackSort(stack, &Compere, sizeof(size_t));
	
	for( ; StackSize(stack); StackPop(stack))
	{
		printf("StackPeek(stack):%lu\n", *(size_t*)StackPeek(stack));
	}
	
	StackDestroy(stack);	
	
	
	return(0);
}
Exemplo n.º 17
0
Arquivo: vm.c Projeto: erik/atto
TValue vm_interpret(AttoVM* vm, AttoBlock* block, int start, int argc)
{
    DEBUGF("Interpret block: %d ops\n", block->code->size);
    int error            = 0;
    TValue* max          = (TValue*)(block->code->elements + start + block->code->size);
    TValue *pc_val       = (TValue*)(block->code->elements + start);
    Instruction i        = TV2INST(*pc_val);
    Stack *stack         = &block->stack;
    const char* opcode_names[] = { OPCODE_NAMES };
    const char* op_name = NULL;

    int x;
    for(x = 0; pc_val < max && !error; ++x) {

        op_name = i >= NUM_OPS ? "unknown" : opcode_names[i];

        if(i >= NUM_OPS) {
            ERROR("bad opcode: %d", i);
        }

        DEBUGF("[%d]\t%s (%d)\n", x, op_name, i);
        switch(i) {
        case OP_NOP:
            DISPATCH;
        case OP_POP:
            EXPECT_ON_STACK(1);
            TValue v = pop(stack);
            valueDestroy(&v);
            DISPATCH;
        case OP_DUP: {
            EXPECT_ON_STACK(1);
            TValue v = pop(stack);
            push(stack, v);
            push(stack, v);
            DISPATCH;
        }
        case OP_SWAP: {
            EXPECT_ON_STACK(2);
            TValue f = pop(stack);
            TValue s = pop(stack);
            push(stack, f);
            push(stack, s);
            DISPATCH;
        }
        case OP_ADD:
        case OP_SUB:
        case OP_MUL:
        case OP_DIV:
        case OP_MOD:
        case OP_POW: {
            EXPECT_ON_STACK(2);
            TValue b = pop(stack);
            TValue a = pop(stack);
            TValue res = MathOp(i, a, b);

            push(stack, res);

            DISPATCH;
        }
        case OP_OR:
        case OP_AND:
        case OP_XOR: {
            EXPECT_ON_STACK(2);
            TValue b = pop(stack);
            TValue a = pop(stack);
            TValue res = BitwiseOp(i, a, b);

            push(stack, res);

            DISPATCH;
        }
        case OP_NOT: {
            EXPECT_ON_STACK(1);
            TValue a = pop(stack);
            push(stack, createNumber(~(long)TV2NUM(a)));
            DISPATCH;
        }
        case OP_EQ:
        case OP_LT:
        case OP_GT:
        case OP_LTE:
        case OP_GTE:
        case OP_CMP: {
            EXPECT_ON_STACK(2);
            TValue b = pop(stack);
            TValue a = pop(stack);
            TValue res = ComparisonOp(i, a, b);

            push(stack, res);

            DISPATCH;
        }
        case OP_IF: {
            EXPECT_ON_STACK(1);
            TValue t = pop(stack);
            if(boolValue(t)) {
                NEXTINST;
            }
            DISPATCH;
        }
        case OP_JMP: {
            EXPECT_ON_STACK(1);
            long jmp = (long)TV2NUM(pop(stack));
            if(jmp + pc_val >= max || jmp + (long)pc_val < 0) {
                ERROR("Invalid jump: %ld", jmp);
            }
            pc_val += jmp;
            DISPATCH;
        }
        case OP_PUSHCONST: {
            int index = TV2INST(*++pc_val);
            if(index >= (int)block->k->size) {
                ERROR("Constant index out of bounds: %d", index);
            }
            TValue k = getIndex(block->k, index);

            push(stack, k);
            DISPATCH;
        }
        case OP_PUSHVAR: {
            int index = TV2INST(*++pc_val);

            if(index < 0 || index >= block->sizev) {
                ERROR("Variable index out of bounds: %d", index);
            }

            DEBUGF("PUSHVAR, index %d, value >> %s\n", index, TValue_to_string(block->vars[index]));

            TValue var = block->vars[index];
            var.value.var.index = index;

            block->vars[index] = var;

            push(stack, var);
            DISPATCH;
        }
        case OP_SETVAR: {
            EXPECT_ON_STACK(2);
            TValue var = pop(stack);

            if(var.type != TYPE_VAR) {
                ERROR("Expected a var, but got %s", TValue_type_to_string(var));
            }

            int index = var.value.var.index;

            TValue *val = malloc(sizeof(TValue));

            *val = pop(stack);

            block->vars[index] = createVar(val);

            DEBUGF("SETVAR, index %d, value >> %s\n", index, TValue_to_string(block->vars[index]));

            DISPATCH;
        }
        case OP_VALUEVAR: {
            EXPECT_ON_STACK(1);
            TValue var = pop(stack);

            if(var.type != TYPE_VAR) {
                ERROR("Expected a var, but got %s", TValue_type_to_string(var));
            }

            Value val = *var.value.var.value;
            AttoType type = var.value.var.type;

            TValue t;
            t.value = val;
            t.type = type;

            push(stack, t);
            DISPATCH;
        }
        case OP_BOOLVALUE: {
            EXPECT_ON_STACK(1);

            TValue tos = pop(stack);

            int bool = boolValue(tos);

            valueDestroy(&tos);

            push(stack, createBool(bool));
            DISPATCH;
        }
        case OP_CONCAT: {
            EXPECT_ON_STACK(2);
            TValue top = pop(stack);
            TValue sec = pop(stack);

            if(!(top.type == TYPE_STRING && sec.type == TYPE_STRING)) {
                ERROR("Expected two string values, but got %s and %s", TValue_type_to_string(sec),
                      TValue_type_to_string(top));
            }

            char *top_s = TV2STR(top);
            char *sec_s = TV2STR(sec);


            char *str = malloc(strlen(top_s) + strlen(sec_s));

            strcpy(str, sec_s);
            strcat(str, top_s);

            valueDestroy(&top);
            valueDestroy(&sec);

            push(stack, createString(str, strlen(str), 0));
            free(str);
            DISPATCH;
        }
        case OP_PRINT: {
            EXPECT_ON_STACK(1);
            TValue v = pop(stack);
            char *str = TValue_to_string(v);

            printf("%s", str);

            if(v.type == TYPE_NUMBER) free(str);
            valueDestroy(&v);
            DISPATCH;
        }
        case OP_READLINE: {
            char *buf = malloc(BUFSIZ);
            memset(buf, '\0', BUFSIZ);
            if(fgets(buf, BUFSIZ, stdin) ) {
                char *nl = strchr(buf, '\n');
                if(nl) {
                    *nl = '\0';
                }
            }

            unsigned len = strlen(buf) + 1;
            push(stack, createString(buf, len, 0));

            free(buf);
            DISPATCH;
        }
        case OP_DUMPSTACK:
            print_stack(*stack);
            DISPATCH;

        case OP_CLEARSTACK: {
            Stack s = StackNew();
            StackDestroy(&block->stack);
            *stack = s;
            DISPATCH;
        }
        case OP_CALL: {
            EXPECT_ON_STACK(2);
            TValue fcn = pop(stack);
            TValue num = pop(stack);

            // FIXME: this explodes when types aren't right :(
            if(fcn.type != TYPE_FUNCTION || num.type != TYPE_NUMBER) {
                ERROR("Expected function and numeric values, but got %s and %s", TValue_type_to_string(fcn),
                      TValue_type_to_string(num));
            }

            int nargs = (int)TV2NUM(num);

            EXPECT_ON_STACK(nargs);

            int j;
            for(j = 0; j < nargs; ++j) {
                TValue v = pop(stack);
                push(&fcn.value.function.b->stack, v);
            }

            TValue ret = vm_interpret(vm, fcn.value.function.b, 0, nargs);

            if(ret.type != TYPE_NULL) {
                push(stack, ret);
            }

            valueDestroy(&fcn);
            valueDestroy(&num);
            valueDestroy(&fcn);

            DISPATCH;
        }
        case OP_RETURN: {
            EXPECT_ON_STACK(1);

            TValue ret = pop(stack);

            DEBUGF("Finished block, returning with %s\n", TValue_to_string(ret));

            return ret;

            DISPATCH;
        }
        default:
            ERROR("Unrecognized opcode: %d", i);
        }
    }

    DEBUGLN("Finished block");
    return createNull();
}