Ejemplo n.º 1
0
static void Compose2D(MatrixStack2D *ms) {
  if (StackSize(ms) >= 2) {
    Matrix2D *d = (Matrix2D *)StackPushNew(ms);
    Matrix2D *a = (Matrix2D *)StackPeek(ms, 2);
    Matrix2D *b = (Matrix2D *)StackPeek(ms, 1);

    Multiply2D(d, a, b);
  }
}
int main() 
{
  int N = 50;
  srand(time(0));
  stack *s = StackNew();
  printf("Node size = %ld Stack size = %ld\n", sizeof(node), sizeof(stack));
  for (int i = 0; i < N; i++) {
    printf("Push %d\n", i);
    StackPush(s, i);
  }
 
  StackPrint(s);

  for (int i = 0; i < N; i++) {
    int n = StackPop(s);
    printf("Pop %d\n", n);
    if (i % 2 == 0)
      printf("Peek = %d\n", StackPeek(s));
  }
  
  printf("Size = %d\n", s->size);
  StackFree(s);
  long sum = sizeof(node) * 50 + sizeof(stack);
  printf("%ld total bytes\n", sum);
}
Ejemplo n.º 3
0
//преобразовать № строки текущей правки в № строки исходного текста
inline static intptr_t CalcOriginalLine(intptr_t nLine)
{
	intptr_t nOrig=nLine;
	for (size_t iNestLevel=0;;iNestLevel++) {
		char *Lines=(char*)StackPeek(iNestLevel);
		if (Lines==NULL)
			return nOrig;
		nOrig = CalcLineInPrev(Lines, nOrig);
		if (nOrig==-1)
			return -1;
	}
}
Ejemplo n.º 4
0
static void ScrollText(ScrollType st)
{
	EditorInfo einfo = {sizeof(EditorInfo)};
	EditorSetPosition es = {sizeof(EditorSetPosition)};

	Info.EditorControl(-1, ECTL_GETINFO, 0, &einfo);
	switch (st) {
	case stDn:
		es.CurLine = einfo.CurLine+1;
		break;
	case stUp:
		es.CurLine = einfo.CurLine-1;
		break;
	case stPgDn:
		es.CurLine = einfo.CurLine+einfo.WindowSizeY-1;
		es.TopScreenLine = einfo.TopScreenLine+einfo.WindowSizeY-1;
		break;
	case stPgUp:
		es.CurLine = einfo.CurLine-einfo.WindowSizeY+1;
		es.TopScreenLine = einfo.TopScreenLine-einfo.WindowSizeY+1;
		break;
	case stEnd:
		es.CurLine = /*es.TopScreenLine = */einfo.TotalLines-1;
		break;
	default:
		es.CurLine = /*es.TopScreenLine = */0;
		break;
	}
	bLineChanged = true;

	es.CurPos = -1;
	es.CurTabPos = es.LeftPos = es.Overtype = -1;
	Info.EditorControl(-1, ECTL_SETPOSITION, 0, &es);

	//обновим № исходной строки
	Info.EditorControl(-1, ECTL_GETINFO, 0, &einfo);
	char *Lines = (char*)StackPeek();
	OriginalLine = CalcOriginalLine(einfo.CurLine);
	HighlightLine(einfo.CurLine);

	Info.AdvControl(&PluginId, ACTL_REDRAWALL, 0, NULL);
}
Ejemplo n.º 5
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);
}
Ejemplo n.º 6
0
/** @brief This function gives the tree functionality
	@param panel the panel handle of the panel on which the button is used
	@param control the control on which the event is generated
	@param event the type of event generated (i.e. left-click causes EVENT_COMMIT)
	@param *callbackData stores the data returned to the UI handled internally by LabWindows
	@param eventData1 stores ancillary information such as the mouse x-position within the panel
	@param eventData2 stores ancillary information such as the mouse y-position within the panel
	@return 1 or 0 specifies whether or not the event should be swallowed. 0 is default-no and 1 is yes-swallow.

### EXTERNAL VARIABLES
    - extern int @ref panelHandle - "OpenPET.c"
	- extern int @ref panelHandle_fmmode_mb - "OpenPET.c"
	- extern int @ref panelHandle_fmmode_duc - "OpenPET.c"
	- extern int @ref panelHandle_fmmode - "OpenPET.c" 
	- extern Stack @ref panel_stack - "UI_Common.c"
	- extern OpenPETTree @ref current_location - "UI_Common.c"

### ABNORMAL TERMINATION CONDITIONS, ERROR AND WARNING MESSAGES
	Errors may be generated by CVI/LabWindows. The LabWindows documentation is available online 
	at <a href="linkURL"> http://zone.ni.com/reference/en-XX/help/370051V-01/ </a>.
	
###	ALGORITHM
	The tree item double-clicked on is given as an index in eventData2. The tag is extracted (i.e. MB0DUC1DB2).
	This tag is parsed to specify the new desired location. The new panel is displayed and the stack is
	updated to allow the desired functionality in the back button.
	
###	DEVELOPMENT HISTORY
       Date    |  Author         |  Email Address     | Ver. |Description Of Change  
	   --------|-----------------|--------------------|------|---------------------
	 08/09/2013| George Netscher | [email protected] | 1.0  |conclusion of summer work
	 
### Copyright (c) 2013 by LBNL. All Rights Reserved.
*/
int CVICALLBACK FloodMapModeTree (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	char item_tag[32];
	OpenPETTree new_location;
	int i, idx=0, current_boards[3]={-1,-1,-1};
	
	switch (event)
	{
		case EVENT_COMMIT:

			// eventData2 contains index of tree item double-clicked
			GetTreeItemTag(panel, control, eventData2, item_tag);
			
			// update current_location so panel will initialize properly
			OpenPETTreeInit(&new_location);   // set to (-1, -1, -1, "NULL")
			new_location.mode = current_location.mode;
			
			for(i=0; i<32; i++)
			{
				// walk through tag string and pull out board numbers
				if( isdigit(item_tag[i]) )
				{
					current_boards[idx++] = (int)(item_tag[i] - '0');
				}
			}
			new_location.MB = current_boards[0];
			new_location.DUC = current_boards[1];
			new_location.DB = current_boards[2];
			
			// clear panel stack up to root panel 
			while( StackPeek(&panel_stack) != panelHandle )
			{
				StackPop(&panel_stack);	
			}
			
			// determine proper panel to display
			/*
			if(new_location.DB != -1) 
			{
				StackPush(&panel_stack, panelHandle_fmmode_mb); 
				StackPush(&panel_stack, panelHandle_fmmode_duc); 
				
				HidePanel (panel);				
				DisplayPanel (panelHandle_fmmode);
				
			}
			*/
			if (new_location.DUC != -1)
			{
				HidePanel(panel);				
				StackPush(&panel_stack, panelHandle_fmmode_mb); 
				StackPush(&panel_stack, panelHandle_fmmode_duc); 
				DisplayPanel(panelHandle_fmmode);
			}
			else if (new_location.MB != -1)
			{
				HidePanel(panel);
				StackPush(&panel_stack, panelHandle_fmmode_mb); 
				DisplayPanel(panelHandle_fmmode_duc);
			}
			else if (new_location.MB == -1)
			{
				HidePanel(panel);
				DisplayPanel(panelHandle_fmmode_mb);
			}
			else {
				HidePanel(panel); 
				DisplayPanel(StackPop(&panel_stack));
			}
			
			current_location.MB = new_location.MB;
			current_location.DUC = new_location.DUC;
			current_location.DB = new_location.DB;
			break;
	}
	return 0;
}
Ejemplo n.º 7
0
/** @brief This function gives the tree functionality
	@param panel the panel handle of the panel on which the button is used
	@param control the control on which the event is generated
	@param event the type of event generated (i.e. left-click causes EVENT_COMMIT)
	@param *callbackData stores the data returned to the UI handled internally by LabWindows
	@param eventData1 stores ancillary information such as the mouse x-position within the panel
	@param eventData2 stores ancillary information such as the mouse y-position within the panel
	@return 1 or 0 specifies whether or not the event should be swallowed. 0 is default-no and 1 is yes-swallow.

### EXTERNAL VARIABLES
    - extern int @ref panelHandle - "OpenPET.c"
	- extern int @ref panelHandle_timemode_mb - "OpenPET.c"
	- extern int @ref panelHandle_timemode_duc - "OpenPET.c"
	- extern int @ref panelHandle_timemode_db - "OpenPET.c"
	- extern int @ref panelHandle_timemode - "OpenPET.c" 
	- extern Stack @ref panel_stack - "UI_Common.c"
	- extern OpenPETTree @ref current_location - "UI_Common.c"

### ABNORMAL TERMINATION CONDITIONS, ERROR AND WARNING MESSAGES
	Errors may be generated by CVI/LabWindows. The LabWindows documentation is available online 
	at <a href="linkURL"> http://zone.ni.com/reference/en-XX/help/370051V-01/ </a>.
	
###	ALGORITHM
	The tree item double-clicked on is given as an index in eventData2. The tag is extracted (i.e. MB0DUC1DB2).
	This tag is parsed to specify the new desired location. The new panel is displayed and the stack is
	updated to allow the desired functionality in the back button.
	
###	DEVELOPMENT HISTORY
       Date    |  Author         |  Email Address     | Ver. |Description Of Change  
	   --------|-----------------|--------------------|------|---------------------
	 08/09/2013| George Netscher | [email protected] | 1.0  |conclusion of summer work
	 
### Copyright (c) 2013 by LBNL. All Rights Reserved.
*/
int CVICALLBACK TimeModeDBTree (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	char item_tag[32];
	OpenPETTree new_location;
	int i, idx, current_boards[3]={-1,-1,-1};
	
	switch (event)
	{
		case EVENT_COMMIT:
			// eventData2 contains index of tree item double-clicked
			GetTreeItemTag(panel, control, eventData2, item_tag);
			
			// update current_location so panel will initialize properly
			OpenPETTreeInit(&new_location);   // set to (-1, -1, -1, "NULL")
			new_location.mode = current_location.mode;
			
			if(system_size == 1)
				// large system -> fill in MB, DUC, and DB board locations
				idx = 0;
			else if(system_size == 2)
				// medium system -> fill in DUC and DB board locations
				idx = 1;
			else if(system_size == 3)
				// small system -> only fill in DB board location
				idx = 2;
			for(i=0; i<32; i++)
			{
				// walk through tag string and pull out board numbers
				if( isdigit(item_tag[i]) )
				{
					current_boards[idx++] = (int)(item_tag[i] - '0');
				}
			}
			new_location.MB = current_boards[0];
			new_location.DUC = current_boards[1];
			new_location.DB = current_boards[2];
			
			// clear panel stack up to root panel 
			while( StackPeek(&panel_stack) != panelHandle )
			{
				StackPop(&panel_stack);	
			}
			
			// determine proper panel to display
			if(new_location.DB != -1) 
			{
				if(system_size == 1)
					// large size
					StackPush(&panel_stack, panelHandle_timemode_mb); 
				if(system_size == 1 || system_size == 2)
					// large or medium size
					StackPush(&panel_stack, panelHandle_timemode_duc);
				
				StackPush(&panel_stack, panelHandle_timemode_db);
				
				HidePanel (panel);				
				DisplayPanel (panelHandle_timemode);
				
			}
			else if (new_location.DUC != -1)
			{
				// in small size, this will never be reached because DUC always equals -1
				if(system_size == 1)
					// large size
					StackPush(&panel_stack, panelHandle_timemode_mb); 
				if(system_size == 1 || system_size == 2)
					// large or medium size
					StackPush(&panel_stack, panelHandle_timemode_duc); 
				
				HidePanel(panel);
				DisplayPanel(panelHandle_timemode_db);
			}
			else if (new_location.MB != -1)
			{
				// in small or medium size, this will never be reached because MB always equals -1
				if(system_size == 1)
					// large size
					StackPush(&panel_stack, panelHandle_timemode_mb);
				
				HidePanel(panel);  
				DisplayPanel(panelHandle_timemode_duc);
			}
			else 
			{
				// only large system should reach here
				HidePanel(panel);
				DisplayPanel(panelHandle_timemode_mb);
			}
			
			current_location.MB = new_location.MB;
			current_location.DUC = new_location.DUC;
			current_location.DB = new_location.DB;
			
			break;
	}
	return 0;
}
Ejemplo n.º 8
0
PtrT StackTop(StackT *self) {
  return StackPeek(self, 0);
}
Ejemplo n.º 9
0
// Strong Component Search Code
struct TreeNode *AllStrongComponents(int startNode)
{ int i; struct TreeNode *tn = NULL;   // the tree node we'd like to create
  static int parentTreeNode,lastDfLabel,CallLevel,*dflabels,*low,*strongcomps,*backtracked;

// put in call level stuff, but make sure that unvisited nodes can get revisted...

