int find_ht(node_type* ptr)
{		/* Auxilliary Function for finding height*/
	int htr,htl,ht=-1;
	if(ptr!=NULL)
	{
		htl=find_ht(ptr->left);
		htr=find_ht(ptr->right);
		if(htl>htr)		/* Height of Left Subtree is greater*/
		{
			ht=htl+1;	
		}
		else		/* Height of Right Subtree is greater*/
		{
			ht=htr+1;	
		}
	}
	return ht;
}
Example #2
0
DFA read_dfa(const char *filename, Hashtable ht, char symbols[][25], int *num)
{
	//reads DFA from specified file, updates info about the terminals
	FILE *fp = fopen(filename,"r");
	if(fp==NULL){
		printf("File %s could not be opened\n",filename);
		exit(0);
	}
	DFA d;
	fscanf(fp,"%d\n",&(d.num_states));
	fscanf(fp,"%d\n",&(d.start_state));
	int i, num_terminals = 1;
	for(i=1;i<=d.num_states;i++){
		//info about each state
		// state_no <space> final?(Y/N) <space> token(if final) <space> backtrack? (Y/N, if final)
		int s_no;
		char temp[25], tok[25];
		fscanf(fp,"%d %s",&s_no,temp);
		if(!strcmp(temp,"N")){
			d.is_final[s_no] = 0;
		}
		else d.is_final[s_no] = 1;
		if(d.is_final[s_no]){
			fscanf(fp, "%s %s",tok,temp);
			strcpy(d.tok[s_no],tok);
			if(find_ht(ht,tok)==-1){
				strcpy(symbols[num_terminals], tok);
				insert_ht(ht,tok,num_terminals++);
			}
			if(!strcmp(temp,"N")){
				d.to_backtrack[s_no] = 0;
			}
			else d.to_backtrack[s_no] = 1;
		}
	}
	memset(d.transitions,-1,sizeof(d.transitions)); //if not specified -> invalid
	//info about transitions - one per line till EOF
	//from_state <space> to_state <space> range of chars (eg. a z)

	char r1[10], r2[10];
	int t1, t2;
	while(!feof(fp)){
		fscanf(fp,"%d %d %s",&t1,&t2,r1);
		if(!strcmp(r1,"others")){
			int i;
			for(i=0;i<128;i++){
				if(d.transitions[t1][i] == -1)
					d.transitions[t1][i] = t2;
			}
		}
		else{
			fscanf(fp,"%s",r2);
			if(!strcmp(r1,"sp"))
				r1[0] = ' ';
			if(!strcmp(r2,"sp"))
				r2[0] = ' ';

			int i;
			for(i=r1[0];i<=r2[0];i++){
				d.transitions[t1][i] = t2;
			}
		}
	}

	*num = num_terminals;
	fclose(fp);
	return d;
}