static void json_spells(cJSON *json) { cJSON *child; if (json->type != cJSON_Object) { log_error("spells is not a json object: %d", json->type); return; } for (child = json->child; child; child = child->next) { if (child->type == cJSON_Object) { spell *sp; cJSON * item = cJSON_GetObjectItem(child, "index"); sp = create_spell(child->string, item ? item->valueint : 0); for (item = child->child; item; item = item->next) { if (strcmp(item->string, "index") == 0) { continue; } else if (strcmp(item->string, "cast") == 0) { sp->cast = (spell_f)get_function(item->valuestring); } else if (strcmp(item->string, "fumble") == 0) { sp->fumble = (fumble_f)get_function(item->valuestring); } else if (strcmp(item->string, "syntax") == 0) { sp->syntax = _strdup(item->valuestring); } } } } }
void fetch_data(void *handle, const char *db) { uint32_t bufsize = 1024; size_t struct_size; int32_t errnop; if (strncmp(db,"pw", 2) == 0) struct_size = sizeof(struct passwd); else if (strncmp(db,"gr", 2) == 0) struct_size = sizeof(struct group); else return; char setent[] = "_nss_ldap_setXXent"; char getent[] = "_nss_ldap_getXXent_r"; char endent[] = "_nss_ldap_endXXent"; /* replace XX's */ strncpy(setent+13, db, 2); strncpy(getent+13, db, 2); strncpy(endent+13, db, 2); setXXent_t ldap_setent = get_function(handle, setent); getXXent_t ldap_getent_r = get_function(handle, getent); endXXent_t ldap_endent = get_function(handle, endent); void *data = malloc(struct_size); void *buf = malloc(bufsize); ldap_setent(); while (ldap_getent_r(data, buf, bufsize, &errnop)) { if (errnop == ERANGE) { buf = realloc(buf, bufsize<<=1); errnop = 0; continue; } if (strncmp(db,"pw", 2) == 0) { struct passwd *pw = (struct passwd*) data; printf("%s:%s:%d:%d:%s:%s:%s\n", pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid, pw->pw_gecos, pw->pw_dir, pw->pw_shell); } if (strncmp(db,"gr", 2) == 0) { struct group *grp = (struct group*) data; printf("%s:%d:", grp->gr_name, grp->gr_gid); uint32_t i = 0; while (grp->gr_mem[i]) { if (i > 0) putchar(','); printf(grp->gr_mem[i++]); } putchar('\n'); } } ldap_endent(); free(data); free(buf); }
static void match_ns_capable(const char *fn, struct expression *expr, void *_param) { struct expression *arg; sval_t sval; char buf[32]; if (get_function() && strcmp(get_function(), "capable") == 0) return; arg = get_argument_from_call_expr(expr->args, 1); if (!get_implied_value(arg, &sval)) return; snprintf(buf, sizeof(buf), "%s", sval_to_str(sval)); set_state(ns_capable_id, buf, NULL, &capable); }
void SundialsInterface::init_memory(void* mem) const { Integrator::init_memory(mem); auto m = static_cast<SundialsMemory*>(mem); // Allocate n-vectors m->xz = N_VNew_Serial(nx_+nz_); m->q = N_VNew_Serial(nq_); m->rxz = N_VNew_Serial(nrx_+nrz_); m->rq = N_VNew_Serial(nrq_); // Reset linear solvers linsolF_.reset(get_function("jacF").sparsity_out(0)); if (nrx_>0) { linsolB_.reset(get_function("jacB").sparsity_out(0)); } }
void profile_in(glui32 addr, glui32 stackuse, int accel) { frame_t *fra; function_t *func; struct timeval now; if (!profiling_active) return; /* printf("### IN: %lx%s\n", addr, (accel?" accel":"")); */ if (profiling_call_counts && current_frame) { function_t *parfunc = current_frame->func; callcount_t **ccref; for (ccref = &parfunc->outcalls; *ccref; ccref = &((*ccref)->next)) { if ((*ccref)->toaddr == addr) break; } if (*ccref) { (*ccref)->count += 1; } else { *ccref = glulx_malloc(sizeof(callcount_t)); (*ccref)->toaddr = addr; (*ccref)->count = 1; (*ccref)->next = NULL; } } gettimeofday(&now, NULL); func = get_function(addr); func->call_count += 1; if (accel) func->accel_count += 1; if (!func->entry_depth) { func->entry_start_time = now; func->entry_start_op = profile_opcount; } func->entry_depth += 1; if (func->max_stack_use < stackuse) func->max_stack_use = stackuse; fra = (frame_t *)glulx_malloc(sizeof(frame_t)); if (!fra) fatal_error("Profiler: cannot malloc frame."); memset(fra, 0, sizeof(frame_t)); fra->parent = current_frame; current_frame = fra; if (fra->parent) fra->depth = fra->parent->depth + 1; fra->func = func; fra->entry_time = now; fra->entry_op = profile_opcount; timerclear(&fra->children_time); fra->children_ops = 0; }
int main (int argc, char *argv[]) { void * lib = NULL; int (*fun) (); struct compiler * compiler; int rc = EXIT_FAILURE; char prog[] = "int foo () { return 42; }"; compiler = compiler_get_gcc (); if (comp_failed == compile_from_string (compiler, prog, libname)) goto out; if (! (lib = load_library (libname))) goto out; fun = (int (*) ()) get_function (lib, funcname); if (!fun) goto out; printf ("function '%s' from '%s' returned '%d'\n", funcname, libname, fun ()); out: if (lib) if (close_library (lib)) rc = EXIT_SUCCESS; return rc; }
void profile_in(glui32 addr, int accel) { frame_t *fra; function_t *func; struct timeval now; /* printf("### IN: %lx%s\n", addr, (accel?" accel":"")); */ gettimeofday(&now, NULL); func = get_function(addr); func->call_count += 1; if (accel) func->accel_count += 1; if (!func->entry_depth) { func->entry_start_time = now; func->entry_start_op = profile_opcount; } func->entry_depth += 1; fra = (frame_t *)glulx_malloc(sizeof(frame_t)); if (!fra) fatal_error("Profiler: cannot malloc frame."); memset(fra, 0, sizeof(frame_t)); fra->parent = current_frame; current_frame = fra; fra->func = func; fra->entry_time = now; fra->entry_op = profile_opcount; timerclear(&fra->children_time); fra->children_ops = 0; }
std::string source_locationt::as_string(bool print_cwd) const { std::string dest; const irep_idt &file=get_file(); const irep_idt &line=get_line(); const irep_idt &column=get_column(); const irep_idt &function=get_function(); if(!file.empty()) { if(dest!="") dest+=' '; dest+="file "; if(print_cwd) dest+=concat_dir_file(id2string(get_working_directory()), id2string(file)); else dest+=id2string(file); } if(!line.empty()) { if(dest!="") dest+=' '; dest+="line "+id2string(line); } if(!column.empty()) { if(dest!="") dest+=' '; dest+="column "+id2string(column); } if(!function.empty()) { if(dest!="") dest+=' '; dest+="function "+id2string(function); } return dest; }
int main(const int argc, const char* argv[]) { if (argc < 2) { fprintf(stderr, "specify the problem number\n"); exit(EXIT_FAILURE); } uint32_t pnum; if (!sscanf(argv[1], "%u", &pnum)) { fprintf(stderr, "could not parse problem number\n"); exit(EXIT_FAILURE); } void (*pfunc)() = get_function(pnum); if (!pfunc) { fprintf(stderr, "problem %d not implemented\n", pnum); exit(EXIT_FAILURE); } clock_t start = clock(); pfunc(); unsigned int runtime_ms = (1000 * (clock() - start)) / CLOCKS_PER_SEC; fprintf(stderr, "Runtime(ms): %u\n", runtime_ms); exit(EXIT_SUCCESS); }
void SundialsInterface::set_work(void* mem, const double**& arg, double**& res, int*& iw, double*& w) const { auto m = static_cast<SundialsMemory*>(mem); // Set work in base classes Integrator::set_work(mem, arg, res, iw, w); // Work vectors m->p = w; w += np_; m->rp = w; w += nrp_; m->v1 = w; w += max(nx_+nz_, nrx_+nrz_); m->v2 = w; w += max(nx_+nz_, nrx_+nrz_); m->jac = w; w += get_function("jacF").nnz_out(0); if (nrx_>0) { m->jacB = w; w += get_function("jacB").nnz_out(0); } }
bool add_performance_data_metric(const std::string metric) { boost::function<std::string(log_summary*)> f = get_function(metric); if (f) { metrics[metric] = boost::bind(f,this); return true; } return false; }
int is_silenced_function(void) { char *func; func = get_function(); if (!func) return 0; if (search_func(silenced_funcs, func)) return 1; return 0; }
static action_t cont_list() { ref_t sym = check_symbol(car(expr)); expr = cdr(expr); if (sym == sym_do) eval_do(expr); else if (sym == sym_fn) C(cont)->fn = cont_fn; else if (sym == sym_if) C(cont)->fn = cont_if; else if (sym == sym_quote) C(cont)->fn = cont_quote; else eval_apply(get_function(sym)); return ACTION_APPLY_CONT; }
static action_t cont_macroexpand1() { if (iscons(expr)) { ref_t symbol = check_symbol(car(expr)); if (has_function(symbol)) { ref_t func = get_function(symbol); if (ismacro(func)) { C(cont)->fn = cont_apply_apply, C(cont)->val[0] = func; expr = cdr(expr); return ACTION_APPLY_CONT; } } } pop_cont(); return ACTION_APPLY_CONT; }
Z3_lbool z3_find_one_discr_function(const clone *clone1_basis, const clone *clone1, const clone *clone2, uint32_t fun_arity, fun *fun) { z3_wrapper z3; z3_wrapper_init(&z3); gen_assert_discr_fun_two_clones(&z3, clone1_basis, clone1, clone2, fun_arity); Z3_lbool rc = Z3_solver_check(z3.ctx, z3.solver); if(rc == Z3_L_TRUE) { get_function(&z3, z3.fun, fun_arity, fun); } z3_wrapper_free(&z3); return rc; }
std::string locationt::as_string() const { std::string dest; const irep_idt &file=get_file(); const irep_idt &line=get_line(); const irep_idt &column=get_column(); const irep_idt &function=get_function(); if(file!="") { if(dest!="") dest+=" "; dest+="file "+id2string(file); } if(line!="") { if(dest!="") dest+=" "; dest+="line "+id2string(line); } if(column!="") { if(dest!="") dest+=" "; dest+="column "+id2string(column); } if(function!="") { if(dest!="") dest+=" "; dest+="function "+id2string(function); } return dest; }
void top_obj_parse(struct s* s) { struct symbol *sym = get_function(s); if(strstr(sym->function_name, "plt")) { nb_plt++; } else { nb_non_plt++; struct symbol *ob = get_object(s); struct dyn_lib* ob3 = sample_to_mmap(s); char *obj = NULL; if(ob) obj = ob->object_name; if(!obj && strstr(sym->function_name, "@plt")) obj = sym->function_name; if(!obj && !strcmp(sym->function_name, "[vdso]")) obj = sym->function_name; if(!obj && ob3) obj = ob3->name; struct value *value = rbtree_lookup(r, obj, cmp); if(!value) { value = calloc(1, sizeof(*value)); value->from_accesses = calloc(max_node, sizeof(*value->from_accesses)); value->to_accesses = calloc(max_node, sizeof(*value->to_accesses)); rbtree_insert(r, obj, value, cmp); } value->accesses++; value->dist_accesses += is_distant(s); value->from_accesses[cpu_to_node(s->cpu)]++; value->to_accesses[get_addr_node(s)]++; if(ob) { value->dist_by_allocator += (is_distant(s) && (get_tid(s) == ob->allocator_tid)); value->dist_by_allocator_remote_cpu += (is_distant(s) && (get_tid(s) == ob->allocator_tid) && (ob->allocator_cpu != s->cpu)); value->dist_by_allocator_alloc_cpu += (is_distant(s) && (get_tid(s) == ob->allocator_tid) && (ob->allocator_cpu == s->cpu)); value->dist_for_obj += (is_distant(s)); value->by_allocator += ((get_tid(s) == ob->allocator_tid)); value->by_everybody += ((get_tid(s) != ob->allocator_tid)); value->by_allocator_before_everybody += (value->by_everybody == 0); value->uid = ob->uid; } nb_total_access++; } }
static void json_building(cJSON *json, building_type *bt) { cJSON *child; const char *flags[] = { "nodestroy", "nobuild", "unique", "decay", "dynamic", "magic", "oneperturn", "namechange", "fort", 0 }; if (json->type != cJSON_Object) { log_error("building %s is not a json object: %d", json->string, json->type); return; } for (child = json->child; child; child = child->next) { switch (child->type) { case cJSON_Array: if (strcmp(child->string, "construction") == 0) { json_construction(child, &bt->construction); } else if (strcmp(child->string, "maintenance") == 0) { json_maintenance(child, &bt->maintenance); } else if (strcmp(child->string, "flags") == 0) { json_flags(child, flags); } break; case cJSON_Object: if (strcmp(child->string, "construction") == 0) { json_construction(child, &bt->construction); } else if (strcmp(child->string, "maintenance") == 0) { json_maintenance(child, &bt->maintenance); } break; case cJSON_String: if (strcmp(child->string, "name") == 0) { bt->name = (const char *(*)(const struct building_type *, const struct building *, int))get_function(child->valuestring); break; } log_error("building %s contains unknown attribute %s", json->string, child->string); break; default: log_error("building %s contains unknown attribute %s", json->string, child->string); } } }
/*---------------------------------------------------------------------*/ void bglpth_setup_bmem() { void *hdl; char bigloothread_lib[ 1000 ]; static void (*____bglthread_setup_bmem)(); bmem_thread = 2; /* Hello world */ fprintf( stderr, "Bmem Pthread initialization...\n" ); if( getenv( "BMEMLIBBIGLOOTHREAD" ) ) { strcpy( bigloothread_lib, getenv( "BMEMLIBBIGLOOTHREAD" ) ); } else { sprintf( bigloothread_lib, "%s/libbigloopth_s-%s.%s", LIBRARY_DIRECTORY, BGL_RELEASE_NUMBER, SHARED_LIB_SUFFIX ); } fprintf( stderr, "Loading thread library %s...\n", bigloothread_lib ); hdl = open_shared_library( bigloothread_lib ); ____bglthread_setup_bmem = (void (*)())get_function( hdl, "bglpth_setup_bmem" ); ____bglthread_new = (void *(*)( void * ))get_function( hdl, "bglpth_thread_new" ); ____pthread_getspecific = get_function( hdl, "bglpth_pthread_getspecific" ); ____pthread_setspecific = (int (*)())get_function( hdl, "bglpth_pthread_setspecific" ); ____pthread_key_create = (int (*)())get_function( hdl, "bglpth_pthread_key_create" ); ____pthread_mutex_init = (int (*)())get_function( hdl, "bglpth_pthread_mutex_init" ); if( ____pthread_key_create( &bmem_key, 0L ) ) { FAIL( IDENT, "Can't get thread key", "bmem_key" ); exit( -2 ); } if( ____pthread_mutex_init( &bmem_mutex, 0L ) ) { FAIL( IDENT, "Can't get thread key", "bmem_key" ); exit( -2 ); } ____bglthread_setup_bmem(); bmem_init(); }
static float factor(void) { float number; if (is_function_token(sym)) { token function_sym = sym; accept(sym); expect(T_LEFT_BANANA); function func = get_function(function_sym); number = func(expression()); expect(T_RIGHT_BANANA); } else if (sym == T_NUMBER) { number = tokenizer_get_number(); accept(T_NUMBER); } else if (accept(T_LEFT_BANANA)) { number = expression(); expect(T_RIGHT_BANANA); } else { error("Factor: syntax error"); get_sym(); } return number; }
static int use_item_callback(unit *u, const item_type *itype, int amount, struct order *ord) { int len; char fname[64]; len = snprintf(fname, sizeof(fname), "use_%s", itype->rtype->_name); if (len > 0 && (size_t)len < sizeof(fname)) { int result; int(*callout)(unit *, const item_type *, int, struct order *); /* check if we have a register_item_use function */ callout = (int(*)(unit *, const item_type *, int, struct order *))get_function(fname); if (callout) { return callout(u, itype, amount, ord); } /* check if we have a matching lua function */ result = lua_use_item(u, itype, fname, amount, ord); if (result != 0) { return result; } /* if the item is a potion, try use_potion, the generic function for * potions that add an effect: */ if (itype->flags & ITF_POTION) { return use_potion(u, itype, amount, ord); } else { log_error("no such callout: %s", fname); } log_error("use(%s) calling '%s': not a function.\n", unitname(u), fname); } return 0; }
ParseNode gen_vardef(const ParseNode & type_spec, const ParseNode & variable_desc, const ParseNode & paramtable) { ParseNode newnode = ParseNode(); string arr_decl = ""; string var_decl = ""; bool do_arr = false; VariableDescAttr * vardescattr = dynamic_cast<VariableDescAttr *>(variable_desc.attr); ParseNode * slice = vardescattr->desc.slice; ParseNode * spec_typename = promote_type(type_spec, vardescattr); // reset type according to kind if (slice == nullptr) { // slice == nullptr if this is not array /* must assure no ParseNode * is nullptr */ slice = new ParseNode(gen_flex(Term{ TokenMeta::NT_VOID, "" }), nullptr); } else { do_arr = true; } newnode.addchild(spec_typename); // type newnode.addchild(slice); // variable_desc ParseNode * pn = new ParseNode(gen_promote_paramtable(paramtable)); newnode.addchild(pn); // paramtable newnode.attr = new VariableDescAttr(*dynamic_cast<VariableDescAttr *>(variable_desc.attr)); // attr if (do_arr) { // ARRAY arr_decl = gen_vardef_array(pn, spec_typename, slice, vardescattr); newnode.fs.CurrentTerm = Term{ TokenMeta::NT_VARIABLEDEFINE, arr_decl }; } else { // SCALAR sprintf(codegen_buf, gen_vardef_typestr(vardescattr).c_str(), spec_typename->fs.CurrentTerm.what.c_str()); string typestr = string(codegen_buf); var_decl += typestr; bool hitted = false; // 是否至少有一个变量,因为有的变量定义可能是函数的声明,这在c++规范是不允许的,所以可能出现空int,空逗号的情况。 /* enumerate paramtable */ // pn is flattened for (int i = 0; i < pn->child.size(); i++) { ParseNode * this_variable = new ParseNode(*pn->child[i]); // skip if it is a function // TODO no module currently if (get_function("", this_variable->fs.CurrentTerm.what)) { continue; } if (hitted) { var_decl += ", "; } hitted = true; sprintf(codegen_buf, "%s", this_variable->child[0]->fs.CurrentTerm.what.c_str()); var_decl += codegen_buf; /* initial value */ if (this_variable->child[1]->fs.CurrentTerm.token != TokenMeta::NT_VARIABLEINITIALDUMMY) { /* if initial value is not dummy but `exp` */ var_decl += " = "; var_decl += this_variable->child[1]->fs.CurrentTerm.what; } /* desc */ this_variable->attr = vardescattr->clone(); } var_decl += ";"; if (!hitted) { // all function declarations var_decl = ""; } newnode.fs.CurrentTerm = Term{ TokenMeta::NT_VARIABLEDEFINE, var_decl }; } // end if // set all elements' attr in paramtable for (int i = 0; i < pn->child.size(); i++) { pn->child[i]->attr = newnode.attr->clone(); } return newnode; }
/* archive file (*.a) loading test */ int main() { int ret; int symnum; bfd* abfd; asymbol** syms; int symbol_pos, symbol_size; int index; #ifndef OBJ_TEST const char* file = "foo.a"; #else const char* file = "hello.o"; #endif unsigned char* file_o; file_o = load_file(file); abfd = bfd_openr(file, NULL); assert(abfd); ret = bfd_check_format(abfd, bfd_archive); //ret = bfd_check_format(abfd, bfd_object); assert(ret); #ifndef OBJ_TEST bfd* b = NULL; #else bfd* b = abfd;//NULL; #endif link_list_t* bfds = NULL; STEP_LOG("create function map\n"); #ifndef OBJ_TEST while(NULL != (b = bfd_openr_next_archived_file(abfd, b))) #endif { ret = bfd_check_format(b, bfd_object); assert(ret); // STEP_LOG("next\n"); if (!(bfd_get_file_flags(b) & HAS_SYMS)) { assert(bfd_get_error() == bfd_error_no_error); /* no symbol */ bfd_close(abfd); return 1; } if (NULL == bfds) { LOG("Add first:0x%08X\n", (int)b); bfds = add_item(bfds, &b, sizeof(b)); } else { LOG("Add bfd:0x%08X\n", (int)b); add_item(bfds, &b, sizeof(b)); } get_symbols(&syms, &symnum, b); create_symbol_function_pos(file_o, b, syms, symnum); } STEP_LOG("relocate function addresses\n"); link_list_t* list = bfds; while(NULL != list) { b = *(bfd**)(list->item); get_symbols(&syms, &symnum, b); reloc_file(file_o, b, syms); list = list->next; } STEP_LOG("try to get function addressses\n"); int (*func)(); void (*func1)(const char*); func = NULL; func1 = NULL; list = bfds; while(NULL != list) { b = *(bfd**)(list->item); LOG("bfd:0x%08X\n", (int)b); LOG("call goodby...."); get_symbols(&syms, &symnum, b); symbol_pos = get_symbol_pos("goodby", b, syms, symnum, file_o); if (0 != symbol_pos) { func = (int (*) ())(get_function(symbol_pos)); } LOG("call hello_someone...."); symbol_pos = get_symbol_pos("hello_someone", b, syms, symnum, file_o); if (0 != symbol_pos) { func1 = (void (*) (const char*))(get_function(symbol_pos)); } if (NULL != func && NULL != func1) break; list = list->next; } STEP_LOG("try to call functions\n"); if (NULL != func) { func(); } else { LOG("failed to call func\n"); } if (NULL != func1) { func1("WORLD!"); } else { LOG("failed to call func\n"); } delete_all_items(bfds); free(syms); bfd_close(abfd); free(file_o); return 0; }
bool check_funcall(struct funcall *f, struct symtable *syms, struct type **res) { if (strcmp(f->fun_ident, "allouer") == 0) { if (f->args.size == 1) { if(!check_expr(f->args.data[0]->e, syms)) { *res = NULL; return false; } } *res = NULL; return true; } else if (((strcmp(f->fun_ident, "ecrire") == 0) && current_lang == LANG_FR) || ((strcmp(f->fun_ident, "write") == 0) && current_lang == LANG_EN)) { for (unsigned i = 0; i < f->args.size; ++i) { if (!check_expr(f->args.data[i]->e, syms)) { *res = NULL; return false; } } *res = NULL; return true; } else if (strcmp(f->fun_ident, "lire") == 0) { if(f->args.size != 1 && f->args.data[0]->e->exprtype != identtype && !find_var(syms->variables, f->args.data[0]->e->val.ident)) { *res = NULL; return false; } f->args.data[0]->e->type = strdup(find_var( syms->variables, f->args.data[0]->e->val.ident)->type->name); *res = NULL; return true; } else if (strcmp(f->fun_ident, "liberer") == 0) { if (f->args.size == 1) { if (!check_expr(f->args.data[0]->e, syms)) { *res = NULL; return false; } *res = NULL; return true; } else { error(f->pos, "liberer expects one argument, not %d", f->args.size); *res = NULL; return false; } } struct function *proto = get_function(syms->functions, f->fun_ident); if (!proto) { error(f->pos, "implicit declaration of function %s", f->fun_ident); *res = NULL; return false; } else if (proto->arg.size != f->args.size) { error(f->pos, "function %s expects %d arguments but %d were given", f->fun_ident, proto->arg.size, f->args.size); *res = NULL; return false; } else { bool ok = true; for (unsigned i = 0; i < proto->arg.size; ++i) { char *argtype = check_expr(f->args.data[i]->e, syms); if (argtype) { if (!equal_types(proto->arg.data[i]->type->name, argtype, syms)) { error(f->pos, "wrong type for argument %d in function %s", i + 1, f->fun_ident); ok = false; } else if (proto->arg.data[i]->global) { if (f->args.data[i]->e->exprtype == valtype) { error(f->args.data[i]->e->pos, "cannot pass a value as a global parameter"); ok = false; } else f->args.data[i]->global = true; } } } if (ok) *res = proto->ret; } return true; }
int gpio_get_raw_function(struct udevice *dev, int offset, const char **namep) { return get_function(dev, offset, false, namep); }
int main() { setup_classes(); // c = C() pyobj c = create_object(C); // d = D() pyobj d = create_object(D); // TODO: call the __init__ method if it exists #ifdef TAGGING pyobj one = inject_int(1); pyobj three = inject_int(3); #else pyobj one = create_int(1); pyobj three = create_int(3); #endif // c.f = 1 set_attr(c, "f", one); // d.f = 1 set_attr(d, "f", one); pyobj i, j, k, h; // i = c.m() { pyobj meth = get_attr(c, "m"); pyobj fun = get_function(meth); void *fp = get_fun_ptr(fun); pyobj (*f)(pyobj) = (pyobj (*)(pyobj)) fp; // cast to a function pointer type i = f(get_receiver(meth)); } // j = d.m() { pyobj meth = get_attr(d, "m"); pyobj fun = get_function(meth); void *fp = get_fun_ptr(fun); pyobj (*f)(pyobj) = (pyobj (*)(pyobj)) fp; // cast to a function pointer type j = f(get_receiver(meth)); } // d.n(3) { pyobj (*f)(pyobj, pyobj) = (pyobj (*)(pyobj, pyobj)) get_fun_ptr_from_attr(d, "n"); f(d, three); } // k = d.m() { pyobj meth = get_attr(d, "m"); pyobj fun = get_function(meth); void *fp = get_fun_ptr(fun); pyobj (*f)(pyobj) = (pyobj (*)(pyobj)) fp; // cast to a function pointer type k = f(get_receiver(meth)); } // h = i + j + k { #ifdef TAGGING // optimized, but assumes i and j are integers // h = i + j + k // unoptimized, but checks that i and j are integers h = inject_int(project_int(i) + project_int(j) + project_int(k)); #else h = create_int(project_int(i) + project_int(j) + project_int(k)); #endif } // print i, j, k print_any(i); print_any(j); print_any(k); print_any(h); return 0; }
ReturnType invoke(const std::unique_ptr<Type>& obj, const std::string& class_name, const std::string& function_name, Params... params) { auto reflectable = find_reflectable(class_name); auto fct = reflectable->get_function(function_name); return fct.template invoke<Type, ReturnType, Params...>(obj, params...); }
int main(int argc, char **argv) { struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"legal", no_argument, NULL, 'l'}, {"verbose", no_argument, NULL, 'v'}, {"quiet", no_argument, NULL, 'q'}, {"repl", no_argument, NULL, 'r'}, {"static-fns", no_argument, NULL, 's'}, {"elide-asserts", no_argument, NULL, 'a'}, {"cache", required_argument, NULL, 'k'}, {"eval", required_argument, NULL, 'e'}, {"theme", required_argument, NULL, 't'}, {"classpath", required_argument, NULL, 'c'}, {"auto-cache", no_argument, NULL, 'K'}, {"init", required_argument, NULL, 'i'}, {"main", required_argument, NULL, 'm'}, // development options {"javascript", no_argument, NULL, 'j'}, {"out", required_argument, NULL, 'o'}, {0, 0, 0, 0} }; int opt, option_index; while ((opt = getopt_long(argc, argv, "h?lvrsak:je:t:c:o:Ki:qm:", long_options, &option_index)) != -1) { switch (opt) { case 'h': usage(argv[0]); exit(0); case 'l': legal(); return 0; case 'v': verbose = true; break; case 'q': quiet = true; break; case 'r': repl = true; break; case 's': static_fns = true; break; case 'a': elide_asserts = true; break; case 'k': cache_path = argv[optind - 1]; break; case 'K': cache_path = ".planck_cache"; { char *path_copy = strdup(cache_path); char *dir = dirname(path_copy); if (mkdir_p(dir) < 0) { fprintf(stderr, "Could not create %s: %s\n", cache_path, strerror(errno)); } free(path_copy); } break; case 'j': javascript = true; break; case 'e': num_scripts += 1; scripts = realloc(scripts, num_scripts * sizeof(struct script)); scripts[num_scripts - 1].type = "text"; scripts[num_scripts - 1].expression = true; scripts[num_scripts - 1].source = argv[optind - 1]; break; case 'i': num_scripts += 1; scripts = realloc(scripts, num_scripts * sizeof(struct script)); scripts[num_scripts - 1].type = "path"; scripts[num_scripts - 1].expression = false; scripts[num_scripts - 1].source = argv[optind - 1]; break; case 'm': main_ns_name = argv[optind - 1]; case 't': theme = argv[optind - 1]; break; case 'c': { char *classpath = argv[optind - 1]; char *source = strtok(classpath, ":"); while (source != NULL) { char *type = "src"; if (str_has_suffix(source, ".jar") == 0) { type = "jar"; } num_src_paths += 1; src_paths = realloc(src_paths, num_src_paths * sizeof(struct src_path)); src_paths[num_src_paths - 1].type = type; src_paths[num_src_paths - 1].path = strdup(source); source = strtok(NULL, ":"); } break; } case 'o': out_path = argv[optind - 1]; break; case '?': usage(argv[0]); exit(1); default: printf("unhandled argument: %c\n", opt); } } int num_rest_args = 0; char **rest_args = NULL; if (optind < argc) { num_rest_args = argc - optind; rest_args = malloc((argc - optind) * sizeof(char*)); int i = 0; while (optind < argc) { rest_args[i++] = argv[optind++]; } } if (num_scripts == 0 && main_ns_name == NULL && num_rest_args == 0) { repl = true; } if (main_ns_name != NULL && repl) { printf("Only one main-opt can be specified."); } JSGlobalContextRef ctx = JSGlobalContextCreate(NULL); JSStringRef nameRef = JSStringCreateWithUTF8CString("planck"); JSGlobalContextSetName(ctx, nameRef); evaluate_script(ctx, "var global = this;", "<init>"); register_global_function(ctx, "AMBLY_IMPORT_SCRIPT", function_import_script); bootstrap(ctx, out_path); register_global_function(ctx, "PLANCK_CONSOLE_LOG", function_console_log); register_global_function(ctx, "PLANCK_CONSOLE_ERROR", function_console_error); evaluate_script(ctx, "var console = {};"\ "console.log = PLANCK_CONSOLE_LOG;"\ "console.error = PLANCK_CONSOLE_ERROR;", "<init>"); evaluate_script(ctx, "var PLANCK_VERSION = \"" PLANCK_VERSION "\";", "<init>"); // require app namespaces evaluate_script(ctx, "goog.require('planck.repl');", "<init>"); // without this things won't work evaluate_script(ctx, "var window = global;", "<init>"); register_global_function(ctx, "PLANCK_READ_FILE", function_read_file); register_global_function(ctx, "PLANCK_LOAD", function_load); register_global_function(ctx, "PLANCK_LOAD_DEPS_CLJS_FILES", function_load_deps_cljs_files); register_global_function(ctx, "PLANCK_CACHE", function_cache); register_global_function(ctx, "PLANCK_EVAL", function_eval); register_global_function(ctx, "PLANCK_GET_TERM_SIZE", function_get_term_size); register_global_function(ctx, "PLANCK_PRINT_FN", function_print_fn); register_global_function(ctx, "PLANCK_PRINT_ERR_FN", function_print_err_fn); register_global_function(ctx, "PLANCK_SET_EXIT_VALUE", function_set_exit_value); is_tty = isatty(STDIN_FILENO) == 1; register_global_function(ctx, "PLANCK_RAW_READ_STDIN", function_raw_read_stdin); register_global_function(ctx, "PLANCK_RAW_WRITE_STDOUT", function_raw_write_stdout); register_global_function(ctx, "PLANCK_RAW_FLUSH_STDOUT", function_raw_flush_stdout); register_global_function(ctx, "PLANCK_RAW_WRITE_STDERR", function_raw_write_stderr); register_global_function(ctx, "PLANCK_RAW_FLUSH_STDERR", function_raw_flush_stderr); { JSValueRef arguments[num_rest_args]; for (int i = 0; i < num_rest_args; i++) { arguments[i] = c_string_to_value(ctx, rest_args[i]); } JSValueRef args_ref = JSObjectMakeArray(ctx, num_rest_args, arguments, NULL); JSValueRef global_obj = JSContextGetGlobalObject(ctx); JSStringRef prop = JSStringCreateWithUTF8CString("PLANCK_INITIAL_COMMAND_LINE_ARGS"); JSObjectSetProperty(ctx, JSValueToObject(ctx, global_obj, NULL), prop, args_ref, kJSPropertyAttributeNone, NULL); JSStringRelease(prop); } evaluate_script(ctx, "cljs.core.set_print_fn_BANG_.call(null,PLANCK_PRINT_FN);", "<init>"); evaluate_script(ctx, "cljs.core.set_print_err_fn_BANG_.call(null,PLANCK_PRINT_ERR_FN);", "<init>"); char *elide_script = str_concat("cljs.core._STAR_assert_STAR_ = ", elide_asserts ? "false" : "true"); evaluate_script(ctx, elide_script, "<init>"); free(elide_script); { JSValueRef arguments[4]; arguments[0] = JSValueMakeBoolean(ctx, repl); arguments[1] = JSValueMakeBoolean(ctx, verbose); JSValueRef cache_path_ref = NULL; if (cache_path != NULL) { JSStringRef cache_path_str = JSStringCreateWithUTF8CString(cache_path); cache_path_ref = JSValueMakeString(ctx, cache_path_str); } arguments[2] = cache_path_ref; arguments[3] = JSValueMakeBoolean(ctx, static_fns); JSValueRef ex = NULL; JSObjectCallAsFunction(ctx, get_function(ctx, "planck.repl", "init"), JSContextGetGlobalObject(ctx), 4, arguments, &ex); debug_print_value("planck.repl/init", ctx, ex); } if (repl) { evaluate_source(ctx, "text", "(require '[planck.repl :refer-macros [apropos dir find-doc doc source pst]])", true, false, "cljs.user", "dumb"); } evaluate_script(ctx, "goog.provide('cljs.user');", "<init>"); evaluate_script(ctx, "goog.require('cljs.core');", "<init>"); evaluate_script(ctx, "cljs.core._STAR_assert_STAR_ = true;", "<init>"); // Process init arguments for (int i = 0; i < num_scripts; i++) { // TODO: exit if not successfull evaluate_source(ctx, scripts[i].type, scripts[i].source, scripts[i].expression, false, NULL, theme); } // Process main arguments if (main_ns_name != NULL) { run_main_in_ns(ctx, main_ns_name, num_rest_args, rest_args); } else if (!repl && num_rest_args > 0) { char *path = rest_args[0]; struct script script; if (strcmp(path, "-") == 0) { char *source = read_all(stdin); script.type = "text"; script.source = source; script.expression = false; } else { script.type = "path"; script.source = path; script.expression = false; } evaluate_source(ctx, script.type, script.source, script.expression, false, NULL, theme); } else if (repl) { if (!quiet) { banner(); } char *home = getenv("HOME"); char *history_path = NULL; if (home != NULL) { char history_name[] = ".planck_history"; int len = strlen(home) + strlen(history_name) + 2; history_path = malloc(len * sizeof(char)); snprintf(history_path, len, "%s/%s", home, history_name); linenoiseHistoryLoad(history_path); } char *prompt = javascript ? " > " : " => "; char *line; while ((line = linenoise(prompt)) != NULL) { if (javascript) { JSValueRef res = evaluate_script(ctx, line, "<stdin>"); print_value("", ctx, res); } else { evaluate_source(ctx, "text", line, true, true, "cljs.user", theme); } linenoiseHistoryAdd(line); if (history_path != NULL) { linenoiseHistorySave(history_path); } free(line); } } return exit_value; }
int is_function(char *token, int len) { int i; return get_function(token, len) != NULL; }
void BonminInterface::init(const Dict& opts) { // Call the init method of the base class Nlpsol::init(opts); // Default options pass_nonlinear_variables_ = true; pass_nonlinear_constraints_ = true; Dict hess_lag_options, jac_g_options, grad_f_options; std::vector< std::vector<int> > sos1_groups; std::vector< std::vector<double> > sos1_weights; // Read user options for (auto&& op : opts) { if (op.first=="bonmin") { opts_ = op.second; } else if (op.first=="pass_nonlinear_variables") { pass_nonlinear_variables_ = op.second; } else if (op.first=="pass_nonlinear_constraints") { pass_nonlinear_constraints_ = op.second; } else if (op.first=="var_string_md") { var_string_md_ = op.second; } else if (op.first=="var_integer_md") { var_integer_md_ = op.second; } else if (op.first=="var_numeric_md") { var_numeric_md_ = op.second; } else if (op.first=="con_string_md") { con_string_md_ = op.second; } else if (op.first=="con_integer_md") { con_integer_md_ = op.second; } else if (op.first=="con_numeric_md") { con_numeric_md_ = op.second; } else if (op.first=="hess_lag_options") { hess_lag_options = op.second; } else if (op.first=="jac_g_options") { jac_g_options = op.second; } else if (op.first=="grad_f_options") { grad_f_options = op.second; } else if (op.first=="hess_lag") { Function f = op.second; casadi_assert_dev(f.n_in()==4); casadi_assert_dev(f.n_out()==1); set_function(f, "nlp_hess_l"); } else if (op.first=="jac_g") { Function f = op.second; casadi_assert_dev(f.n_in()==2); casadi_assert_dev(f.n_out()==2); set_function(f, "nlp_jac_g"); } else if (op.first=="grad_f") { Function f = op.second; casadi_assert_dev(f.n_in()==2); casadi_assert_dev(f.n_out()==2); set_function(f, "nlp_grad_f"); } else if (op.first=="sos1_groups") { sos1_groups = to_int(op.second.to_int_vector_vector()); for (auto & g : sos1_groups) { for (auto & e : g) e-= GlobalOptions::start_index; } } else if (op.first=="sos1_weights") { sos1_weights = op.second.to_double_vector_vector(); } else if (op.first=="sos1_priorities") { sos1_priorities_ = to_int(op.second.to_int_vector()); } } // Do we need second order derivatives? exact_hessian_ = true; auto hessian_approximation = opts_.find("hessian_approximation"); if (hessian_approximation!=opts_.end()) { exact_hessian_ = hessian_approximation->second == "exact"; } // Setup NLP functions create_function("nlp_f", {"x", "p"}, {"f"}); create_function("nlp_g", {"x", "p"}, {"g"}); if (!has_function("nlp_grad_f")) { create_function("nlp_grad_f", {"x", "p"}, {"f", "grad:f:x"}); } if (!has_function("nlp_jac_g")) { create_function("nlp_jac_g", {"x", "p"}, {"g", "jac:g:x"}); } jacg_sp_ = get_function("nlp_jac_g").sparsity_out(1); // By default, assume all nonlinear nl_ex_.resize(nx_, true); nl_g_.resize(ng_, true); // Allocate temporary work vectors if (exact_hessian_) { if (!has_function("nlp_hess_l")) { create_function("nlp_hess_l", {"x", "p", "lam:f", "lam:g"}, {"hess:gamma:x:x"}, {{"gamma", {"f", "g"}}}); } hesslag_sp_ = get_function("nlp_hess_l").sparsity_out(0); if (pass_nonlinear_variables_) { const casadi_int* col = hesslag_sp_.colind(); for (casadi_int i=0;i<nx_;++i) nl_ex_[i] = col[i+1]-col[i]; } } else { if (pass_nonlinear_variables_) nl_ex_ = oracle_.which_depends("x", {"f", "g"}, 2, false); } if (pass_nonlinear_constraints_) nl_g_ = oracle_.which_depends("x", {"g"}, 2, true); // Create sos info // Declare size sos_num_ = sos1_groups.size(); // sos1 type sos1_types_.resize(sos_num_, 1); casadi_assert(sos1_weights.empty() || sos1_weights.size()==sos_num_, "sos1_weights has incorrect size"); casadi_assert(sos1_priorities_.empty() || sos1_priorities_.size()==sos_num_, "sos1_priorities has incorrect size"); if (sos1_priorities_.empty()) sos1_priorities_.resize(sos_num_, 1); sos_num_nz_ = 0; for (casadi_int i=0;i<sos_num_;++i) { // get local group const std::vector<int>& sos1_group = sos1_groups[i]; // Get local weights std::vector<double> default_weights(sos1_group.size(), 1.0); const std::vector<double>& sos1_weight = sos1_weights.empty() ? default_weights : sos1_weights[i]; casadi_assert(sos1_weight.size()==sos1_group.size(), "sos1_weights has incorrect size"); // Populate lookup vector sos1_starts_.push_back(sos_num_nz_); sos_num_nz_+=sos1_group.size(); sos1_weights_.insert(sos1_weights_.end(), sos1_weight.begin(), sos1_weight.end()); sos1_indices_.insert(sos1_indices_.end(), sos1_group.begin(), sos1_group.end()); } sos1_starts_.push_back(sos_num_nz_); // Allocate work vectors alloc_w(nx_, true); // xk_ alloc_w(nx_, true); // lam_xk_ alloc_w(ng_, true); // gk_ alloc_w(nx_, true); // grad_fk_ alloc_w(jacg_sp_.nnz(), true); // jac_gk_ if (exact_hessian_) { alloc_w(hesslag_sp_.nnz(), true); // hess_lk_ } }