  if (0 == CallLevel)
  { if (0 == numNodes) ReadInput();
    else {free(dflabels); free(low); free(strongcomps); free(backtracked);}
    dflabels = (int *)malloc(numNodes*sizeof(int));    
    low      = (int *)malloc(numNodes*sizeof(int));
    strongcomps  = (int *)malloc(numNodes*sizeof(int));
    backtracked  = (int *)malloc(numNodes*sizeof(int));}

  // recursion unrolling condition; only if dfLabel is unset
  //printf("recursion level %d\n",CallLevel);
  if (dflabels[startNode] == 0) 
  { tn = (struct TreeNode *)malloc(sizeof(TreeNode));
    tn->node_label = startNode;
    tn->parent = tn; // initialize parent as self
    tn->first = tn->last = tn->left = tn->right = NULL;
    if (0 == CallLevel) StackPush(strongcomps,startNode);
    CallLevel++;
    for (i = 0; i < nodes[startNode].degree; i++) 
    { // only assign dflabel once, init low      
      if (0 == dflabels[startNode]) 
      { tn->dflabel = dflabels[startNode] = low[startNode] = ++lastDfLabel;
        printf("dfLabel( %d)=%d, parentNode=%d, low[%d]=%d\n",startNode,lastDfLabel,parentTreeNode,startNode,low[startNode]);
        printf("stack: ");StackPrintAll(strongcomps);printf("\n");}
      printf("processing (%d,%d): ",tn->node_label,nodes[startNode].adjNodes[i]);
      if (0 == dflabels[nodes[startNode].adjNodes[i]]) 
      { printf ("tree-edge\n");
        StackPush(strongcomps,nodes[startNode].adjNodes[i]);
	parentTreeNode = startNode;
	// tree node building code section
	struct TreeNode *child = AllStrongComponents(nodes[startNode].adjNodes[i]);    
	if (NULL != child)
	{ child->left = child->right = NULL; child->parent = tn; 
          if (NULL == tn->first) tn->first = tn->last = child;
 	  else { child->left = tn->last; tn->last->right = tn->last = child; }	
          // backtracking...
          backtracked[child->node_label]++;
	}
	printf("backtracking %d -> %d\n",nodes[startNode].adjNodes[i],startNode);
        // update parent's low with child's low
	if (low[nodes[startNode].adjNodes[i]] < low[startNode]) 
	{ low[startNode] = low[nodes[startNode].adjNodes[i]];
          printf ("low[%d] = %d on backtrack\n",startNode,low[startNode]); 
	}
	else printf("No change in low[%d] on backtrack\n",startNode);
	// check to see if child is entry node for the strong component
	if (low[nodes[startNode].adjNodes[i]] == dflabels[nodes[startNode].adjNodes[i]]) 
	{ printf ("STRONG COMPONENT ");
	  while (StackPeek(strongcomps) != nodes[startNode].adjNodes[i]) printf("%d ",StackPop(strongcomps));
  	  printf("%d ",StackPop(strongcomps));
	  printf("\n");}
      }
      else if (dflabels[nodes[startNode].adjNodes[i]] < dflabels[startNode]  && backtracked[nodes[startNode].adjNodes[i]] == 0)
      { printf ("back-edge\n");
        if ((dflabels[nodes[startNode].adjNodes[i]]) < low[startNode]) 
        { low[startNode] = dflabels[nodes[startNode].adjNodes[i]];
	  printf ("low[%d] = %d on back-edge\n",startNode,low[startNode]);}
      }
      else if (backtracked[nodes[startNode].adjNodes[i]] > 0) 
      { printf("cross-edge\n");
        if ((dflabels[nodes[startNode].adjNodes[i]]) < low[startNode]) 
        { low[startNode] = dflabels[nodes[startNode].adjNodes[i]];
	  printf ("low[%d] = %d on cross-edge\n",startNode,low[startNode]);}
      }
    }
  }
  CallLevel--; 
  // pick unvisited
  if (0 == CallLevel) 
  { for (i = 0; i < numNodes; i++) 
    { if (0 == dflabels[i]) 
      { struct TreeNode *unvisted = AllStrongComponents(i);; break; }}}
  
