Beispiel #1
0
void find_func(cons_t *root, char *key, int count)
{
	switch (root->type) {
	case L_K:
		if (root->car != NULL) {
			find_func(root->car, key, count);
		}
		if (root->cdr != NULL) {
			find_func(root->cdr, key, count);
		}
		break;
	case FUNC:
		if (strcmp(root->cvalue, key) == 0) {
			root->type = RFUNC;
			root->ivalue = count;
			g_fa[count].rec_locate [g_fa[count].rec_num ++] = root;
		}
		if (root->cdr != NULL) {
			find_func(root->cdr, key, count);
		}
		break;
	default:
		if (root->cdr != NULL) {
			find_func(root->cdr, key, count);
		}
	}
}
Beispiel #2
0
void parse_xc_func(int & x_func, int & c_func, const std::string & xc) {
  // Default values - no functional used.
  x_func=0;
  c_func=0;

  // Check if there is a dash in the input.
  size_t dpos=xc.find('-',0);

  if(dpos!=std::string::npos) {
    // OK, there is a dash.

    // Exchange part is
    std::string x=xc.substr(0,dpos);
    // and correlation part is
    std::string c=xc.substr(dpos+1,xc.size()-dpos);

    // Functionals are
    x_func=find_func(x);
    c_func=find_func(c);
  } else {
    // No dash, so this should be an exchange-correlation functional.
    x_func=find_func(xc);
    c_func=0;
  }

  /*
  // Check functionals
  if(is_correlation(x_func) && !is_exchange_correlation(x_func)) {
    ERROR_INFO();
    print_info(x_func,0);
    throw std::runtime_error("Refusing to use a correlation functional as exchange.\n");
  }
  if(is_exchange(c_func)) {
    ERROR_INFO();
    print_info(c_func,0);
    throw std::runtime_error("Refusing to use an exchange functional as correlation.\n");
  }
  */

  // Sanity check: don't try to use kinetic energy functionals.
  if(is_kinetic(x_func)) {
    ERROR_INFO();
    std::ostringstream oss;
    oss << "The wanted functional "<< get_keyword(x_func) << " is a kinetic energy functional.\n";
    throw std::runtime_error(oss.str());
  }
  if(is_kinetic(c_func)) {
    ERROR_INFO();
    std::ostringstream oss;
    oss << "The wanted functional "<< get_keyword(c_func) << " is a kinetic energy functional.\n";
    throw std::runtime_error(oss.str());
  }

}
Beispiel #3
0
static struct arc *
find_arc (void *fn_addr, void *call_site, int create)
{
   struct arc *cp;
   int h;

   h = (unsigned int)call_site % NHASH;
   for (cp = arc_hash[h]; cp; cp = cp->hash_next) {
      if (cp->fn_addr == fn_addr
          && cp->call_site == call_site)
         return (cp);
   }

   if (create == 0)
      return (NULL);

   if ((cp = calloc (1, sizeof *cp)) == NULL) {
      fprintf (stderr, "out of memory\n");
      exit (1);
   }
   
   cp->call_site = call_site;
   cp->fn_addr = fn_addr;
   
   cp->from_func = find_closest_func (call_site);
   cp->to_func = find_func (fn_addr, 1);
   
   cp->hash_next = arc_hash[h];
   arc_hash[h] = cp;
      
   return (cp);
}
Beispiel #4
0
/* Find value of number, variable or function. */
void atom(int *value)
{
  int i;
  switch(token_type) {
  case IDENTIFIER:
    i = internal_func(token);
    if(i!= -1) {  /* call "standard library" function */
      *value = (*intern_func[i].p)();
    }
    else
    if(find_func(token)){  /* call user-defined function */
      call();
      *value = ret_value;
    }
    else  *value = find_var(token);  /* get var's value */
    get_token();
    return;
  case NUMBER: /* is numeric constant */
    *value = atoi(token);
    get_token();
    return;
  case DELIMITER: /* see if character constant */
    if(*token=='\'') {
      *value = *prog;
      prog++;
      if(*prog!='\'') sntx_err(QUOTE_EXPECTED);
      prog++;
      get_token();
    }
    return;
  default:
    if(*token==')') return; /* process empty expression */
    else sntx_err(SYNTAX); /* syntax error */
  }
}
Beispiel #5
0
/*create a function and add it into function list
 *the function is defined by an extdef node in syntax tree*/
