main() { //int str[]={1,2,3,4,3,2,1}; //if(ispalindrome(str)) // printf("yes:\n\n"); //else // printf("No::\n\n"); int i; struct S *s=createS(); for(i=0;i<6;i++) push(&s,i); printstack(s); reverse(&s); printf("\n\n after\n\n"); printstack(s); }
int main() { initialize(); push(1); push(2); push(3); printstack(); printf("popped %d\n", pop()); printstack(); return 0; }
int opal_backtrace_print(FILE *file, char *prefix, int strip) { printstack(fileno(file)); return OPAL_SUCCESS; }
int main() { push(1,1); push(1,2); push(2,3); push(2,4); push(3,5); push(3,6); printstack(1); printstack(2); printstack(3); printf("Popping from stack1 %d \n",pop(1)); printf("Popping from stack1 %d \n",pop(2)); printf("Popping from stack1 %d \n",pop(3)); }
void push(const char *field, const char *str) { assert(depth < MAXDEPTH); configstack[depth].field = field; configstack[depth].str = str; depth++; printstack(); printf("\n"); }
int main() { stack S1; stack S2; char ngaran[5][10]; CreateEmpty(&S1); CreateEmpty(&S2); int i; for(i=0 ; i<5 ; i++){ scanf("%s", ngaran[i]); } printf("S1 -"); printstack(S1); printf("S2 -"); printstack(S2); push(ngaran[0], &S1); push(ngaran[1], &S2); spop(&S1, &S2); printf("S1 -"); printstack(S1); printf("S2 -"); printstack(S2); pop(&S2); push(ngaran[2], &S1); push(ngaran[3], &S2); push(ngaran[4], &S2); spop(&S2, &S1); printf("S2 -"); printstack(S2); printf("S1 -"); printstack(S1); return 0; }
void CrashHandler_handleCrash(int signum) { switch(signum) { case SIGABRT: Logger::warning("SIGABRT: abort() called somewhere in the program."); break; case SIGSEGV: Logger::warning("SIGSEGV: Illegal memory access."); break; case SIGILL: Logger::warning("SIGILL: Executing a malformed instruction. (possibly invalid pointer)"); break; case SIGFPE: Logger::warning("SIGFPE: Illegal floating point instruction (possibly division by zero)."); break; } printstack(); exit(signum); }
int main(int argc, char **argv) { struct rs_config config; const char *label; uint16_t sub_vid, sub_did; int id; if(argc != 2) { fprintf(stderr, "usage: %s <config>\n", argv[0]); return 1; } memset(&config, 0, sizeof(config)); if(!(label = parse_config(NULL, 1, argv[1], &config))) errx(1, "parse_config failed"); push(KW_SERVICE, label); if(config.type) push(KW_TYPE, config.type); if(config.descr) push(KW_DESCR, config.descr); if(config.rs_start.rss_nr_pci_id > 0) { printstack(); printf("%s %s ", KW_PCI, KW_DEVICE); for(id = 0; id < config.rs_start.rss_nr_pci_id; id++) { sub_vid = config.rs_start.rss_pci_id[id].sub_vid; sub_did = config.rs_start.rss_pci_id[id].sub_did; /* * The PCI driver interprets each of these two fields * individually, so we must print them even if just one * of them is set. Correct matching of just one of * the fields may be hard to do from a script though, * so driver writers are advised to specify either both * or neither of these two fields. */ if (sub_vid != NO_SUB_VID || sub_did != NO_SUB_DID) printf("%04X:%04X/%04X:%04X ", config.rs_start.rss_pci_id[id].vid, config.rs_start.rss_pci_id[id].did, sub_vid, sub_did); else printf("%04X:%04X ", config.rs_start.rss_pci_id[id].vid, config.rs_start.rss_pci_id[id].did); } printf("\n"); } }
static inline BOOL do_basic_glibc_backtrace() { BOOL success = FALSE; std::string strace_filename = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"stack_trace.log"); llinfos << "Opening stack trace file " << strace_filename << llendl; LLFILE* StraceFile = LLFile::fopen(strace_filename, "w"); if (!StraceFile) { llinfos << "Opening stack trace file " << strace_filename << " failed. Using stderr." << llendl; StraceFile = stderr; } printstack(fileno(StraceFile)); if (StraceFile != stderr) fclose(StraceFile); return success; }
int diag_backtrace(diag_output_t *o, diag_backtrace_param_t *p, diag_context_t *c) { fmt_userdata_t u = {0}; ucontext_t context; if (c && c->context) { context = *c->context; } else { getcontext(&context); } if (p->backtrace_count && p->backtrace_count < DIAG_BT_LIMIT) { u.count = p->backtrace_count; } else { u.count = DIAG_BT_LIMIT; } if (o->output_mode == DIAG_WRITE_FD) { printstack(o->outfile); } else { #ifdef BROKEN_SIGNAL_UCONTEXT_T if (c && c->context) { /* must ignore user context, which probably came from * signal handler */ u.skips = FRAMES_TO_SKIP; getcontext(&context); } #endif u.p = p; u.o = o; walkcontext(&context, fmt, &u); } return 0; }
int main(int argc, char** argv) { FILE *fp; char *buffer = malloc(MAX_LINE * sizeof(char)); int stack[STACK_SIZE]; int stackOffset = 0; if (buffer == NULL) { printf("Could not allocate buffer"); return -1; } if (!(fp = fopen(argv[1], "r+"))) { printf("Could not open file"); return -1; } int opcode; int operand; while (readinst(&opcode, &operand, fp)) {//readChunk(fp, buffer)) { #ifdef DEBUG printf("Instruction:\n"); #endif //opcode = readOpcode(buffer); #ifdef DEBUG printf(" Opcode = %u\n", opcode); #endif //operand = readOperand(buffer); #ifdef DEBUG printf(" Operand = %u\n", operand); #endif (*lookupTable[opcode])(&stack, &stackOffset, operand); #ifdef DEBUG_PRINTSTACK printf("New stack ptr: 0x%x+%u=0x%x (%u) \n", stack, stackOffset, stack+stackOffset, *(stack+stackOffset)); printstack(&stack, stackOffset); #endif } fclose(fp); }
/* Obtain a backtrace and print it to stdout. */ void xine_print_trace (void) { #if HAVE_BACKTRACE /* Code Taken from GNU C Library manual */ void *array[10]; size_t size; char **strings; size_t i; size = backtrace (array, 10); strings = backtrace_symbols (array, size); printf ("Obtained %lu stack frames.\n", (unsigned long) size); for (i = 0; i < size; i++) { printf ("%s\n", strings[i]); } free (strings); #elif HAVE_PRINTSTACK printstack(STDOUT_FILENO); #else printf("stack backtrace not available.\n"); #endif #endif }
int main(int argc, char *argv[]) { int type; double op2, temp; char s[MAXOP]; while ((type = getop(s)) != EOF){ switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); /* pop() - pop() has an undefined order of evaluation */ push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: zero divisor\n"); break; case '%': op2 = pop(); if (op2 != 0.0) push((int)pop() % (int)op2); else printf("error: zero modulo\n"); break; case SIN: push(sin(pop())); break; case COS: push(cos(pop())); break; case EXP: push(exp(pop())); break; case POW: op2 = pop(); push(pow(pop(), op2)); break; case '!': /* factorial */ op2 = pop(); printf("factorial on %g\n", op2); if (op2 == 0) push(1.0); else if (op2 < 0){ printf("error: factorial on negative number\n"); push(op2); } else { for (temp = op2 - 1; temp > 0; temp--) op2 *= temp; push(op2); } break; case VARIABLE: push(variables[lastVariable-'a']); break; case '=': pop(); /* ignore top of stack, which is the previous value of the variable */ variables[lastVariable-'a'] = pop(); break; case '\n': /* print result */ case GET_TOP: if (sp > 0) printf("\tTop is now: %.8g\n", value[sp-1]); break; case SWAP_TOP: temp = pop(); op2 = pop(); push(temp); push(op2); break; case GET_STACK: printstack(); break; case CLEAR: sp = 0; break; default: printf("error: unknown command %s\n", s); break; } } }
void print_stack() { printstack(fileno(stdout)); }
void print(const char *field, const char *str) { printstack(); printf("%s %s\n", field, str); }
/* Reverse Polish calculator */ main() { int type; double op2; char s[MAXOP]; while((type=getop(s))!=EOF){ switch(type){ case NUMBER: push(atof(s)); break; case IDENTIFIER: dealWithName(s); case '+': push(pop()+pop()); break; case '*': push(pop()*pop()); break; case '-': op2=pop(); push(pop()-op2); break; case '/': op2=pop(); if(op2!=0.0) push(pop()/op2); else printf("error:zero divisor\n"); break; case '%': op2=pop(); if(op2) push(fmod(pop(),op2)); else printf("error:zero divisor\n"); break; case '\n': printf("\t%.8g\n",pop()); break; /* print the top element and not push */ case 'p': printop(); break; /* copy the top element and print it */ case 'c': copy(); break; /* print the stack */ case 'P': printstack(); break; /* swap the top two element */ case 's': swap(); break; case 'C': clear(); break; default: printf("error:unknown command %s\n",s); break; } } return 0; }
void backtrace_symbols_fd(void *const *array, int size, int fd) { /* Workaround implemented */ printstack(fd); }
void KCrash::defaultCrashHandler (int sig) { // WABA: Do NOT use kDebug() in this function because it is much too risky! // Handle possible recursions static int crashRecursionCounter = 0; crashRecursionCounter++; // Nothing before this, please ! #if !defined(Q_OS_WIN) signal(SIGALRM, SIG_DFL); alarm(3); // Kill me... (in case we deadlock in malloc) #endif #ifdef Q_OS_SOLARIS (void) printstack(2 /* stderr, assuming it's still open. */); #endif if (crashRecursionCounter < 2) { if (s_emergencySaveFunction) { s_emergencySaveFunction (sig); } if ((s_flags & AutoRestart) && s_autoRestartCommand) { sleep(1); startProcess(s_autoRestartArgc, const_cast<const char**>(s_autoRestartCommandLine), false); } crashRecursionCounter++; } #if !defined(Q_OS_WIN) if (!(s_flags & KeepFDs)) closeAllFDs(); # if defined(Q_WS_X11) else if (QX11Info::display()) close(ConnectionNumber(QX11Info::display())); # endif #endif if (crashRecursionCounter < 3) { #ifndef NDEBUG fprintf(stderr, "KCrash: crashing... crashRecursionCounter = %d\n", crashRecursionCounter); fprintf(stderr, "KCrash: Application Name = %s path = %s pid = %lld\n", s_appName ? s_appName : "<unknown>" , s_appPath ? s_appPath : "<unknown>", QCoreApplication::applicationPid()); fprintf(stderr, "KCrash: Arguments: "); for (int i = 0; s_autoRestartCommandLine[i]; ++i) { fprintf(stderr, "%s ", s_autoRestartCommandLine[i]); } fprintf(stderr, "\n"); #else fprintf(stderr, "KCrash: Application '%s' crashing...\n", s_appName ? s_appName : "<unknown>"); #endif if (!s_launchDrKonqi) { setCrashHandler(0); #if !defined(Q_OS_WIN) raise(sig); // dump core, or whatever is the default action for this signal. #endif return; } const char * argv[27]; // don't forget to update this int i = 0; // argument 0 has to be drkonqi argv[i++] = s_drkonqiPath; #if defined Q_WS_X11 // start up on the correct display argv[i++] = "-display"; if ( QX11Info::display() ) argv[i++] = XDisplayString(QX11Info::display()); else argv[i++] = getenv("DISPLAY"); #elif defined(Q_WS_QWS) // start up on the correct display argv[i++] = "-display"; argv[i++] = getenv("QWS_DISPLAY"); #endif argv[i++] = "--appname"; argv[i++] = s_appName ? s_appName : "<unknown>"; if (KApplication::loadedByKdeinit) argv[i++] = "--kdeinit"; // only add apppath if it's not NULL if (s_appPath && *s_appPath) { argv[i++] = "--apppath"; argv[i++] = s_appPath; } // signal number -- will never be NULL char sigtxt[ 10 ]; sprintf( sigtxt, "%d", sig ); argv[i++] = "--signal"; argv[i++] = sigtxt; char pidtxt[ 20 ]; sprintf( pidtxt, "%lld", QCoreApplication::applicationPid()); argv[i++] = "--pid"; argv[i++] = pidtxt; const KComponentData componentData = KGlobal::mainComponent(); const KAboutData *about = componentData.isValid() ? componentData.aboutData() : 0; if (about) { if (about->internalVersion()) { argv[i++] = "--appversion"; argv[i++] = about->internalVersion(); } if (about->internalProgramName()) { argv[i++] = "--programname"; argv[i++] = about->internalProgramName(); } if (about->internalBugAddress()) { argv[i++] = "--bugaddress"; argv[i++] = about->internalBugAddress(); } } char sidtxt[256]; if ( kapp && !kapp->startupId().isNull()) { argv[i++] = "--startupid"; strlcpy(sidtxt, kapp->startupId().constData(), sizeof(sidtxt)); argv[i++] = sidtxt; } if ( s_flags & SaferDialog ) argv[i++] = "--safer"; if ((s_flags & AutoRestart) && s_autoRestartCommand) argv[i++] = "--restarted"; //tell drkonqi if the app has been restarted #if defined(Q_OS_WIN) char threadId[8] = { 0 }; sprintf( threadId, "%d", GetCurrentThreadId() ); argv[i++] = "--thread"; argv[i++] = threadId; #endif // NULL terminated list argv[i] = NULL; startProcess(i, argv, true); } if (crashRecursionCounter < 4) { fprintf(stderr, "Unable to start Dr. Konqi\n"); } _exit(255); }
main () { int sw,lon; pila stackptr = NULL; int choice,est,i,cdel,k,y,p; char name[30]; float not1,not2,prom,cod; clrscr(); while((choice = instructions()) != 6 ){ switch(choice){ case 1: clrscr(); gotoxy(10,10); printf("Entre cantidad de estudiantes... "); gotoxy(43,10); scanf("%d",&est); for(i=1;i<=est;i++){ clrscr(); gotoxy(4,1); printf("É\n"); gotoxy(74,1);printf("»\n"); gotoxy(4,23);printf("È\n"); gotoxy(74,23);printf("¼\n"); for (k= 5; k<= 73; k ++) { gotoxy (k,y); gotoxy(k,1);printf("Í\n"); gotoxy (k,23);printf("Í\n"); } for (p=2; p<=22; p++) { gotoxy (4,p);printf("º\n"); gotoxy (74,p);printf("º\n"); } // CAPTURA DE LA INFORMACION DE LOS NODOS gotoxy(25,8); printf(" PROCESAMIENTO DE ESTUDIANTES "); gotoxy(25,10); printf("code: "); scanf("%f",&cod); gotoxy(25,12); printf("Name: \n"); gotoxy(31,12); cin.getline(name,30); gotoxy(25,14); printf("Note1: "); gotoxy(32,14); do{ gotoxy(32,14); clreol(); scanf("%f",¬1); }while(not1<0 || not1>5); gotoxy(25,16); printf("note2: "); do{ gotoxy(32,16); clreol(); scanf("%f",¬2); }while(not2<0 || not2>5); prom = (not1+not2); // ENVIA INFO Y GUARDA push(&stackptr,cod,name,not1,not2,lon,prom); clrscr(); } break; case 2: if(! pila_vacia(stackptr)){//VERIFICA ESTADO DE LA PILA printf("\n",pop(&stackptr));//SACA INFO DE LA PILA gotoxy(25,22); printf("presione <<enter>> "); getch(); } else{ gotoxy(25,22); printf("La pila esta vacia...! "); getch(); } break; case 3: clrscr(); printstack(stackptr); // MUESTRA PILA getch(); break; case 4: if(! pila_vacia(stackptr)){//VERIFICA ESTADO DE LA PILA buscar(stackptr); } else{ gotoxy(25,22); printf("La pila esta vacia...\n\n"); getch(); } break; case 5: if(! pila_vacia(stackptr)){ Eliminar(stackptr); } else{ gotoxy(25,22); printf("La pila esta vacia...\n\n"); getch(); } default: break; } } return 0; }
void WordLadder::outputLadder(const string &start, const string &end, const string &outputFile) { cout << "Finding word ladder from " << start << " to " << end << ": "; ofstream outfile; outfile.open(outputFile.c_str()); if (!outfile.is_open()) { cout << "Opening output file failed." << endl; return; } // set up the stuff queue< stack<string> > queue; stack< string > stack; string word; list<string>::iterator it; bool startgood = false, endgood = false; // initial validity tests for (it=dict.begin();it!=dict.end();++it) { if (*it == start) { startgood = true; } if (*it == end) { endgood = true; } } if (!startgood || !endgood) { cout << "Starting or ending word was not found in the dictionary." << endl; return; } if (start == end) { outfile << start; return; } stack.push(start); queue.push(stack); // find the first word, delete it dict.remove(start); while(!queue.empty()) { // get the word off of the top of the front stack word = queue.front().top(); for (it=dict.begin();it!=dict.end();++it) { // wordcompare will decide if the word is off by one from the dictionary word. if (wordcompare(word,*it)) { if (*it == end) { // if the off by one word is the last word // the ladder contains the entire stack -- output and return. queue.front().push(end); //print the stack printstack(queue.front(),outfile); //cout << "Operations: " << opers << endl << endl; return; } // otherwise, create a copy of the front stack and push the // off by one word from dictionary stack = queue.front(); stack.push(*it); queue.push(stack); it = dict.erase(it); // decrement iterator by one to correct for the advanced iterator // returned by the std::list::erase function it--; } } queue.pop(); } // if a word ladder is not found, then do this if (outfile.is_open()) { outfile << "No Word Ladder Found!!"; cout << "No Word Ladder Found!!"; } }
/*! Create a new expression by parsing the given string. */ mapper_expr mapper_expr_new_from_string(const char *str, int input_is_float, int output_is_float, int vector_size) { const char *s = str; if (!str) return 0; stack_obj_t stack[STACK_SIZE]; int top = -1; exprnode result = 0; const char *error_message = 0; token_t tok; int i, next_token = 1; int var_allowed = 1; float oldest_samps = 0; PUSHSTATE(EXPR); PUSHSTATE(YEQUAL_EQ); PUSHSTATE(YEQUAL_Y); while (top >= 0) { if (next_token && expr_lex(&s, &tok)) {FAIL("Error in lexical analysis.");} next_token = 0; if (stack[top].type == ST_NODE) { if (top==0) SUCCESS(stack[top].node); if (stack[top-1].type == ST_STATE) { if (top >= 2 && stack[top-2].type == ST_NODE) { if (stack[top-1].type == ST_STATE && (stack[top-1].state == EXPR_RIGHT || stack[top-1].state == TERM_RIGHT || stack[top-1].state == CLOSE_PAREN)) { collapse_expr_to_left(&stack[top-2].node, stack[top].node, 1); POP(); } else if (stack[top-1].type == ST_STATE && stack[top-1].state == CLOSE_HISTINDEX) { die_unless(stack[top-2].node->tok.type == TOK_VAR, "expected VAR two-down on the stack.\n"); die_unless(!stack[top].node->next && (stack[top].node->tok.type == TOK_INT || stack[top].node->tok.type == TOK_FLOAT), "expected lonely INT or FLOAT expression on the stack.\n"); if (stack[top].node->tok.type == TOK_FLOAT) stack[top-2].node->history_index = (int)stack[top].node->tok.f; else stack[top-2].node->history_index = stack[top].node->tok.i; /* Track the oldest history reference in order * to know how much buffer needs to be * allocated for this expression. */ if (oldest_samps > stack[top-2].node->history_index) oldest_samps = stack[top-2].node->history_index; exprnode_free(stack[top].node); POP(); } else if (stack[top-1].type == ST_STATE && stack[top-1].state == CLOSE_VECTINDEX) { die_unless(stack[top-2].node->tok.type == TOK_VAR, "expected VAR two-down on the stack.\n"); die_unless(!stack[top].node->next && (stack[top].node->tok.type == TOK_INT || stack[top].node->tok.type == TOK_FLOAT), "expected lonely INT or FLOAT expression on the stack.\n"); if (stack[top].node->tok.type == TOK_FLOAT) stack[top-2].node->vector_index = (int)stack[top].node->tok.f; else stack[top-2].node->vector_index = stack[top].node->tok.i; if (stack[top-2].node->vector_index > 0) {FAIL("Vector indexing not yet implemented.");} if (stack[top-2].node->vector_index < 0 || stack[top-2].node->vector_index >= vector_size) {FAIL("Vector index outside input size.");} exprnode_free(stack[top].node); POP(); } } else { // swap the expression down the stack stack_obj_t tmp = stack[top-1]; stack[top-1] = stack[top]; stack[top] = tmp; } } #if TRACING printstack(&stack[0], top); #endif continue; } switch (stack[top].state) { case YEQUAL_Y: if (tok.type == TOK_VAR && tok.var == 'y') POP(); else {FAIL("Error in y= prefix.");} next_token = 1; break; case YEQUAL_EQ: if (tok.type == TOK_OP && tok.op == '=') { POP(); } else { {FAIL("Error in y= prefix.");} } next_token = 1; break; case EXPR: POP(); PUSHSTATE(EXPR_RIGHT); PUSHSTATE(TERM); break; case EXPR_RIGHT: if (tok.type == TOK_OP) { POP(); if (tok.op == '+' || tok.op == '-') { APPEND_OP(tok); PUSHSTATE(EXPR); next_token = 1; } } else POP(); break; case TERM: POP(); PUSHSTATE(TERM_RIGHT); PUSHSTATE(VALUE); break; case TERM_RIGHT: if (tok.type == TOK_OP) { POP(); if (tok.op == '*' || tok.op == '/' || tok.op == '%') { APPEND_OP(tok); PUSHSTATE(TERM); next_token = 1; } } else POP(); break; case VALUE: if (tok.type == TOK_INT) { POP(); PUSHEXPR(tok, 0); next_token = 1; } else if (tok.type == TOK_FLOAT) { POP(); PUSHEXPR(tok, 1); next_token = 1; } else if (tok.type == TOK_VAR) { if (var_allowed) { POP(); PUSHEXPR(tok, input_is_float); PUSHSTATE(VAR_RIGHT); next_token = 1; } else {FAIL("Unexpected variable reference.");} } else if (tok.type == TOK_OPEN_PAREN) { POP(); PUSHSTATE(CLOSE_PAREN); PUSHSTATE(EXPR); next_token = 1; } else if (tok.type == TOK_FUNC) { POP(); if (tok.func == FUNC_UNKNOWN) {FAIL("Unknown function.");} else { PUSHEXPR(tok, 1); int arity = function_table[tok.func].arity; if (arity > 0) { PUSHSTATE(CLOSE_PAREN); PUSHSTATE(EXPR); for (i=1; i < arity; i++) { PUSHSTATE(COMMA); PUSHSTATE(EXPR); } PUSHSTATE(OPEN_PAREN); } next_token = 1; } } else if (tok.type == TOK_OP && tok.op == '-') { POP(); PUSHSTATE(NEGATE); PUSHSTATE(VALUE); next_token = 1; } else {FAIL("Expected value.");} break; case NEGATE: POP(); // insert '0' before, and '-' after the expression. // set is_float according to trailing operator. if (stack[top].type == ST_NODE) { token_t t; t.type = TOK_INT; t.i = 0; exprnode e = exprnode_new(&t, 0); t.type = TOK_OP; t.op = '-'; e->next = exprnode_new(&t, 0); collapse_expr_to_left(&e, stack[top].node, 1); stack[top].node = e; } else {FAIL("Expected to negate an expression.");} break; case VAR_RIGHT: if (tok.type == TOK_OPEN_SQUARE) { POP(); PUSHSTATE(VAR_VECTINDEX); } else if (tok.type == TOK_OPEN_CURLY) { POP(); PUSHSTATE(VAR_HISTINDEX); } else POP(); break; case VAR_VECTINDEX: POP(); if (tok.type == TOK_OPEN_SQUARE) { var_allowed = 0; PUSHSTATE(CLOSE_VECTINDEX); PUSHSTATE(EXPR); next_token = 1; } break; case VAR_HISTINDEX: POP(); if (tok.type == TOK_OPEN_CURLY) { var_allowed = 0; PUSHSTATE(CLOSE_HISTINDEX); PUSHSTATE(EXPR); next_token = 1; } break; case CLOSE_VECTINDEX: if (tok.type == TOK_CLOSE_SQUARE) { var_allowed = 1; POP(); PUSHSTATE(VAR_HISTINDEX); next_token = 1; } else {FAIL("Expected ']'.");} break; case CLOSE_HISTINDEX: if (tok.type == TOK_CLOSE_CURLY) { var_allowed = 1; POP(); PUSHSTATE(VAR_VECTINDEX); next_token = 1; } else {FAIL("Expected '}'.");} break; case CLOSE_PAREN: if (tok.type == TOK_CLOSE_PAREN) { POP(); next_token = 1; break; } else {FAIL("Expected ')'.");} break; case COMMA: if (tok.type == TOK_COMMA) { POP(); // find previous expression on the stack for (i=top-1; i>=0 && stack[i].type!=ST_NODE; --i) {}; if (i>=0) { collapse_expr_to_left(&stack[i].node, stack[top].node, 0); POP(); } next_token = 1; } else {FAIL("Expected ','.");} break; case OPEN_PAREN: if (tok.type == TOK_OPEN_PAREN) { POP(); next_token = 1; } else {FAIL("Expected '('.");} break; case END: if (tok.type == TOK_END) { POP(); break; } else {FAIL("Expected END.");} default: FAIL("Unexpected parser state."); break; } #if TRACING printstack(&stack[0], top); #endif } done: if (!result) { if (error_message) printf("%s\n", error_message); goto cleanup; } // We need a limit, but this is a bit arbitrary. if (oldest_samps < -100) { trace("Expression contains history reference of %f\n", oldest_samps); goto cleanup; } // Coerce the final output if necessary exprnode e = result; while (e->next) e = e->next; if (e->is_float && !output_is_float) { token_t coerce; coerce.type = TOK_TOINT32; e->next = exprnode_new(&coerce, 0); e->next->is_float = 0; } else if (!e->is_float && output_is_float) { token_t coerce; coerce.type = TOK_TOFLOAT; e->next = exprnode_new(&coerce, 0); e->next->is_float = 1; } /* Special case: if this is a vector expression, we currently do * not completely support it. However, we can "fake" vector * operations by performing the entire expression element-wise. * In this case, we have to disallow any vector indexing, so here * we scan the compiled expression and check for it. This will be * removed in a future version. */ if (vector_size > 1) { e = result; while (e) { if (e->tok.type == TOK_VAR && e->vector_index > 0) { trace("vector indexing not yet implemented\n"); goto cleanup; } e = e->next; } } mapper_expr expr = malloc(sizeof(struct _mapper_expr)); expr->node = result; expr->vector_size = 1; expr->history_size = (int)ceilf(-oldest_samps)+1; expr->history_pos = -1; expr->input_history = calloc(1, sizeof(mapper_signal_value_t) * vector_size * expr->history_size); expr->output_history = calloc(1, sizeof(mapper_signal_value_t) * expr->history_size); return expr; cleanup: for (i=0; i<top; i++) { if (stack[i].type == ST_NODE) exprnode_free(stack[i].node); } return 0; }
ReturnValue alphaBeta(Configuration v, int alpha, int beta, int depth){ // int counter=0; if (DEBUG_STACK){ printstack(); printf("alphabeta a=%d b=%d d=%d\n", alpha, beta, depth); // printBoardNonBlock(v); } ++stackcount; HashRetVal s; s=retrieve(v); ReturnValue ret; ReturnValue temp; ret.alpha=alpha; ret.beta=beta; if (s!=NULL) { switch (s->type){ case EXACT: if (s->lowerbound>=beta) { ret.value=s->lowerbound; ret.move=s->mv; --stackcount; if (DEBUG_STACK){ printstack(); printf("hit exact 1\n"); } return ret; } if (s->upperbound<=alpha) { ret.value=s->upperbound; ret.move=s->mv; --stackcount; if (DEBUG_STACK){ printstack(); printf("hit exact 2\n"); } return ret; } ret.alpha=max(alpha, s->lowerbound); ret.beta=min(beta, s->upperbound); ret.move=s->mv; break; case FAIL_LOW: if (s->upperbound<=alpha) { ret.value=s->upperbound; ret.move=s->mv; --stackcount; if (DEBUG_STACK){ printstack(); printf("hit fail low\n"); } return ret; } break; case FAIL_HIGH: if (s->lowerbound>=beta) { ret.value=s->lowerbound; ret.move=s->mv; --stackcount; if (DEBUG_STACK){ printstack(); printf("hit fail high\n"); } return ret; } break; default: break; } free(s); } if (depth==0) { ChildIterator itr=getExpansion(v); ret.value=getCurrentValue(itr); ret.move=getCurrent(itr); releaseChildIterator(itr); if (getType(v)==MAXNODE) updateMoveHeuristic(v, ret.move.x, ret.move.y, ret.value); else updateMoveHeuristic(v, ret.move.x, ret.move.y, -ret.value); if (DEBUG_STACK){ printBoardNonBlock(v); printstack(); printf("eval %d\n", ret.value); printstack(); printf("(%d, %d)\n", ret.move.x, ret.move.y); } } else if (getType(v)==MAXNODE) { // printf("*\n"); ChildIterator itr=getExpansion(v); // printf("e: %d %d %d\n", getCurrent(itr).x, getCurrent(itr).y, depth); int a=alpha; ret.value=-FIVE_SCORE; ret.move=getCurrent(itr); if (getCurrentValue(itr)>=FIVE_SCORE){ ret.value=FIVE_SCORE; } else { while (itr!=NULL && ret.value<beta) { // printf("depth=%d, move=%d %d\n", // depth, getCurrent(itr).x, // getCurrent(itr).y); if (tickTimer()==0) break; applyMove(v, getCurrent(itr)); // printBoardNonBlock(v); if (DEBUG_STACK){ printstack(); printf("black trying %d %d\n", getCurrent(itr).x, getCurrent(itr).y); } switch (getChildrenCount(itr)){ // case 1: /* ++quadcount; temp=alphaBeta(v, a, beta, depth-((doublecount & 3)==0));*/ case 1: // case 2: ++doublecount; temp=alphaBeta(v, a, beta, depth-1); --doublecount; break; default: temp=alphaBeta(v, a, beta, depth-1); break; } updateMoveHeuristic(v, temp.move.x, temp.move.y, temp.value); if (DEBUG_STACK){ printstack(); printf("black try %d %d, result=%d\n", getCurrent(itr).x, getCurrent(itr).y, temp.value); } if (temp.value>ret.value) { ret.value=temp.value; ret.move=getCurrent(itr); // printf("current black move = %d %d\n", ret.move.x, ret.move.y); } undoMove(v, getCurrent(itr)); // printBoard(v); if (a<ret.value){ a=ret.value; } // printf("a=%d ret.value=%d\n", a, ret.value); // TODO to be verified /* if (temp.value<=-INFINITY){ ++counter; } if (counter>2) break;*/ getNext(&itr); // printf("e: %d %d\n", itr->current.x, itr->current.y); } if (DEBUG_STACK){ if (ret.value>=beta){ printstack(); printf("pruned\n"); } } } releaseChildIterator(itr); } else { // printf("-\n"); ChildIterator itr=getExpansion(v); // printf("n: %d %d %d\n", getCurrent(itr).x, getCurrent(itr).y, depth); int b=beta; ret.value=FIVE_SCORE; ret.move=getCurrent(itr); if (getCurrentValue(itr)<=-FIVE_SCORE){ ret.value=-FIVE_SCORE; } else { while (itr!=NULL && ret.value>alpha) { if (tickTimer()==0) break; applyMove(v, getCurrent(itr)); if (DEBUG_STACK){ printstack(); printf("white trying %d %d\n", getCurrent(itr).x, getCurrent(itr).y); } if (getChildrenCount(itr)<=1){ ++doublecount; temp=alphaBeta(v, alpha, b, depth-1); --doublecount; } else { temp=alphaBeta(v, alpha, b, depth-1); } updateMoveHeuristic(v, temp.move.x, temp.move.y, -temp.value); if (DEBUG_STACK){ printstack(); printf("white try %d %d, result=%d\n", getCurrent(itr).x, getCurrent(itr).y, temp.value); printf("retval=%d\n", ret.value); } if (temp.value<ret.value){ ret.value=temp.value; ret.move=getCurrent(itr); // printf("current white move = %d %d\n", ret.move.x, ret.move.y); } undoMove(v, getCurrent(itr)); if (b>ret.value){ b=ret.value; } // printf("a=%d ret.value=%d\n", b, ret.value); /* if (ret.value<=-INFINITY-10) break;*/ // TODO to be verified /* if (temp.value>=INFINITY){ ++counter; } if (counter>2) break;*/ getNext(&itr); } if (DEBUG_STACK){ if (ret.value<=alpha){ printstack(); printf("pruned\n"); } } } releaseChildIterator(itr); } if (ret.value<=alpha && getType(v)==MINNODE) { /* fail low */ v->upperbound=ret.value; if (depth>0) store(v, ret.move, FAIL_LOW); /* Fail low result implies an upper bound */ } else if (ret.value>alpha && ret.value<beta) { /* accurate window */ v->upperbound=v->lowerbound=ret.value; if (depth>0) store(v, ret.move, EXACT); } else if (getType(v)==MINNODE && ret.value>=MAXNODE){ /* fail high */ v->lowerbound=ret.value; if (depth>0) store(v, ret.move, FAIL_HIGH); } /* printstack(); printf("ab return %d (%d,%d))\n", ret.value, ret.move.x, ret.move.y);*/ // getchar(); --stackcount; return ret; }
void opal_backtrace_print(FILE *file) { printstack(fileno(file)); }