  return tn;
}
Ejemplo n.º 10
0
Matrix2D *GetMatrix2D(MatrixStack2D *ms, size_t num) {
  return (Matrix2D *)StackPeek(ms, num);
}
Ejemplo n.º 11
0
/*
set ip to point to the first symbol of w$;
repeat forever begin
    let s be the state on top of the stack and
        a the symbol pointed to by ip;
    if action[s, a] = shift s' then begin
        push a then s' on top of the stack;
        advance ip to the next input symbol
    end
    else if action[s, a] = reduce A -> B then begin
        pop 2*|B| symbols off the stack;
        let s' be the state now on top of the stack;
        push A then goto[s', A] on top of the stack;
        output the production A -> B
    end
    else if action[s, a] = accept then
        return
    else error()
end
*/
SYNTAX_TREE* ParseSource(L_TOKEN*      input,
                         LR_TABLE      parser,
                         GRAMMAR_TABLE grammar)
{
    // set ip and init stack
    L_TOKEN* ip = input;
    StackPushState(0);
    // printf("Parsing source...\n");
    
    // the program's syntax tree
	SYNTAX_TREE* ast = NULL;

    // loop forever
    for (;;)
    {
        // get the state off the top of the stack
        PARSE_STACK s = StackPeek();
        if (s.token || s.state == -1
                || s.state >= parser.numStates
                || ip == NULL)
        {
            if (ip)
                printf("Parse error: invalid state on top of the stack.\n");
            else
                printf("Parse error: unexpected end of input.\n");
            return 0;
        }
        
        // find the action table entry for the state and input
        ACTION action = ActionTable(parser, s.state, ip->token);

        // perform the parse action
        if (action.type == ACTION_SHIFT)
        {
            // push a then s' on top of the stack;
            StackPushToken(ip);
            StackPushState(action.value);
            // advance ip to the next input symbol
            ip = ip->next;
        }
        else if (action.type == ACTION_REDUCE)
        {
            SYNTAX_TREE* node;
            RULE r;
            int rhs;
            
            // output the production A -> B
            if (action.value < 0 || action.value >= grammar.numRules) {
                printf("Parse error: invalid production for reduce action.\n");
                PrintErrorInput(ip, grammar);
                return 0;
            }
            r = grammar.rules[action.value];
            //printf("%s\n", GetElement(r.lhs, grammar));

            // pop 2*|B| symbols off the stack;
            node = (SYNTAX_TREE*)malloc(sizeof(SYNTAX_TREE));
            node->token = r.lhs;
            node->production = action.value;
            node->string = NULL;
            node->length = 0;
            node->line = 0;
            node->children = (SYNTAX_TREE**)malloc(r.rhsLength * sizeof(SYNTAX_TREE*));
            node->numChildren = r.rhsLength;
            for (rhs = 0; rhs < r.rhsLength; rhs++)
            {
                /*PARSE_STACK state = */ StackPop();
                PARSE_STACK symbol = StackPop();
                if (symbol.token == NULL)
                {
                    printf("Parse error: expected token.\n");
                    PrintErrorInput(ip, grammar);
                    return 0;
                }
                
                int child = r.rhsLength - rhs - 1;
                if (symbol.type == TOKEN_L_TOKEN)
                {
                    L_TOKEN* token = (L_TOKEN*)symbol.token;
                    node->children[child] = (SYNTAX_TREE*)malloc(sizeof(SYNTAX_TREE));
                    node->children[child]->token = token->token;
                    node->children[child]->production = 0;
                    node->children[child]->string = token->string;
                    node->children[child]->length = token->length;
                    node->children[child]->line = token->line;
                    node->children[child]->children = NULL;
                    node->children[child]->numChildren = 0;
                }
                else if (symbol.type == TOKEN_SYNTAX_TREE)
                {
                    node->children[child] = (SYNTAX_TREE*)symbol.token;
                }
                else
                {
                    printf("Parse error: expected token object.\n");
                    PrintErrorInput(ip, grammar);
                }
            }
            if (r.rhsLength) node->line = node->children[0]->line;
                
            // let s' be the state now on top of the stack;
            s = StackPeek();
            if (s.token || s.state == -1 || s.state >= parser.numStates)
            {
                printf("Parse error: expected state on top of stack.\n");
                PrintErrorInput(ip, grammar);
                return 0;
            }
            
            // push A then goto[s', A] on top of the stack;
            if (r.lhs == gSymbolGoal)
            {
                ast = node;
            }
            StackPushTree(node);
            StackPushState(GotoTable(parser, s.state, r.lhs));
        }
        else if (action.type == ACTION_ACCEPT)
        {
            // accept
            // printf("Parse accepted!\n");
            break;
        }
        else
        {
            // error
            printf("Parse error: illegal action type.\n");
            PrintErrorInput(ip, grammar);
            return 0;
        }
    }
    
    // free the stack
    while (gParseStack)
        StackPop();

    // no errors
    return ast;
}
Ejemplo n.º 12
0
/* check if a source is parsable */
int ParseSucceeds(L_TOKEN* input, 
                  LR_TABLE parser, 
                  GRAMMAR_TABLE grammar)
{
    // set ip and init stack
    L_TOKEN* ip = input;
    StackPushState(0);
    
    // the program's syntax tree
	SYNTAX_TREE* ast = NULL;

    int successful = 0;

    // loop forever
    for (;;)
    {
        // get the state off the top of the stack
        PARSE_STACK s = StackPeek();
        if (s.token || s.state == -1
                || s.state >= parser.numStates)
        {
            // error
            successful = -1;
            break;
        }

        if (ip == NULL) {
            successful = 0;
            break;
        }
        
        // find the action table entry for the state and input
        ACTION action = ActionTable(parser, s.state, ip->token);

        // perform the parse action
        if (action.type == ACTION_SHIFT)
        {
            // push a then s' on top of the stack;
            StackPushToken(ip);
            StackPushState(action.value);
            // advance ip to the next input symbol
            ip = ip->next;
        }
        else if (action.type == ACTION_REDUCE)
        {
            SYNTAX_TREE* node;
            RULE r;
            int rhs;
            
            // output the production A -> B
            if (action.value < 0 || action.value >= grammar.numRules) 
            {
                // error, free
                successful = -1;
                break;
            }
            r = grammar.rules[action.value];

            // pop 2*|B| symbols off the stack;
            for (rhs = 0; rhs < r.rhsLength; rhs++)
            {
                StackPop();
                StackPop();
            }
                
            // let s' be the state now on top of the stack;
            s = StackPeek();
            if (s.token || s.state == -1 || s.state >= parser.numStates)
            {
                successful = -1;
                break;
            }
            
            // push A then goto[s', A] on top of the stack;
            StackPushTree(NULL);
            StackPushState(GotoTable(parser, s.state, r.lhs));
        }
        else if (action.type == ACTION_ACCEPT)
        {
            // accept
            successful = 1;
            break;
        }
        else
        {
            // error
            if (ip->token == gSymbolEOF)
                successful = 0;
            else
                successful = -1;
            break;
        }
    }
    
    // free the stack
    while (gParseStack)
        StackPop();

    // no errors
    return successful;
}
Ejemplo n.º 13
0
int InfixToSuffix(ElementType* infix, ElementType* suffix,int len)//中缀表达式转为后缀表达式
{
	int i = 0;
	int j = 0;
	StackNode* sign_head;
	StackNode* sign_top;
	InitStack(&sign_head,&sign_top);
	for (i = 0; i < len; ++i)
	{
		if (infix[i].sign == '\0')//中缀读到数字
		{
			suffix[j++].num = infix[i].num;
		}
		else//中缀读到符号
		{
			if (StackEmpty(sign_top))//符号栈为空
			{
				StackPush(sign_head, &sign_top, infix[i]);
			}
			else if (infix[i].sign == '(')//中缀读到'('
			{
				StackPush(sign_head, &sign_top, infix[i]);
			}
			else if (infix[i].sign == ')')//中缀读到')'
			{
				while (StackPeek(sign_top).sign != '(' && !StackEmpty(sign_top))
				{
					suffix[j++] = StackPop(sign_head, &sign_top);
				}
				if (StackPeek(sign_top).sign == '(' && !StackEmpty(sign_top))
				{
					StackPop(sign_head, &sign_top);
				}
			}
			else if (infix[i].sign == '+' || infix[i].sign == '-')
			{
				ElementType temp;
				temp = StackPeek(sign_top);
				if (temp.sign == '*' || temp.sign == '/')
				{
					while (!StackEmpty(sign_top) && StackPeek(sign_top).sign != '(')
					{
						suffix[j++] = StackPop(sign_head, &sign_top);
					}
					StackPush(sign_head, &sign_top, infix[i]);
				}
				else
				{
					StackPush(sign_head, &sign_top, infix[i]);
				}
			}
			else
			{
				StackPush(sign_head, &sign_top, infix[i]);
			}
		}
	}
	while (!StackEmpty(sign_top))
	{
		suffix[j++] = StackPop(sign_head, &sign_top);
	}
	free(sign_head);
	return j;
}
Ejemplo n.º 14
0
void FuncInstr(){
    VyObj func_obj = StackPeek();
    VyFunction* func = (VyFunction*) Obj(func_obj);
    func->creation_scope = CurrentScope();
}
Ejemplo n.º 15
0
void BindInstr(){
    VyObj name_obj = StackPop();
    VyObj val = StackPeek();
    VySymbol* name = (VySymbol*) Obj(name_obj);
    VariableBind(name, val);
}