/* * Show object types that have been defined. */ void showobjtypes(void) { STRINGHEAD *hp; OBJECTACTIONS *oap; STRINGHEAD *ep; int index, i; hp = &objectnames; ep = &elements; if (hp->h_count == 0) { printf("No object types defined\n"); return; } for (index = 0; index < hp->h_count; index++) { oap = objects[index]; printf("\t%s\t{", namestr(&objectnames, index)); for (i = 0; i < oap->oa_count; i++) { if (i) printf(","); printf("%s", namestr(ep, oap->oa_elements[i])); } printf("}\n"); } }
/* * Show the list of user defined functions. */ void showfunctions(void) { FUNC *fp; /* current function */ long count; long index; count = 0; if (funccount > 0) { if (conf->resource_debug & RSCDBG_FUNC_INFO) math_str("Index\tName \tArgs\tOpcodes\n" "-----\t------ \t---- \t------\n"); else math_str("Name\tArguments\n" "----\t---------\n"); for (index = 0; index < funccount; index++) { fp = functions[index]; if (conf->resource_debug & RSCDBG_FUNC_INFO) { math_fmt("%5ld\t%-12s\t", index, namestr(&funcnames,index)); if (fp) { count++; math_fmt("%-5d\t%-5ld\n", fp->f_paramcount, fp->f_opcodecount); } else { math_str("null\t0\n"); } } else { if (fp == NULL) continue; count++; math_fmt("%-12s\t%-2d\n", namestr(&funcnames, index), fp->f_paramcount); } } } if (conf->resource_debug & RSCDBG_FUNC_INFO) { math_fmt("\nNumber non-null: %ld\n", count); math_fmt("Number null: %ld\n", funccount - count); math_fmt("Total number: %ld\n", funccount); } else { if (count > 0) math_fmt("\nNumber: %ld\n", count); else math_str("No user functions defined\n"); } }
/* * Initialize a function for definition. * Newflag is TRUE if we should allocate a new function structure, * instead of the usual overwriting of the template function structure. * The new structure is returned in the global curfunc variable. * * given: * name name of function * newflag TRUE if need new structure */ void beginfunc(char *name, BOOL newflag) { register FUNC *fp; /* current function */ newindex = adduserfunc(name); maxopcodes = OPCODEALLOCSIZE; fp = functemplate; if (newflag) { fp = (FUNC *) malloc(funcsize(maxopcodes)); if (fp == NULL) { math_error("Cannot allocate temporary function"); /*NOTREACHED*/ } } fp->f_next = NULL; fp->f_localcount = 0; fp->f_opcodecount = 0; fp->f_savedvalue.v_type = V_NULL; fp->f_savedvalue.v_subtype = V_NOSUBTYPE; newname = namestr(&funcnames, newindex); fp->f_name = newname; curfunc = fp; initlocals(); initlabels(); oldop = OP_NOP; oldoldop = OP_NOP; debugline = 0; errorcount = 0; }
/* * Free memory used to store function and its constants */ void freefunc(FUNC *fp) { long index; unsigned long i; if (fp == NULL) return; if (fp == curfunc) { index = newindex; } else { for (index = 0; index < funccount; index++) { if (functions[index] == fp) break; } if (index == funccount) { math_error("Bad call to freefunc!!!"); /*NOTREACHED*/ } } if (newname[0] != '*' && (conf->traceflags & TRACE_FNCODES)) { printf("Freeing function \"%s\"\n",namestr(&funcnames,index)); dumpnames = FALSE; for (i = 0; i < fp->f_opcodecount; ) { printf("%ld: ", i); i += dumpop(&fp->f_opcodes[i]); } } freenumbers(fp); if (fp != functemplate) free(fp); }
SummarizingMetric(const char * name, T initial_value, bool reg_new = true) : impl::MetricBase(name, reg_new) , initial_value(initial_value) , value_(initial_value) , n(0) // TODO: this assumes initial_value is not actually a value , mean(initial_value) , M2(0) , min(std::numeric_limits<T>::max()) , max(std::numeric_limits<T>::min()) { #ifdef VTRACE_SAMPLED if (SummarizingMetric::vt_type == -1) { LOG(ERROR) << "warning: VTrace sampling unsupported for this type of SummarizingMetric."; } else { std::string namestr( name ); std::string countstr = namestr + "_count"; std::string meanstr = namestr + "_mean"; std::string stddevstr = namestr + "_stddev"; vt_counter_value = VT_COUNT_DEF(name, name, SummarizingMetric::vt_type, VT_COUNT_DEFGROUP); vt_counter_count = VT_COUNT_DEF(countstr.c_str(), countstr.c_str(), VT_COUNT_TYPE_UNSIGNED, VT_COUNT_DEFGROUP); vt_counter_mean = VT_COUNT_DEF(meanstr.c_str(), meanstr.c_str(), VT_COUNT_TYPE_DOUBLE, VT_COUNT_DEFGROUP); vt_counter_stddev = VT_COUNT_DEF(stddevstr.c_str(), stddevstr.c_str(), VT_COUNT_TYPE_DOUBLE, VT_COUNT_DEFGROUP); } #endif }
/// \brief Get the function address of the wrapper of the destructor. void* Value::GetDtorWrapperPtr(const clang::RecordDecl* RD) const { std::string funcname; { llvm::raw_string_ostream namestr(funcname); namestr << "__cling_StoredValue_Destruct_" << RD; } // Check whether the function exists before calling // utils::TypeName::GetFullyQualifiedName which is expensive // (memory-wise). See ROOT-6909. std::string code; if (!m_Interpreter->getAddressOfGlobal(funcname)) { code = "extern \"C\" void "; clang::QualType RDQT(RD->getTypeForDecl(), 0); std::string typeName = utils::TypeName::GetFullyQualifiedName(RDQT, RD->getASTContext()); std::string dtorName = RD->getNameAsString(); code += funcname + "(void* obj){((" + typeName + "*)obj)->~" + dtorName + "();}"; } // else we have an empty code string - but the function alreday exists // so we'll be fine and take the existing one (ifUniq = true). return m_Interpreter->compileFunction(funcname, code, true /*ifUniq*/, false /*withAccessControl*/); }
static Node *simpucon(Simp *s, Node *n, Node *dst) { Node *tmp, *u, *tag, *elt, *sz; Node *r; Type *ty; Ucon *uc; size_t i; /* find the ucon we're constructing here */ ty = tybase(n->expr.type); uc = NULL; for (i = 0; i < ty->nmemb; i++) { if (!strcmp(namestr(n->expr.args[0]), namestr(ty->udecls[i]->name))) { uc = ty->udecls[i]; break; } } if (!uc) die("Couldn't find union constructor"); if (dst) tmp = dst; else tmp = temp(s, n); /* Set the tag on the ucon */ u = addr(s, tmp, mktype(n->line, Tyuint)); tag = mkintlit(n->line, uc->id); tag->expr.type = mktype(n->line, Tyuint); append(s, set(deref(u), tag)); /* fill the value, if needed */ if (!uc->etype) return tmp; elt = rval(s, n->expr.args[1], NULL); u = addk(u, Wordsz); if (stacktype(uc->etype)) { elt = addr(s, elt, uc->etype); sz = disp(n->line, tysize(uc->etype)); r = mkexpr(n->line, Oblit, u, elt, sz, NULL); } else { r = set(deref(u), elt); } append(s, r); return tmp; }
static Ucon *finducon(Node *n) { size_t i; Type *t; Ucon *uc; t = tybase(n->expr.type); if (exprop(n) != Oucon) return NULL; for (i = 0; i < t->nmemb; i++) { uc = t->udecls[i]; if (!strcmp(namestr(uc->name), namestr(n->expr.args[0]))) return uc; } die("No ucon?!?"); return NULL; }
static Dtree *addstruct(Dtree *t, Node *pat, Node *val, Node ***cap, size_t *ncap) { Node *elt, *memb; Type *ty; size_t i, j; if (t->any) return t->any; for (i = 0; i < pat->expr.nargs; i++) { elt = pat->expr.args[i]; for (j = 0; j < t->nval; j++) { if (!strcmp(namestr(elt->expr.idx), namestr(t->val[j]->expr.idx))) { ty = exprtype(pat->expr.args[i]); memb = structmemb(val, elt->expr.idx, ty); t = addpat(t, pat->expr.args[i], memb, cap, ncap); break; } } } return t; }
char *dtnodestr(Node *n) { switch (exprop(n)) { case Ovar: return namestr(n->expr.args[0]); case Olit: return litstr[n->expr.args[0]->lit.littype]; case Oucon: return namestr(n->expr.args[0]); case Otup: return "tuple"; case Oarr: return "array"; case Ostruct: return "struct"; case Ogap: return "_"; default: die("Invalid pattern in exhaustivenes check. BUG."); break; } return "???"; }
/* gets the byte offset of 'memb' within the aggregate type 'aggr' */ static size_t offset(Node *aggr, Node *memb) { Type *ty; Node **nl; size_t i; size_t off; ty = tybase(exprtype(aggr)); if (ty->type == Typtr) ty = tybase(ty->sub[0]); assert(ty->type == Tystruct); nl = ty->sdecls; off = 0; for (i = 0; i < ty->nmemb; i++) { off = tyalign(off, size(nl[i])); if (!strcmp(namestr(memb), declname(nl[i]))) return off; off += size(nl[i]); } die("Could not find member %s in struct", namestr(memb)); return -1; }
/* * Print the elements of an object in short and unambiguous format. * This is the default routine if the user's is not defined. * * given: * op object being printed */ S_FUNC void objprint(OBJECT *op) { int count; /* number of elements */ int i; /* index */ count = op->o_actions->oa_count; math_fmt("obj %s {", namestr(&objectnames, op->o_actions->oa_index)); for (i = 0; i < count; i++) { if (i) math_str(", "); printvalue(&op->o_table[i], PRINT_SHORT | PRINT_UNAMBIG); } math_chr('}'); }
static void checkundef(Node *n, Reaching *r, Bitset *reach, Bitset *kill) { size_t i, j, did; Node *def; Type *t; if (n->type != Nexpr) return; if (exprop(n) == Ovar) { did = n->expr.did; for (j = 0; j < r->ndefs[did]; j++) { t = tybase(exprtype(n)); if (t->type == Tystruct || t->type == Tyunion || t->type == Tyarray || t->type == Tytuple) continue; if (bshas(kill, r->defs[did][j])) continue; if (!bshas(reach, r->defs[did][j])) continue; def = nodes[r->defs[did][j]]; if (exprop(def) == Oundef) fatal(n, "%s used before definition", namestr(n->expr.args[0])); } } else { switch (exprop(n)) { case Oset: case Oasn: case Oblit: checkundef(n->expr.args[1], r, reach, kill); break; case Oaddr: case Oslice: /* these don't actually look at the of args[0], so they're ok. */ for (i = 1; i < n->expr.nargs; i++) checkundef(n->expr.args[i], r, reach, kill); break; case Ocall: for (i = 1; i < n->expr.nargs; i++) if (exprop(n->expr.args[i]) != Oaddr) checkundef(n->expr.args[i], r, reach, kill); break; default: for (i = 0; i < n->expr.nargs; i++) checkundef(n->expr.args[i], r, reach, kill); break; } } }
void process_workgroup_announce(struct subnet_record *subrec, struct packet_struct *p, char *buf) { struct dgram_packet *dgram = &p->packet.dgram; int ttl = IVAL(buf,1)/1000; char *workgroup_announce_name = buf+5; uint32 servertype = IVAL(buf,23); char *master_name = buf+31; struct work_record *work; char *source_name = dgram->source_name.name; master_name[43] = 0; DEBUG(3,("process_workgroup_announce: from %s<%02x> IP %s to \ %s for workgroup %s.\n", source_name, source_name[15], inet_ntoa(p->ip), namestr(&dgram->dest_name),workgroup_announce_name)); DEBUG(5,("process_workgroup_announce: ttl=%d server type=%08x master browser=%s\n", ttl, servertype, master_name)); /* Workgroup announcements must only go to the MSBROWSE name. */ if (!strequal(dgram->dest_name.name, MSBROWSE) || (dgram->dest_name.name_type != 0x1)) { DEBUG(0,("process_workgroup_announce: from IP %s should be to __MSBROWSE__<0x01> not %s\n", inet_ntoa(p->ip), namestr(&dgram->dest_name))); return; } if ((work = find_workgroup_on_subnet(subrec, workgroup_announce_name))==NULL) { /* We have no record of this workgroup. Add it. */ if((work = create_workgroup_on_subnet(subrec, workgroup_announce_name, ttl))==NULL) return; } else { /* Update the workgroup death_time. */ update_workgroup_ttl(work, ttl); } if(*work->local_master_browser_name == '\0') { /* Set the master browser name. */ set_workgroup_local_master_browser_name( work, master_name ); } subrec->work_changed = True; }
/* Outputs a symbol table, and it's sub-tables * recursively, with a sigil describing the symbol * type, as follows: * T type * S symbol * N namespace * * Does not print captured variables. */ static void outstab(Stab *st, FILE *fd, int depth) { size_t i, n; void **k; char *ty; Type *t; indent(fd, depth); fprintf(fd, "Stab %p (super = %p, name=\"%s\")\n", st, st->super, namestr(st->name)); if (!st) return; /* print types */ k = htkeys(st->ty, &n); for (i = 0; i < n; i++) { indent(fd, depth + 1); fprintf(fd, "T "); /* already indented */ outname(k[i], fd); t = gettype(st, k[i]); ty = tystr(t); fprintf(fd, " = %s [tid=%d]\n", ty, t->tid); free(ty); } free(k); /* dump declarations */ k = htkeys(st->dcl, &n); for (i = 0; i < n; i++) { indent(fd, depth + 1); fprintf(fd, "S "); /* already indented */ outsym(getdcl(st, k[i]), fd, 0); } free(k); /* dump sub-namespaces */ k = htkeys(st->ns, &n); for (i = 0; i < n; i++) { indent(fd, depth + 1); fprintf(fd, "N %s\n", (char*)k[i]); outstab(getns_str(st, k[i]), fd, depth + 1); } free(k); }
options::entry::entry(const char *name, const char *description, UINT32 flags, const char *defvalue) : m_next(NULL), m_flags(flags), m_seqid(0), m_error_reported(false), m_priority(OPTION_PRIORITY_DEFAULT), m_description(description) { // copy in the name(s) as appropriate if (name != nullptr) { // first extract any range std::string namestr(name); int lparen = namestr.find('('); int dash = namestr.find(lparen + 1, '-'); int rparen = namestr.find(dash + 1, ')'); if (lparen != -1 && dash != -1 && rparen != -1) { m_minimum.assign(namestr.substr(lparen + 1, dash - (lparen + 1))); strtrimspace(m_minimum); m_maximum.assign(namestr.substr(dash + 1, rparen - (dash + 1))); strtrimspace(m_maximum); namestr.erase(lparen, rparen + 1 - lparen); } // then chop up any semicolon-separated names int semi; int nameindex = 0; while ((semi = namestr.find(';')) != -1 && nameindex < ARRAY_LENGTH(m_name)) { m_name[nameindex++].assign(namestr.substr(0, semi)); namestr.erase(0, semi + 1); } // finally add the last item if (nameindex < ARRAY_LENGTH(m_name)) m_name[nameindex++] = namestr; } // set the default value if (defvalue != nullptr) m_defdata = defvalue; m_data = m_defdata; }
core_options::entry::entry(const options_entry &entrylist) : m_next(NULL), m_flags(entrylist.flags), m_seqid(0), m_error_reported(false), m_priority(OPTION_PRIORITY_DEFAULT), m_description(entrylist.description) { // copy in the name(s) as appropriate if (entrylist.name != NULL) { // first extract any range astring namestr(entrylist.name); int lparen = namestr.chr(0, '('); int dash = namestr.chr(lparen + 1, '-'); int rparen = namestr.chr(dash + 1, ')'); if (lparen != -1 && dash != -1 && rparen != -1) { m_minimum.cpysubstr(namestr, lparen + 1, dash - (lparen + 1)).trimspace(); m_maximum.cpysubstr(namestr, dash + 1, rparen - (dash + 1)).trimspace(); namestr.del(lparen, rparen + 1 - lparen); } // then chop up any semicolon-separated names int semi; int nameindex = 0; while ((semi = namestr.chr(0, ';')) != -1 && nameindex < ARRAY_LENGTH(m_name)) { m_name[nameindex++].cpysubstr(namestr, 0, semi); namestr.del(0, semi + 1); } // finally add the last item if (nameindex < ARRAY_LENGTH(m_name)) m_name[nameindex++] = namestr; } // set the default value if (entrylist.defvalue != NULL) m_defdata = entrylist.defvalue; m_data = m_defdata; }
/// \brief Get the function address of the wrapper of the destructor. void* Value::GetDtorWrapperPtr(const clang::RecordDecl* RD, Interpreter& interp) const { std::string funcname; { llvm::raw_string_ostream namestr(funcname); namestr << "__cling_StoredValue_Destruct_" << RD; } std::string code("extern \"C\" void "); { clang::QualType RDQT(RD->getTypeForDecl(), 0); std::string typeName = utils::TypeName::GetFullyQualifiedName(RDQT, RD->getASTContext()); std::string dtorName = RD->getNameAsString(); code += funcname + "(void* obj){((" + typeName + "*)obj)->~" + dtorName + "();}"; } return interp.compileFunction(funcname, code, true /*ifUniq*/, false /*withAccessControl*/); }
void KMahjonggTilesetSelector::setupData(KConfigSkeleton * aconfig) { //Get our currently configured Tileset entry KConfig * config = aconfig->config(); KConfigGroup group = config->group("General"); QString initialGroup = group.readEntry("Tileset_file"); //The lineEdit widget holds our tileset path, but the user does not manipulate it directly kcfg_TileSet->hide(); //This will also load our resourcedir if it is not done already KMahjonggTileset tile; //Now get our tilesets into a list QStringList tilesAvailable = KGlobal::dirs()->findAllResources("kmahjonggtileset", QLatin1String( "*.desktop"), KStandardDirs::Recursive); QLatin1String namestr("Name"); int numvalidentries = 0; for (int i = 0; i < tilesAvailable.size(); ++i) { KMahjonggTileset * aset = new KMahjonggTileset(); QString atileset = tilesAvailable.at(i); if (aset->loadTileset(atileset)) { tilesetMap.insert(aset->authorProperty(namestr), aset); tilesetList->addItem(aset->authorProperty(namestr)); //Find if this is our currently configured Tileset if (atileset==initialGroup) { //Select current entry tilesetList->setCurrentRow(numvalidentries); tilesetChanged(); } ++numvalidentries; } else { delete aset; } } connect(tilesetList, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(tilesetChanged())); }
struct nmb_packet *nmb = &p->packet.nmb; struct nmb_name *question_name = &rrec->packet->packet.nmb.question.question_name; struct nmb_name *answer_name = &nmb->answers->rr_name; /* Sanity check. Ensure that the answer name in the incoming packet is the same as the requested name in the outgoing packet. */ if(!nmb_name_equal(question_name, answer_name)) { DEBUG(0,("node_status_response: Answer name %s differs from question \ name %s.\n", namestr(answer_name), namestr(question_name))); return; } DEBUG(5,("node_status_response: response from name %s on subnet %s.\n", namestr(answer_name), subrec->subnet_name)); /* Just send the whole answer resource record for the success function to parse. */ if(rrec->success_fn) (*rrec->success_fn)(subrec, rrec->userdata, nmb->answers, p->ip); /* Ensure we don't retry. */ remove_response_record(subrec, rrec); } /**************************************************************************** Deal with a timeout when requesting a node status. ****************************************************************************/ static void node_status_timeout_response(struct subnet_record *subrec, struct response_record *rrec)
/* * Return the name of a function given its index. */ char * namefunc(long index) { return namestr(&funcnames, index); }
void plotTreeNorms(TTree *tree_, std::string selectString, bool do7TeV){ // Create a map for plotting the pullsummaries: std::map < const char*, std::pair <double,double> > pullSummaryMap; int nPulls=0; TObjArray *l_branches = tree_->GetListOfBranches(); int nBranches = l_branches->GetEntries(); gStyle->SetPadTopMargin(0.01); TCanvas *c = new TCanvas("c","",960,800); std::string treename = tree_->GetName(); c->SaveAs(Form("%s_normresiduals.pdf[",treename.c_str())); // File to store plots in TFile *fOut = new TFile(Form("%s_normresiduals.root",treename.c_str()),"RECREATE"); TH1F *bHd = new TH1F("bHd","",50,-1.0,1.0); TH1F *bHfd = new TH1F("bHfd","",50,-1.0,1.0); for (int iobj=0;iobj<nBranches;iobj++){ TBranch *br =(TBranch*) l_branches->At(iobj); // Draw the normal histogram const char* name = br->GetName(); // select only the normalizations string namestr(name); if(namestr.find("n_exp")==string::npos) continue; bool fitPull=true; bool fitPullf=true; double p_mean =0; int nToysInTree = tree_->GetEntries(); // Find out if paramter is fitted value or constraint term. bool isFitted = true; p_mean = prenorms_[name].first; // toy initial parameters from the datacards std::cout << "******* "<< name << " *******"<<std::endl; std::cout << p_mean << std::endl; std::cout << "******************************" <<std::endl; TH1F* bH = (TH1F*)bHd->Clone(Form("%s",name)); TH1F* bHf = (TH1F*)bHfd->Clone(Form("%s_fail",name)); const char* drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean); tree_->Draw(Form("%s>>%s",drawInput,name),""); tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same"); fitPull = true; fitPullf = true; bHf->SetLineColor(2); bH->GetXaxis()->SetTitle(bH->GetTitle()); bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree)); bH->GetYaxis()->SetTitleOffset(1.05); bH->GetXaxis()->SetTitleOffset(0.9); bH->GetYaxis()->SetTitleSize(0.05); bH->GetXaxis()->SetTitleSize(0.05); bH->GetXaxis()->SetTitle(Form("%s",name)); bH->SetTitle(""); if ( bH->Integral() <=0 ) fitPull = false; if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);} if ( bHf->Integral() <=0 ) fitPullf = false; if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);} c->Clear(); TPad pad1("t1","",0.01,0.01,0.66,0.95); TPad pad2("t2","",0.70,0.20,0.98,0.80); pad1.SetNumber(1); pad2.SetNumber(2); if ( isFitted ) {pad2.Draw();} pad1.Draw(); pad1.SetGrid(true); TLatex *titletext = new TLatex();titletext->SetNDC(); c->cd(1); bH->Draw(); bHf->Draw("same"); TLegend *legend = new TLegend(0.6,0.8,0.9,0.89); legend->SetFillColor(0); legend->AddEntry(bH,"All Toys","L"); legend->AddEntry(bHf,selectString.c_str(),"L"); legend->Draw(); if (fitPull){ c->cd(2); double gap; TLatex *tlatex = new TLatex(); tlatex->SetNDC(); if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;} else {tlatex->SetTextSize(0.11);gap=0.14;} tlatex->SetTextColor(4); tlatex->DrawLatex(0.11,0.80,Form("Mean : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2))); if (fitPullf){ tlatex->SetTextColor(2); tlatex->DrawLatex(0.11,0.60,Form("Mean : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2))); } tlatex->SetTextSize(0.10); tlatex->SetTextColor(1); tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",p_mean)); pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2)); nPulls++; } // double titleSize = isFitted ? 0.1 : 0.028; //titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name); c->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); c->SaveAs(Form("mlfit/%s_residual_%s_%s.pdf",name,treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name)); } if (nPulls>0){ std::cout << "Generating Pull Summaries" <<std::endl; int nRemainingPulls = nPulls; TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0); std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin(); std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end(); int pullPlots = 1; while (nRemainingPulls > 0){ int nThisPulls = min(maxPullsPerPlot,nRemainingPulls); TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls); for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){ pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first); pullSummaryHist.SetBinContent(pi,((*pull_it).second).first); pullSummaryHist.SetBinError(pi,((*pull_it).second).second); nRemainingPulls--; } pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize); pullSummaryHist.GetYaxis()->SetRangeUser(-1,1);pullSummaryHist.GetYaxis()->SetTitle("residual summary (relative)");pullSummaryHist.Draw("E1"); hc->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); hc->SaveAs(Form("mlfit/residual_summary_%d_%s_%s.pdf",pullPlots,treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots)); // hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots)); pullPlots++; } delete hc; } c->SaveAs(Form("%s_normresiduals_%s.pdf]",treename.c_str(),(do7TeV ? "7TeV": "8TeV"))); fOut->Close(); delete c; return; }
Node *fold(Node *n, int foldvar) { Node **args, *r; Type *t; vlong a, b; size_t i; if (!n) return NULL; if (n->type != Nexpr) return n; r = NULL; args = n->expr.args; for (i = 0; i < n->expr.nargs; i++) args[i] = fold(args[i], foldvar); switch (exprop(n)) { case Ovar: if (foldvar && issmallconst(decls[n->expr.did])) r = fold(decls[n->expr.did]->decl.init, foldvar); break; case Oadd: /* x + 0 = 0 */ if (isval(args[0], 0)) r = args[1]; if (isval(args[1], 0)) r = args[0]; if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a + b, exprtype(n)); break; case Osub: /* x - 0 = 0 */ if (isval(args[1], 0)) r = args[0]; if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a - b, exprtype(n)); break; case Omul: /* 1 * x = x */ if (isval(args[0], 1)) r = args[1]; if (isval(args[1], 1)) r = args[0]; /* 0 * x = 0 */ if (isval(args[0], 0)) r = args[0]; if (isval(args[1], 0)) r = args[1]; if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a * b, exprtype(n)); break; case Odiv: /* x/1 = x */ if (isval(args[1], 1)) r = args[0]; /* 0/x = 0 */ if (isval(args[1], 0)) r = args[1]; if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a / b, exprtype(n)); break; case Omod: /* x%1 = x */ if (isval(args[1], 0)) r = args[0]; if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a % b, exprtype(n)); break; case Oneg: if (islit(args[0], &a)) r = val(n->line, -a, exprtype(n)); break; case Obsl: if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a << b, exprtype(n)); break; case Obsr: if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a >> b, exprtype(n)); break; case Obor: if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a | b, exprtype(n)); break; case Oband: if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a & b, exprtype(n)); break; case Obxor: if (islit(args[0], &a) && islit(args[1], &b)) r = val(n->line, a ^ b, exprtype(n)); break; case Omemb: t = tybase(exprtype(args[0])); /* we only fold lengths right now */ if (t->type == Tyarray && !strcmp(namestr(args[1]), "len")) r = t->asize; break; case Ocast: r = foldcast(n); break; default: break; } if (r) return r; else return n; }
void plotTree(TTree *tree_, std::string whichfit, std::string selectString){ // Create a map for plotting the pullsummaries: std::map < const char*, std::pair <double,double> > pullSummaryMap; int nPulls=0; TObjArray *l_branches = tree_->GetListOfBranches(); int nBranches = l_branches->GetEntries(); gStyle->SetPadTopMargin(0.01); TCanvas *c = new TCanvas("c","",960,800); std::string treename = tree_->GetName(); c->SaveAs(Form("%s.pdf[",treename.c_str())); // File to store plots in TFile *fOut = new TFile(Form("%s.root",treename.c_str()),"RECREATE"); for (int iobj=0;iobj<nBranches;iobj++){ TBranch *br =(TBranch*) l_branches->At(iobj); // Draw the normal histogram const char* name = br->GetName(); // names with - are not allowed string namestr(name); if(namestr.find("-")!=string::npos) { std::cout << "Variable " << name << " contains a bad character: -. Skipping. " << std::endl; continue; } bool fitPull=false; bool fitPullf=false; bool plotLH=false; TGraph *gr=NULL; double p_mean =0; double p_err =0; int nToysInTree = tree_->GetEntries(); // Find out if paramter is fitted value or constraint term bool isFitted = findNuisancePre(name); if (doPull && isFitted){ p_mean = bfvals_[name].first; // toy constrainits thrown about best fit to data if(namestr.find("n_exp")==string::npos) p_err = prevals_[name].second; // uncertainties taken from card std::cout << "******* "<< name << " *******"<<std::endl; std::cout << p_mean << " " << p_err << std::endl; std::cout << "******************************" <<std::endl; const char* drawInput; // if the parameter is a normalization, the error is not available. Do the residual instead of the pull if(namestr.find("n_exp")!=string::npos) drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean); else drawInput = Form("(%s-%f)/%f",name,p_mean,p_err); tree_->Draw(Form("%s>>%s",drawInput,name),""); tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same"); fitPull = true; fitPullf = true; if (doLH) { gr = graphLH(name,p_err,whichfit); if (gr) plotLH=true; } } else{ tree_->Draw(Form("%s>>%s",name,name),""); tree_->Draw(Form("%s>>%s_fail",name,name),selectString.c_str(),"same"); } TH1F* bH = (TH1F*) gROOT->FindObject(Form("%s",name))->Clone(); TH1F* bHf = (TH1F*) gROOT->FindObject(Form("%s_fail",name))->Clone(); bHf->SetLineColor(2); bH->GetXaxis()->SetTitle(bH->GetTitle()); bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree)); bH->GetYaxis()->SetTitleOffset(1.05); bH->GetXaxis()->SetTitleOffset(0.9); bH->GetYaxis()->SetTitleSize(0.05); bH->GetXaxis()->SetTitleSize(0.05); if (isFitted) {bH->GetXaxis()->SetTitle(Form("(%s-#theta_{B})/#sigma_{#theta}",name));} else {bH->GetXaxis()->SetTitle(Form("%s",name));} bH->SetTitle(""); if ( bH->Integral() <=0 ) fitPull = false; if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);} if ( bHf->Integral() <=0 ) fitPullf = false; if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);} c->Clear(); //TPad pad1("t1","",0.01,0.02,0.59,0.98); // Pad 1 sizes depend on the parameter type ... double pad1_x1,pad1_x2,pad1_y1,pad1_y2; if ( !isFitted ) { pad1_x1 = 0.01; pad1_x2 = 0.98; pad1_y1 = 0.045; pad1_y2 = 0.98; } else { pad1_x1 = 0.01; pad1_x2 = 0.59; pad1_y1 = 0.56; pad1_y2 = 0.98; } TPad pad1("t1","",pad1_x1,pad1_y1,pad1_x2,pad1_y2); TPad pad1a("t1a","",0.01,0.045,0.59,0.522); TPad pad2("t2","",0.59,0.04,0.98,0.62); TPad pad3("t3","",0.55,0.64,0.96,0.95); pad1.SetNumber(1); pad2.SetNumber(2); pad3.SetNumber(3); pad1a.SetNumber(4); if ( isFitted ) {pad1a.Draw();pad2.Draw();pad3.Draw();} pad1.Draw(); pad2.SetGrid(true); TLatex *titletext = new TLatex();titletext->SetNDC(); if ( isFitted ){ c->cd(4); tree_->Draw(Form("%s:%s_In>>%s_%s_2d",name,name,name,tree_->GetName()),""); //TH2D *h2d_corr = (TH2D*)gROOT->FindObject(Form("%s_2d",name)); //h2d_corr->SetMarkerColor(4); //h2d_corr->SetTitle(""); //h2d_corr->GetXaxis()->SetTitle(Form("%s_In",name)); //h2d_corr->GetYaxis()->SetTitle(Form("%s",name)); titletext->SetTextAlign(11); titletext->SetTextSize(0.05); titletext->DrawLatex(0.05,0.02,Form("%s_In",name)); titletext->SetTextAngle(90); titletext->DrawLatex(0.04,0.06,Form("%s",name)); titletext->SetTextAngle(0); } c->cd(1); bH->Draw(); bHf->Draw("same"); TLegend *legend = new TLegend(0.6,0.8,0.9,0.89); legend->SetFillColor(0); legend->AddEntry(bH,"All Toys","L"); legend->AddEntry(bHf,selectString.c_str(),"L"); legend->Draw(); if (doPull && plotLH) { c->cd(2); gr->Draw("ALP"); } if (fitPull){ c->cd(3); double gap; TLatex *tlatex = new TLatex(); tlatex->SetNDC(); if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;} else {tlatex->SetTextSize(0.11);gap=0.14;} tlatex->SetTextColor(4); tlatex->DrawLatex(0.11,0.80,Form("Mean : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2))); if (fitPullf){ tlatex->SetTextColor(2); tlatex->DrawLatex(0.11,0.60,Form("Mean : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1))); tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2))); } tlatex->SetTextSize(0.10); tlatex->SetTextColor(1); if(namestr.find("n_exp")!=string::npos) tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",prevals_[name].first)); else tlatex->DrawLatex(0.11,0.33,Form("Pre-fit #pm #sigma_{#theta}: %.3f #pm %.3f",prevals_[name].first, p_err)); tlatex->DrawLatex(0.11,0.18,Form("Best-fit (#theta_{B}) : %.3f ",p_mean)); tlatex->DrawLatex(0.11,0.03,Form("Best-fit (#theta_{S+B}): %.3f ",bfvals_sb_[name].first)); pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2)); nPulls++; } double titleSize = isFitted ? 0.1 : 0.028; titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name); c->SaveAs(Form("%s.pdf",treename.c_str())); fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name)); //c->SaveAs(Form("%s_%s.pdf",treename.c_str(),name)); } if (doPull && nPulls>0){ std::cout << "Generating Pull Summaries" <<std::endl; int nRemainingPulls = nPulls; TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0); std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin(); std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end(); int pullPlots = 1; while (nRemainingPulls > 0){ int nThisPulls = min(maxPullsPerPlot,nRemainingPulls); TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls); for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){ pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first); pullSummaryHist.SetBinContent(pi,((*pull_it).second).first); pullSummaryHist.SetBinError(pi,((*pull_it).second).second); nRemainingPulls--; } pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize); pullSummaryHist.GetYaxis()->SetRangeUser(-3,3);pullSummaryHist.GetYaxis()->SetTitle("pull summary (n#sigma)");pullSummaryHist.Draw("E1"); hc->SaveAs(Form("%s.pdf",treename.c_str())); fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots)); // hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots)); pullPlots++; } delete hc; } c->SaveAs(Form("%s.pdf]",treename.c_str())); fOut->Close(); delete c; return; }
/* * Call the appropriate user-defined routine to handle an object action. * Returns the value that the routine returned. */ VALUE objcall(int action, VALUE *v1, VALUE *v2, VALUE *v3) { FUNC *fp; /* function to call */ STATIC OBJECTACTIONS *oap; /* object to call for */ struct objectinfo *oip; /* information about action */ long index; /* index of function (negative if undefined) */ VALUE val; /* return value */ VALUE tmp; /* temp value */ char name[SYMBOLSIZE+1+1]; /* full name of user routine to call */ size_t namestr_len; /* length of the namestr() return string */ char *namestr_ret; /* namestr() return string */ size_t opi_name_len; /* length of the oip name */ /* initialize VALUEs */ val.v_subtype = V_NOSUBTYPE; tmp.v_subtype = V_NOSUBTYPE; if ((unsigned)action > OBJ_MAXFUNC) { math_error("Illegal action for object call"); /*NOTREACHED*/ } oip = &objectinfo[action]; if (v1->v_type == V_OBJ) { oap = v1->v_obj->o_actions; } else if (v2->v_type == V_OBJ) { oap = v2->v_obj->o_actions; } else { math_error("Object routine called with non-object"); /*NOTREACHED*/ } index = oap->oa_indices[action]; if (index < 0) { namestr_ret = namestr(&objectnames, oap->oa_index); if (namestr_ret == NULL) { math_error("namestr returned NULL!!!"); /*NOTREACHED*/ } namestr_len = strlen(namestr_ret); opi_name_len = strlen(oip->name); if (namestr_len > (size_t)SYMBOLSIZE-1-opi_name_len) { math_error("namestr returned a strong too long!!!"); /*NOTREACHED*/ } name[0] = '\0'; strncpy(name, namestr_ret, namestr_len+1); strcat(name, "_"); strncat(name, oip->name, opi_name_len+1); index = adduserfunc(name); oap->oa_indices[action] = index; } fp = NULL; if (index >= 0) fp = findfunc(index); if (fp == NULL) { switch (oip->error) { case ERR_PRINT: objprint(v1->v_obj); val.v_type = V_NULL; break; case ERR_CMP: val.v_type = V_INT; if (v1->v_type != v2->v_type) { val.v_int = 1; return val; } val.v_int = objcmp(v1->v_obj, v2->v_obj); break; case ERR_TEST: val.v_type = V_INT; val.v_int = objtest(v1->v_obj); break; case ERR_POW: if (v2->v_type != V_NUM) { math_error("Non-real power"); /*NOTREACHED*/ } val = objpowi(v1, v2->v_num); break; case ERR_ONE: val.v_type = V_NUM; val.v_num = qlink(&_qone_); break; case ERR_INC: tmp.v_type = V_NUM; tmp.v_num = &_qone_; val = objcall(OBJ_ADD, v1, &tmp, NULL_VALUE); break; case ERR_DEC: tmp.v_type = V_NUM; tmp.v_num = &_qone_; val = objcall(OBJ_SUB, v1, &tmp, NULL_VALUE); break; case ERR_SQUARE: val = objcall(OBJ_MUL, v1, v1, NULL_VALUE); break; case ERR_VALUE: copyvalue(v1, &val); break; case ERR_ASSIGN: copyvalue(v2, &tmp); tmp.v_subtype |= v1->v_subtype; freevalue(v1); *v1 = tmp; val.v_type = V_NULL; break; default: math_error("Function \"%s\" is undefined", namefunc(index)); /*NOTREACHED*/ } return val; } switch (oip->args) { case 0: break; case 1: ++stack; stack->v_addr = v1; stack->v_type = V_ADDR; break; case 2: ++stack; stack->v_addr = v1; stack->v_type = V_ADDR; ++stack; stack->v_addr = v2; stack->v_type = V_ADDR; break; case 3: ++stack; stack->v_addr = v1; stack->v_type = V_ADDR; ++stack; stack->v_addr = v2; stack->v_type = V_ADDR; ++stack; stack->v_addr = v3; stack->v_type = V_ADDR; break; default: math_error("Bad number of args to calculate"); /*NOTREACHED*/ } calculate(fp, oip->args); switch (oip->retval) { case A_VALUE: return *stack--; case A_UNDEF: freevalue(stack--); val.v_type = V_NULL; break; case A_INT: if ((stack->v_type != V_NUM) || qisfrac(stack->v_num)) { math_error("Integer return value required"); /*NOTREACHED*/ } index = qtoi(stack->v_num); qfree(stack->v_num); stack--; val.v_type = V_INT; val.v_int = index; break; default: math_error("Bad object return"); /*NOTREACHED*/ } return val; }
/* Outputs a node in indented tree form. This is * not a full serialization, but mainly an aid for * understanding and debugging. */ static void outnode(Node *n, FILE *fd, int depth) { size_t i; char *ty; char *tr; int tid; char buf[1024]; if (!n) { findentf(fd, depth, "Nil\n"); return; } findentf(fd, depth, "%s.%zd@%i", nodestr[n->type], n->nid, lnum(n->loc)); switch (n->type) { case Nfile: fprintf(fd, "(name = %s)\n", n->file.files[0]); dumpfilestabs(file, depth + 1, fd); for (i = 0; i < n->file.nuses; i++) outnode(n->file.uses[i], fd, depth + 1); for (i = 0; i < n->file.nstmts; i++) outnode(n->file.stmts[i], fd, depth + 1); break; case Ndecl: tr = ""; if (n->decl.trait) tr = namestr(n->decl.trait->name); fprintf(fd, "(did = %zd, trait=%s, vis = %d)\n", n->decl.did, tr, n->decl.vis); findentf(fd, depth + 1, "isglobl=%d\n", n->decl.isglobl); findentf(fd, depth + 1, "isconst=%d\n", n->decl.isconst); findentf(fd, depth + 1, "isgeneric=%d\n", n->decl.isgeneric); findentf(fd, depth + 1, "isextern=%d\n", n->decl.isextern); findentf(fd, depth + 1, "ispkglocal=%d\n", n->decl.ispkglocal); findentf(fd, depth + 1, "ishidden=%d\n", n->decl.ishidden); findentf(fd, depth + 1, "isimport=%d\n", n->decl.isimport); findentf(fd, depth + 1, "isnoret=%d\n", n->decl.isnoret); findentf(fd, depth + 1, "isexportinit=%d\n", n->decl.isexportinit); findentf(fd, depth, ")\n"); outsym(n, fd, depth + 1); outnode(n->decl.init, fd, depth + 1); break; case Nblock: fprintf(fd, "\n"); outstab(n->block.scope, fd, depth + 1); for (i = 0; i < n->block.nstmts; i++) outnode(n->block.stmts[i], fd, depth + 1); break; case Nifstmt: fprintf(fd, "\n"); outnode(n->ifstmt.cond, fd, depth + 1); outnode(n->ifstmt.iftrue, fd, depth + 1); outnode(n->ifstmt.iffalse, fd, depth + 1); break; case Nloopstmt: fprintf(fd, "\n"); outnode(n->loopstmt.init, fd, depth + 1); outnode(n->loopstmt.cond, fd, depth + 1); outnode(n->loopstmt.step, fd, depth + 1); outnode(n->loopstmt.body, fd, depth + 1); break; case Niterstmt: fprintf(fd, "\n"); outnode(n->iterstmt.elt, fd, depth + 1); outnode(n->iterstmt.seq, fd, depth + 1); outnode(n->iterstmt.body, fd, depth + 1); break; case Nmatchstmt: fprintf(fd, "\n"); outnode(n->matchstmt.val, fd, depth + 1); for (i = 0; i < n->matchstmt.nmatches; i++) outnode(n->matchstmt.matches[i], fd, depth + 1); break; case Nmatch: fprintf(fd, "\n"); outnode(n->match.pat, fd, depth + 1); outnode(n->match.block, fd, depth + 1); break; case Nuse: fprintf(fd, " (name = %s, islocal = %d)\n", n->use.name, n->use.islocal); break; case Nexpr: if (exprop(n) == Ovar) assert(decls[n->expr.did]->decl.did == n->expr.did); ty = tystr(n->expr.type); if (n->expr.type) tid = n->expr.type->tid; else tid = -1; fprintf(fd, " (type = %s [tid %d], op = %s, isconst = %d, did=%zd)\n", ty, tid, opstr[n->expr.op], n->expr.isconst, n->expr.did); free(ty); outnode(n->expr.idx, fd, depth + 1); for (i = 0; i < n->expr.nargs; i++) outnode(n->expr.args[i], fd, depth + 1); break; case Nlit: switch (n->lit.littype) { case Lvoid: fprintf(fd, " Lvoid\n"); break; case Lchr: fprintf(fd, " Lchr %c\n", n->lit.chrval); break; case Lbool: fprintf(fd, " Lbool %s\n", n->lit.boolval ? "true" : "false"); break; case Lint: fprintf(fd, " Lint %llu\n", n->lit.intval); break; case Lflt: fprintf(fd, " Lflt %lf\n", n->lit.fltval); break; case Llbl: fprintf(fd, " Llbl %s\n", n->lit.lblval); break; case Lstr: fprintf(fd, " Lstr %.*s\n", (int)n->lit.strval.len, n->lit.strval.buf); break; case Lfunc: fprintf(fd, " lfunc\n"); outnode(n->lit.fnval, fd, depth + 1); break; } break; case Nfunc: fprintf(fd, " (args =\n"); for (i = 0; i < n->func.nargs; i++) outnode(n->func.args[i], fd, depth + 1); findentf(fd, depth, ")\n"); outstab(n->func.scope, fd, depth + 1); outnode(n->func.body, fd, depth + 1); break; case Nname: fprintf(fd, "("); if (n->name.ns) fprintf(fd, "%s.", n->name.ns); fprintf(fd, "%s", n->name.name); fprintf(fd, ")\n"); break; case Nimpl: fprintf(fd, "(name = %s, type = %s)\n", namestr(n->impl.traitname), tyfmt(buf, sizeof buf, n->impl.type)); findentf(fd, depth, ""); outnode(n->impl.traitname, fd, depth + 1); for (i = 0; i < n->impl.ndecls; i++) outnode(n->impl.decls[i], fd, depth + 1); break; case Nnone: fprintf(stderr, "Nnone not a real node type!"); fprintf(fd, "Nnone\n"); break; } }
static const std::string& xmlstr() {return namestr();}
static void dumptypes(Node *n, int indent) { size_t i; char *ty; if (!n) return; switch (n->type) { case Nfile: for (i = 0; i < n->file.nuses; i++) dumptypes(n->file.uses[i], indent); for (i = 0; i < n->file.nstmts; i++) dumptypes(n->file.stmts[i], indent); break; case Ndecl: printindent(indent); if (n->decl.isconst) printf("const "); else printf("var "); ty = tystr(n->decl.type); printf("%s : %s\n", namestr(n->decl.name), ty); free(ty); dumptypes(n->decl.init, indent + 1); break; case Nblock: for (i = 0; i < n->block.nstmts; i++) dumptypes(n->block.stmts[i], indent); break; case Nifstmt: dumptypes(n->ifstmt.cond, indent); dumptypes(n->ifstmt.iftrue, indent); dumptypes(n->ifstmt.iffalse, indent); break; case Nloopstmt: dumptypes(n->loopstmt.init, indent); dumptypes(n->loopstmt.cond, indent); dumptypes(n->loopstmt.step, indent); dumptypes(n->loopstmt.body, indent); break; case Niterstmt: dumptypes(n->iterstmt.elt, indent); dumptypes(n->iterstmt.seq, indent); dumptypes(n->iterstmt.body, indent); break; case Nmatchstmt: dumptypes(n->matchstmt.val, indent); for (i = 0; i < n->matchstmt.nmatches; i++) dumptypes(n->matchstmt.matches[i], indent); break; case Nmatch: dumptypes(n->match.pat, indent); dumptypes(n->match.block, indent); break; case Nuse: printindent(indent); if (n->use.islocal) printf("Use \"%s\"\n", n->use.name); else printf("Use %s\n", n->use.name); break; case Nexpr: dumptypes(n->expr.idx, indent); for (i = 0; i < n->expr.nargs; i++) dumptypes(n->expr.args[i], indent); break; case Nlit: switch (n->lit.littype) { case Lfunc: dumptypes(n->lit.fnval, indent); break; default: break; } break; case Nfunc: printindent(indent); printf("Args:\n"); for (i = 0; i < n->func.nargs; i++) dumptypes(n->func.args[i], indent+1); printindent(indent); printf("Body:\n"); dumptypes(n->func.body, indent + 1); break; case Ntrait: die("Traits not fully implemented\n"); break; case Nname: break; case Nnone: die("Nnone not a real node type!"); break; } }
/* * Returns the name of object type with specified index */ char * objtypename(unsigned long index) { return namestr(&objectnames, (long)index); }
Node *fold(Node *n, int foldvar) { Node **args, *r; Type *t; vlong a, b; size_t i; if (!n) return NULL; if (n->type != Nexpr) return n; r = NULL; args = n->expr.args; if (n->expr.idx) n->expr.idx = fold(n->expr.idx, foldvar); for (i = 0; i < n->expr.nargs; i++) args[i] = fold(args[i], foldvar); switch (exprop(n)) { case Ovar: if (foldvar && issmallconst(decls[n->expr.did])) r = fold(decls[n->expr.did]->decl.init, foldvar); break; case Oadd: /* x + 0 = 0 */ if (isintval(args[0], 0)) r = args[1]; if (isintval(args[1], 0)) r = args[0]; if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a + b, exprtype(n)); break; case Osub: /* x - 0 = 0 */ if (isintval(args[1], 0)) r = args[0]; if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a - b, exprtype(n)); break; case Omul: /* 1 * x = x */ if (isintval(args[0], 1)) r = args[1]; if (isintval(args[1], 1)) r = args[0]; /* 0 * x = 0 */ if (isintval(args[0], 0)) r = args[0]; if (isintval(args[1], 0)) r = args[1]; if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a * b, exprtype(n)); break; case Odiv: /* x/0 = error */ if (isintval(args[1], 0)) fatal(args[1], "division by zero"); /* x/1 = x */ if (isintval(args[1], 1)) r = args[0]; /* 0/x = 0 */ if (isintval(args[1], 0)) r = args[1]; if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a / b, exprtype(n)); break; case Omod: /* x%0 = error */ if (isintval(args[1], 0)) fatal(args[1], "division by zero"); /* x%1 = 0 */ if (isintval(args[1], 1)) r = val(n->loc, 0, exprtype(n)); if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a % b, exprtype(n)); break; case Oneg: if (getintlit(args[0], &a)) r = val(n->loc, -a, exprtype(n)); break; case Obsl: if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a << b, exprtype(n)); break; case Obsr: if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a >> b, exprtype(n)); break; case Obor: if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a | b, exprtype(n)); break; case Oband: if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a & b, exprtype(n)); break; case Obxor: if (getintlit(args[0], &a) && getintlit(args[1], &b)) r = val(n->loc, a ^ b, exprtype(n)); break; case Omemb: t = tybase(exprtype(args[0])); /* we only fold lengths right now */ if (t->type == Tyarray && !strcmp(namestr(args[1]), "len")) { r = t->asize; r->expr.type = exprtype(n); } break; case Oarr: if (n->expr.nargs > 0) qsort(n->expr.args, n->expr.nargs, sizeof(Node*), idxcmp); break; case Ocast: r = foldcast(n); break; default: break; } if (r && n->expr.idx) r->expr.idx = n->expr.idx; if (r) return r; else return n; }