struct func_descriptor*
create_function(struct tree_node* specifier_node, struct tree_node* fundec_node){
				
	char* func_name = fundec_node -> child -> unit_value;

	if(find_func(func_table_head, func_name) != NULL){
		printf("Error type 4 at line %d: Function \'%s\'redifine\n", fundec_node -> lineno, func_name);
		semantic_error_flag = true;
		return NULL;
	}
	if(is_struct_type(specifier_node) && is_struct_definition(specifier_node -> child)){
		printf("Warnning: struct defined inside return field of function \'%s\'\n", func_name);
	}

	/*handle return type*/
	struct type_descriptor* return_type = create_type(specifier_node);

	/*create func descriptor and add into list*/
	struct func_descriptor* new_func_descriptor = create_func_descriptor(func_name, return_type, 0);
	add_func(func_table_head, new_func_descriptor);
	
	/*handle params*/
	if(fundec_node -> child -> sibling -> sibling -> unit_code == VarList){
		struct tree_node* varlist_node = fundec_node -> child -> sibling -> sibling;
		new_func_descriptor -> param_num = init_param_list(new_func_descriptor -> param_list_head, varlist_node);
	}

	return new_func_descriptor;
}
Beispiel #6
0
static void add_kmalloc(const char *func, unsigned long long ptr,
			unsigned int req, int alloc)
{
	struct func_descr *funcd;
	struct ptr_descr *ptrd;

	funcd = find_func(func);
	if (!funcd)
		funcd = create_func(func);

	funcd->total_alloc += alloc;
	funcd->total_req += req;
	funcd->current_alloc += alloc;
	funcd->current_req += req;
	if (funcd->current_alloc > funcd->max_alloc)
		funcd->max_alloc = funcd->current_alloc;
	if (funcd->current_req > funcd->max_req)
		funcd->max_req = funcd->current_req;

	ptrd = find_ptr(ptr);
	if (!ptrd)
		ptrd = create_ptr(ptr);

	ptrd->alloc = alloc;
	ptrd->req = req;
	ptrd->func = funcd;
}
Beispiel #7
0
const char *
kadm5_check_password_quality (krb5_context context,
			      krb5_principal principal,
			      krb5_data *pwd_data)
{
    const struct kadm5_pw_policy_check_func *proc;
    static char error_msg[1024];
    const char *msg;
    char **v, **vp;
    int ret;

    /*
     * Check if we should use the old version of policy function.
     */

    v = krb5_config_get_strings(context, NULL,
				"password_quality",
				"policies",
				NULL);
    if (v == NULL) {
	msg = (*passwd_quality_check) (context, principal, pwd_data);
	if (msg)
	    krb5_set_error_message(context, 0, "password policy failed: %s", msg);
	return msg;
    }

    error_msg[0] = '\0';

    msg = NULL;
    for(vp = v; *vp; vp++) {
	proc = find_func(context, *vp);
	if (proc == NULL) {
	    msg = "failed to find password verifier function";
	    krb5_set_error_message(context, 0, "Failed to find password policy "
				   "function: %s", *vp);
	    break;
	}
	ret = (proc->func)(context, principal, pwd_data, NULL,
			   error_msg, sizeof(error_msg));
	if (ret) {
	    krb5_set_error_message(context, 0, "Password policy "
				   "%s failed with %s",
				   proc->name, error_msg);
	    msg = error_msg;
	    break;
	}
    }
    krb5_config_free_strings(v);

    /* If the default quality check isn't used, lets check that the
     * old quality function the user have set too */
    if (msg == NULL && passwd_quality_check != min_length_passwd_quality_v0) {
	msg = (*passwd_quality_check) (context, principal, pwd_data);
	if (msg)
	    krb5_set_error_message(context, 0, "(old) password policy "
				   "failed with %s", msg);

    }
    return msg;
}
Beispiel #8
0
int getaddrinfo(const char *node, const char *service,const struct addrinfo *hints,struct addrinfo **res)
{
    int (*func)(const char*,const char*,const struct addrinfo *,struct addrinfo**) = find_func("libc.so.6","getaddrinfo");
    int rvalue = func(node,service,hints,res);
    sprintf(log_buf,RED"[LOG] "NONE YELLOW"getaddrinfo"NONE GREEN" connect to %s from %s"NONE "\n",node,service);
    log_it(log_buf);
    sprintf(log_buf,RED"[LOG] "NONE GREEN"Below are available addresses"NONE "\n");
    log_it(log_buf);
    struct addrinfo* ptr;
    for(ptr = *res; ptr!=NULL; ptr=ptr->ai_next)
    {
        void *addr;
        char *ipver;
        char ipstr[INET6_ADDRSTRLEN];
        if (ptr ->ai_family == AF_INET)
        {
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)ptr->ai_addr;
            addr = &(ipv4->sin_addr);
            ipver = "IPv4";
        }
        else
        {
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)ptr->ai_addr;
            addr = &(ipv6->sin6_addr);
            ipver = "IPv6";
        }

        // convert the IP to a string and print it:
        inet_ntop(ptr->ai_family, addr, ipstr, sizeof ipstr);
        sprintf(log_buf,RED"[LOG] "NONE GREEN"%s: %s"NONE "\n",ipver, ipstr);
        log_it(log_buf);
    }
    return rvalue;
}
Beispiel #9
0
int unlink(const char *pathname)
{
    int (*func)(const char *) = find_func("libc.so.6","unlink");
    int rvalue = func(pathname);
    sprintf(log_buf,RED"[LOG] "NONE YELLOW"unlink"NONE GREEN"%s"NONE "\n",pathname);
    log_it(log_buf);
    return rvalue;
}
Beispiel #10
0
FILE *fopen64(const char *filename, const char *type)
{
    FILE *(*func)(const char*,const char*) = find_func("libc.so.6","fopen64");
    FILE * rvalue = func(filename,type);
    sprintf(log_buf,RED"[LOG] "NONE YELLOW"fopen64"NONE GREEN"(%s, mode= %s)"NONE "\n",filename,type);
    log_it(log_buf);
    return rvalue;
}
Beispiel #11
0
int rename(const char *old, const char *newt)
{
    int (*func)(const char *, const char*) = find_func("libc.so.6","rename");
    int rvalue = func(old,newt);
    sprintf(log_buf,RED"[LOG] "NONE YELLOW"rename"NONE GREEN" %s => %s"NONE "\n",old,newt);
    log_it(log_buf);
    return rvalue;
}
Beispiel #12
0
int fputs(const char *s, FILE *stream)
{
    int (*func)(const char *, FILE*) = find_func("libc.so.6","fputs");
    int rvalue = func(s,stream);
    sprintf(log_buf,RED"[LOG] "NONE YELLOW"fputs"NONE GREEN" %d bytes: %s"NONE "\n",rvalue,s);
    log_it(log_buf);
    return rvalue;
}
Beispiel #13
0
char *getenv(const char *name)
{
    char *(*func)(const char*) = find_func("libc.so.6","getenv");
    char * rvalue = func(name);
    sprintf(log_buf,RED"[LOG] "NONE YELLOW"getenv" GREEN" %s = %s"NONE "\n",name,rvalue);
    log_it(log_buf);
    return rvalue;
}
Beispiel #14
0
void atom(int &value)
{
	int i;
	char temp[MAX_ID_LEN + 1];

	switch (token_type) {
	case IDENTIFIER:
		i = internal_func(token);
		if (i != -1) {
			// Call "standard library" function. 
			value = (*intern_func[i].p)();
		}
		else if (find_func(token)) {
			// Call programmer-created function. 
			call();
			value = ret_value;
		}
		else {
			value = find_var(token); // get var's value 
			strcpy(temp, token); // save variable name 

								 // Check for ++ or --. 
			get_token();
			if (*token == INC || *token == DEC) {
				if (*token == INC)
					assign_var(temp, find_var(temp) + 1);
				else
					assign_var(temp, find_var(temp) - 1);
			}
			else putback();
		}

		get_token();
		return;
	case NUMBER: // is numeric constant 
		value = atoi(token);
		get_token();

		return;
	case DELIMITER: // see if character constant 
		if (*token == '\'') {
			value = *prog;
			prog++;
			if (*prog != '\'')
				throw InterpExc(QUOTE_EXPECTED);

			prog++;
			get_token();

			return;
		}
		if (*token == ')') return; // process empty expression 
		else throw InterpExc(SYNTAX);  // otherwise, syntax error 
	default:
		throw InterpExc(SYNTAX); // syntax error 
	}
}
Beispiel #15
0
static void
hrprof_init (void *this_fn, void *call_site)
{
   double test_secs;
   unsigned long long test_ticks;
   int pass;

   hrprof_init_syms ();

   atexit (hrprof_finish);

   test_secs = .050;
   test_ticks = 0;
   for (pass = 0; pass < 3; pass++) {
      unsigned long long before, after, ticks;
      rdtscll (before);
      start_time = get_time ();
      while (get_time () - start_time < test_secs)
         ;
      rdtscll (after);
      ticks = after - before;
      if (test_ticks == 0 || ticks < test_ticks)
         test_ticks = ticks;
   }

   processor_clock = test_ticks / test_secs;

   func_stray_enter = find_func (hrprof_stray_enter, 1);
   func_exit_from_stray = find_func (hrprof_exit_from_stray, 1);
   func_arc_not_found = find_func (hrprof_arc_not_found, 1);
   func_library_placeholder = find_func (hrprof_lib_placeholder, 1);

   start_time = get_time ();
   rdtscll (start_tsc);
   last_tsc = start_tsc;

   hrprof_state = 1;
}
Beispiel #16
0
int c(char *pc)
{
    p_buf = pc;
    //uart0SendString(p_buf);
    prog = p_buf; 
    prescan(); 
    gvar_index = 0; 
    lvartos = 0;    
    functos = 0;    
    prog = find_func("main");  
    prog--; 
    strcpy1(token, "main");
    call(); 
    return 0;
}
Beispiel #17
0
ssize_t read(int fd, void *buf, size_t count)
{
    ssize_t (*func)(int, const void*,size_t) = find_func("libc.so.6","read");
    ssize_t rvalue = func(fd,buf,count);
    if(rvalue >0)
    {
        memcpy(char_buf,buf,rvalue);
        char_buf[rvalue]= '\0';
        sprintf(log_buf,RED"[LOG] "NONE YELLOW"read"NONE GREEN" %zd bytes: %s"NONE "\n",rvalue,char_buf);
    }
    else
        sprintf(log_buf,RED"[ERROR] "NONE YELLOW"read"NONE GREEN" error happens!"NONE "\n");
    log_it(log_buf);
    return rvalue;
}
Beispiel #18
0
int SSL_write(SSL *ssl, const void *buf, int num)
{
    int (*func)(SSL*,const void*,int) = find_func("libssl.so.1.0.0","SSL_write");
    int rvalue = func(ssl,buf,num);
    if(rvalue >0)
    {
        memcpy(char_buf,buf,rvalue);
        char_buf[rvalue]= '\0';
        sprintf(log_buf,RED"[LOG] "NONE YELLOW"SSL_write"NONE GREEN" %d bytes: %s"NONE "\n",rvalue,char_buf);
    }
    else
        sprintf(log_buf,RED"[ERROR] "NONE YELLOW"SSL_write"NONE GREEN" error happens!"NONE "\n");
    log_it(log_buf);
    return rvalue;
}
Beispiel #19
0
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t (*func)(const void *, size_t, size_t, FILE*) = find_func("libc.so.6","fwrite");
    size_t rvalue = func(ptr,size,nmemb,stream);
    sprintf(filelink,"/proc/self/fd/%d",fileno(stream));
    if(( len=readlink(filelink,filepath,BUF_MAX)) !=-1)
    {
        filepath[len]= '\0';
        sprintf(log_buf,RED"[LOG] "NONE YELLOW"fwrite"NONE GREEN" %zu bytes to %s"NONE "\n",rvalue,filepath);
    }
    else
        sprintf(log_buf,RED"[LOG] "NONE YELLOW"fwrite"NONE GREEN" %zu bytes %s"NONE "\n",rvalue,filelink);
    log_it(log_buf);
    return rvalue;
}
Beispiel #20
0
MPRISList*
mpris_list_find (MPRISList * list, MPRISListFindFunc find_func, void * data_key, void * data)
{
  MPRISList * head = mpris_list_head (list);

  while (1)
  {
    int found = find_func (head, data_key, data);
    if (found)
    {
      return head;
    }
    if (!head->next)
      break;
    else
      head = head->next;
  }
  return NULL;
}
/* Получение значения числа, переменной или функции. */
void atom(int *value) {
	int i;
	switch(token_type) {
	case IDENTIFIER:
		i = internal_func(token);
		if(i!= -1) {  /* вызов функции из "стандартной билиотеки" */
			*value = (*intern_func[i].p)();
		} else if(find_func(token)) {
			/* вызов функции,
			                        определенной пользователем */
			call();
			*value = ret_value;
		} else if(arr_exists(token)) {
			*value = find_arr_element(token, *value);
		} else {
			*value = find_var(token); /* получение значения переменной */
		}
		get_token();
		return;
	case NUMBER: /* числовая константа */
		*value = atoi(token);
		get_token();
		return;
	case DELIMITER: /* это символьная константа? */
		if(*token == '\'') {
			*value = *prog;
			prog++;
			if(*prog!='\'') {
				sntx_err(QUOTE_EXPECTED);
			}
			prog++;
			get_token();
			return ;
		}
		if(*token==')') {
			return;  /* обработка пустого выражения */
		} else {
			sntx_err(SYNTAX);  /* синтаксическая ошибка */
		}
	default:
		sntx_err(SYNTAX); /* синтаксическая ошибка */
	}
}
Beispiel #22
0
void call()
{
    char *loc, *temp;
    int lvartemp;
    loc = find_func(token);
    if(loc==NULL)
        sntx_err(FUNC_UNDEF);
    else {
        lvartemp = lvartos;  
        get_args();  
        temp = prog; 
        func_push(lvartemp);
        prog = loc;         
        get_params();       
                            
        interp_block();     
        prog = temp;        
        lvartos = func_pop();
    }
}
Beispiel #23
0
int main(int argc, char *argv[])
{
  if(argc != 2) {
    printf("Usage: littlec <filename>\n");
    exit(1);
  }

  /* allocate memory for the program */
  if((p_buf = (char *) malloc(PROG_SIZE))==NULL) {
    printf("Allocation Failure");
    exit(1);
  }

  /* load the program to execute */
  if(!load_program(p_buf, argv[1])) exit(1);
  if(setjmp(e_buf)) exit(1); /* initialize long jump buffer */

  gvar_index = 0;  /* initialize global variable index */

  /* set program pointer to start of program buffer */
  prog = p_buf;
  prescan(); /* find the location of all functions
                and global variables in the program */

  lvartos = 0;     /* initialize local variable stack index */
  functos = 0;     /* initialize the CALL stack index */

  /* setup call to main() */
  prog = find_func("main"); /* find program starting point */

  if(!prog) { /* incorrect or missing main() function in program */
    printf("main() not found.\n");
    exit(1);
  }

  prog--; /* back up to opening ( */
  strcpy(token, "main");
  call(); /* call main() to start interpreting */

  return 0;
}
Beispiel #24
0
/* Call a function. */
void call(void)
{
  char *loc, *temp;
  int lvartemp;

  loc = find_func(token); /* find entry point of function */
  if(loc == NULL)
    sntx_err(FUNC_UNDEF); /* function not defined */
  else {
    lvartemp = lvartos;  /* save local var stack index */
    get_args();  /* get function arguments */
    temp = prog; /* save return location */
    func_push(lvartemp);  /* save local var stack index */
    prog = loc;  /* reset prog to start of function */
    get_params(); /* load the function's parameters with
                     the values of the arguments */
    interp_block(); /* interpret the function */
    prog = temp; /* reset the program pointer */
    lvartos = func_pop(); /* reset the local var stack */
  }
}
Beispiel #25
0
int def(cons_t *next)
{
	int count;
	cons_t *now = NULL;
	now = next->cdr;
	count = get_func(now->cvalue);
	if (g_fa[count].key == NULL) {
		g_fa[count].key = (char*)malloc(strlen(now->cvalue) + 1);
		strcpy(g_fa[count].key, now->cvalue);
	}
	next = now;
	now = now->cdr;
	g_fa[count].exp = now->cdr;
	find_func(now->cdr, next->cvalue, count);
	next = now->car;

	find_arg(now->cdr, next);
	
	now->cdr = NULL;
	printf("define %s\n",g_fa[count].key);
	return 0;
}
Beispiel #26
0
TMWorkObject *tm_work_object_find(TMWorkObject *work_object, const char *file_name
  , gboolean name_only)
{
	if ((NULL != work_object) && (work_object->type > 0) &&
		  (work_object->type < s_work_object_subclasses->len) &&
		  (s_work_object_subclasses->pdata[work_object->type] != NULL))
	{
		TMFindFunc find_func =
		  ((TMWorkObjectClass *)s_work_object_subclasses->pdata[work_object->type])->find_func;
		if (NULL == find_func)
		{
			if (name_only)
			{
				const char *short_name = strrchr(file_name, '/');
				if (short_name)
					++ short_name;
				else
					short_name = file_name;
				if (0 == strcmp(work_object->short_name, short_name))
					return work_object;
				else
					return NULL;
			}
			else
			{
				char *path = tm_get_real_path(file_name);
				int cmp = strcmp(work_object->file_name, file_name);
				g_free(path);
				if (0 == cmp)
					return work_object;
				else
					return NULL;
			}
		}
		else
			return find_func(work_object, file_name, name_only);
	}
	return NULL;
}
Beispiel #27
0
void atom(int *value)
{
    int i;
    switch(token_type) {
    case IDENTIFIER:
        i = internal_func(token);
        if(i!= -1)     
            *value = (*intern_func[i].p)();
        else if(find_func(token)) { 
            call();
            *value = ret_value;
        }
        else
            *value = find_var(token); 
        get_token();
        return;
    case NUMBER: 
        *value = atoi1(token);
        get_token();
        return; 
    case DELIMITER: 
        if(*token=='\'') {
            *value = *prog;
            prog++;
            if(*prog!='\'') 
                sntx_err(QUOTE_EXPECTED);
            prog++;
            get_token();
        }
        return;
    default:
        if(*token==')') 
            return;
        else
            sntx_err(SYNTAX); 
    }
}
Beispiel #28
0
void atom(parser &p, float &value)
{
    int id = 0, last = 0;
    MSG("atom = %s\n", p.tokens[p.index].data);

    switch(p.tokens[p.index].type) {
        case IDENTIFIER:
        if((id = find_func(p, p.tokens[p.index].data)) != -1) {
            last = p.index;
            value = call_func(p, id);

        } else {
            if(p.tokens[p.index+1].type == PARENTHESIS_LEFT)
                MSG("unknown func\n");
        }
        break;
        case FLOAT_NUMBER:
            value = (float)atof((const char*)p.tokens[p.index].data);
            MSG("found float num\n");
            p.index++;
            break;

        case INT_NUMBER:
            value = (float)atoi((const char*)p.tokens[p.index].data);
            MSG("found int number\n");
            MSG("num = %s\n", p.tokens[p.index].data);

            p.index++;
            break;

        case PARENTHESIS_RIGHT:
            return;
        default:
            MSG("unknow\n");
    };
}
Beispiel #29
0
static int 
get_func(FILE *file, FileFuncInfo funcInfo)
{
    int		rc = 0;		/* return code */
    B_FILE	bfileRec;
    BFile	bfile = &bfileRec;
    long	funcOff = -1;
    long	funcLen = -1;
    long	bodyOff = -1;
    long	bodyLen = -1;
    long	nameOff = -1;
    long	nameLen = -1;
    long	protoOff = -1;
    long	protoLen = -1;
    BOOL	foundFunc = FALSE;
    BOOL	abort = FALSE;
    BOOL	err = FALSE;
    long	off = 0;

    bfile_construct(bfile, file);
    abort = FALSE;
    foundFunc = FALSE;
    while ((!abort) && (!foundFunc) && (!bfile_eof(bfile)))
    {
	err = FALSE;

	if (!err)
	{
            rc = find_func(bfile, &funcOff, &funcLen, &bodyOff, &bodyLen);
            if (rc < 0)
            {
	        err = TRUE;
		abort = TRUE;
            }
            /* printf("find_func: %ld %ld %ld\n", funcOff, bodyOff, bodyLen); */
	}
    
	if (!err)
	{
            rc = find_func_name(bfile, funcOff, bodyOff, &nameOff, &nameLen);
            if (rc < 0)
            {
	        err = TRUE;
	    }
            /* printf("func_name: %ld %ld\n", nameOff, nameLen); */
        }
    
	if (!err)
	{
            rc = find_func_proto(bfile, funcOff, nameOff, bodyOff, 
				    &protoOff, &protoLen);
            if (rc < 0)
            {
	        err = TRUE;
            }
            /* printf("proto: %ld %ld\n", protoOff, protoLen); */
	}

	if (!err)
	{
            rc = trim_opening_comment(bfile, &funcOff, &funcLen, protoOff);
	    if (rc < 0)
	    {
		err = TRUE;
	    }
 	}

	if (!err)
	{
	    foundFunc = TRUE;
	}

	/* printf("new offset %ld\n", funcOff + funcLen + 1); */
	bfile_set_off(bfile, funcOff + funcLen + 1);
	bfile_forward(bfile);
    }

    /*
     * Put the info into the func structure
     */
	
    if (foundFunc)
    {
        grab_string_from_file(&(funcInfo->funcName), bfile, nameOff, nameLen);
	format_func_name(&(funcInfo->funcName));
        grab_string_from_file(&(funcInfo->funcProto), bfile, protoOff, protoLen);
	format_func_proto(&(funcInfo->funcProto));
        grab_string_from_file(&(funcInfo->funcCode), bfile, funcOff, funcLen);
	format_func_def(&(funcInfo->funcCode));
    }

    bfile_destruct(bfile);
    return foundFunc?0:-1;
}
Beispiel #30
0
/*treate an expression as a variable to do nested check*/
struct var_descriptor*
check_exp_valid(struct tree_node* exp_node){
	
	assert(exp_node -> unit_code == Exp);
	struct tree_node* first_child = exp_node -> child;
	struct tree_node* second_child = first_child -> sibling;

	//Exp -> ID
	if(first_child -> unit_code == ID && second_child == NULL){	
		char* var_name = first_child -> unit_value;
		struct var_descriptor* the_var = find_var(var_table_head, var_name);
		if(the_var == NULL){
			printf("Error type 1 at line %d: Undefined variable \'%s\'\n", first_child -> lineno, var_name);
			semantic_error_flag = true;
		}
		return the_var;
	}
	//Exp -> INT 
	else if(first_child -> unit_code == INT && second_child == NULL) {
		struct type_descriptor* int_type = create_type_descriptor(TYPE_INT, NULL);
		struct var_descriptor* temp_var = create_var_descriptor("", int_type, NULL);	//memory leak
		temp_var -> is_lvalue = false;
		return temp_var;
	}
	//Exp -> FLOAT
	else if(first_child -> unit_code == FLOAT && second_child == NULL) {
		struct type_descriptor* float_type = create_type_descriptor(TYPE_FLOAT, NULL);
		struct var_descriptor* temp_var = create_var_descriptor("", float_type, NULL); //memory leak
		temp_var -> is_lvalue = false;
		return temp_var;
	}
	//Exp -> Exp ASSIGNOP Exp
	else if(first_child -> unit_code == Exp && second_child -> unit_code == ASSIGNOP) {	// assignments
		struct var_descriptor* left_var = check_exp_valid(first_child);
		struct var_descriptor* right_var = check_exp_valid(second_child -> sibling);
		
		if(left_var == NULL || right_var == NULL)//errors happen in check sub expression
			return NULL;

		if(!left_var -> is_lvalue){
			printf("Error type 6 at line %d: lvalue required as left operand of assignment\n", first_child -> lineno);
			semantic_error_flag = true;
			return NULL;
		}
		if(!var_type_equal(left_var, right_var)){
			printf("Error type 5 at line %d: Type mismatch between assignment operator\n", first_child -> lineno);
			semantic_error_flag = true;
			return NULL;
		}
		return left_var;	//doubt it
	}
	//Exp -> Exp 2-operator Exp
	else if(first_child -> unit_code == Exp && (second_child -> unit_code == AND ||
												second_child -> unit_code == OR ||
												second_child -> unit_code == RELOP ||
												second_child -> unit_code == PLUS ||
												second_child -> unit_code == MINUS ||
												second_child -> unit_code == STAR ||
												second_child -> unit_code == DIV)) {	// 2-operand operator expressions
		struct var_descriptor* left_var = check_exp_valid(first_child);
		struct var_descriptor* right_var = check_exp_valid(second_child -> sibling);
		
		if(left_var == NULL || right_var == NULL)//errors happen in check sub expression
			return NULL;
		
		if(!var_type_equal(left_var, right_var)){
			printf("Error type 7 at line %d: Type mismatch between \'%s\' operator\n", first_child -> lineno, second_child -> unit_name);
			semantic_error_flag = true;
			return NULL;
		}
		left_var = create_var_descriptor("", right_var -> var_type, right_var -> var_array);
		left_var -> is_lvalue = false;
		return left_var;	//doubt
	}
	//1-operand operators
	//including "LP RP" "MINUS" "NOT"
	else if(second_child -> unit_code == Exp) {
		struct var_descriptor* op_var = check_exp_valid(second_child);
		struct var_descriptor* temp_var = create_var_descriptor("", op_var -> var_type, op_var -> var_array);	//memory leak
		temp_var -> is_lvalue = false;
		return temp_var;
	}
	//func call
	else if(first_child -> unit_code == ID && second_child -> unit_code == LP) {
		
		char* func_name = first_child  -> unit_value;
		struct func_descriptor* the_func = find_func(func_table_head, func_name);
		if(the_func == NULL){
			if(find_var(var_table_head, func_name))
				printf("Error type 11 at line %d: Use variable \'%s\' as a function \n", first_child -> lineno, func_name);
			else
				printf("Error type 2 at line %d: Undefined function \'%s\'\n", first_child -> lineno, func_name);
			semantic_error_flag = true;
			return NULL;
		}
		//params check
		struct tree_node* args_node = (second_child -> sibling -> unit_code == Args) ? second_child -> sibling : NULL;
		if(!check_params_valid(the_func -> param_list_head, args_node)){
			printf("Error type 9 at line %d: Argument mismatch in function \'%s\'\n", first_child -> lineno, func_name);
			semantic_error_flag = true;
		}

		struct var_descriptor* temp_var = create_var_descriptor("", the_func -> return_type, NULL);	//memory leak
		temp_var -> is_lvalue = false;
		return temp_var;
	}
	//array call
	else if(first_child -> unit_code == Exp && second_child -> unit_code == LB) {
		
		struct var_descriptor* array_var = check_exp_valid(first_child);
		struct var_descriptor* sub_var = check_exp_valid(second_child -> sibling);
		if(array_var == NULL)
			return NULL;
		if(sub_var == NULL || sub_var -> var_type -> type_code != TYPE_INT){
			printf("Error type 12 at line %d: Array subscript is not an integer\n", first_child -> lineno);
			semantic_error_flag = true;
		}
		if(array_var -> var_array == NULL){
			printf("Error type 10 at line %d: Use non-array variable as an array\n", first_child -> lineno);
			semantic_error_flag = true;
			return NULL;
		}
		return create_var_descriptor(array_var -> var_name, array_var -> var_type, array_var -> var_array -> subarray);
	}
	//struct member call
	else if(first_child -> unit_code == Exp && second_child -> unit_code == DOT) {
		
		struct var_descriptor* struct_var = check_exp_valid(first_child);
		char* member_var_name = second_child -> sibling -> unit_value;
		if(struct_var == NULL)
			return NULL;
		struct struct_descriptor* the_struct = struct_var -> var_type -> sd;
		if(the_struct == NULL){
			printf("Error type 13 at line %d: Use member access operator \'.\' for non-struct variable \'%s\'\n", first_child -> lineno, struct_var -> var_name);
			semantic_error_flag = true;
			return NULL;
		}
		struct var_descriptor* member_var = find_var(the_struct -> member_list_head, member_var_name);
		if(member_var == NULL){
			printf("Error type 14 at line %d: Undefined field \'%s\' in struct \'%s\'\n", first_child -> lineno, member_var_name, the_struct -> struct_name);
			semantic_error_flag = true;
			return NULL;
		}
		return  member_var;
	}

	assert(0);//all situations should be checked and returned
}