QString CodeGenerator::generateCode(const DraggableElement* element, int sub) { QString str; bool stop = false; for(const DraggableElement* next = element; next && !stop; next = next->getNextElem()) { QString name = next->getIdentifier(); // TODO: indent should be more dynamic QString tmp; if (next->getType() == DraggableElement::Hat && _events.contains(name)) { tmp = indentCode(&_events[name]._code, sub, generateCode(next->getNextElem(), sub+1)); if(_eventCounters.contains(name)) _eventCounters[name]++; else _eventCounters[name] = 1; tmp.replace(QLatin1String("%counter%"), QString::number(_eventCounters[name])); stop = true; } else if (next->getType() == DraggableElement::Wrapper && _controls.contains(name)) { tmp = indentCode(&_controls[name], sub, generateCode(next->getWrapElem(), sub+1)); } else if (next->getType() == DraggableElement::Command && _commands.contains(name)) { tmp = indentCode(&_commands[name], sub); } else { qDebug() << "block: " << name << "not supported yet"; str += indent(sub) + "pass\n"; continue; } if(tmp.contains(QLatin1String("%indent_counter%"))) { tmp.replace(QLatin1String("%indent_counter%"), QString::number(_indentCounter)); _indentCounter++; } const std::vector<ParamBase*>* params = next->getParamsVector(); for(std::vector<ParamBase*>::const_iterator it = params->begin(); it != params->end(); it++) { tmp = tmp.arg(generateParam(*it)); } str += tmp; } if(str.isEmpty()) { str = indent(sub) + "pass\n"; } return str; }
void compile(){ fileSave(); SendMessage(hNotifs, WM_SETTEXT, 0, (LPARAM) ""); FILE *fp; // file input FILE *fo; // file output TokenList * tokenList; fp = fopen(openedFileName, "r"); fo = fopen("SYMBOL TABLE.txt", "w"); tokenList = createTokenList(); initLexer(fp, fo); initToken(tokenList); readToken(); generateCode(tokenList); fclose(fp); fclose(fo); if(strcmp(errorList[0], "") == 0){ SendMessage(hNotifs, WM_SETTEXT, 0, (LPARAM) "No error"); hasError = 0; } else { hasError = 1; int i; for(i = 0; i < sizeof(errorList) / sizeof(errorList[0]); i++){ int index = GetWindowTextLength(hNotifs); SetFocus(hNotifs); SendMessageA(hNotifs, EM_SETSEL, (WPARAM)index, (LPARAM)index); // set selection - end of text SendMessageA(hNotifs, EM_REPLACESEL, 0, (LPARAM) errorList[i]); // append! } } memset(errorList, 0, sizeof(errorList) / sizeof(errorList[0])); }
/** Generate all output in LLnextgen style This function opens the output files, and writes all necessary output to them. */ void generateLLgenStyle(void) { int i; openOutputs(); /* First generate all the default declarations and defines. */ generateHeaderFile(hOutput); generateDefaultGlobalDeclarations(cOutput, NULL); /* We do this here, because for LLnextgen style output we don't want this in generateDefaultGlobalDeclarations. */ if (!option.noLLreissue) tfputs(cOutput, "#define LL_NEW_TOKEN (-2)\n"); generateDirectiveCodeAtEnd(cOutput); /* These are necessary PER .c file */ for (i = 0; i < listSize(outputs); i++) { FileListItem *lOutput = (FileListItem *) listIndex(outputs, i); generateDefaultLocalDeclarations(lOutput->output, hOutput->name); generateDirectiveDeclarations(lOutput->output); } /* Now where ready to generate the code. */ generateCode(); closeFile(hOutput, true); closeFile(cOutput, true); for (i = 0; i < listSize(outputs); i++) { FileListItem *lOutput = (FileListItem *) listIndex(outputs, i); closeFile(lOutput->output, true); free(lOutput); } deleteList(outputs); }
void Translator::translate() { // Find all empty lines in the file // indexEmptyLines(); // Find all data and code labels // classifyLabels(); // Begin generating output // // Put required header // sourceOutput << "#include \"SMB.hpp\"\n\n"; // Generate constant declarations first // generateConstantDeclarations(); // Generate data declarations next // generateDataDeclarations(); // Finally, generate code // generateCode(); }
int encode(UCHAR *encodeData, CodeInfo *codeInfo, UCHAR *data, int dataLen) { // 各バイト値の発生回数を数える TreeNode nodes[NODE_SIZE]; memset(nodes, 0, sizeof(nodes)); for (int i = 0; i < 22; i++) { nodes[i].chr = charSet[i]; } for (int i = 0; i < dataLen; i++) { nodes[convertChar2Index(data[i])].occurrence++; } // ハフマン木を作成 int root = CreateHuffmanTree(nodes, 22 - 1); // 深さ優先探索でバイト値→符号情報を作成 int codeInfoNum = generateCode(codeInfo, nodes, root, 0, 0); if (codeInfoNum > 22) { // charSetで指定されている文字以外が含まれたデータを読み込もうとしている return -1; } // 圧縮データをメモリに書き込み int encodeDataLen = writeEncodeData(encodeData, nodes, root, codeInfo, data, dataLen); return encodeDataLen; }
void animate_code_on() { if (watch_otp_count) strcpy(pin_text, generateCode(otp_keys[otp_selected], timezone_offset)); else strcpy(pin_text, "123456"); otp_updated_at_tick = otp_update_tick; GRect start = text_pin_rect; switch(animation_direction) { case UP : start.origin.y += display_bounds.size.h; break; case DOWN : start.origin.y -= display_bounds.size.h; break; case LEFT : start.origin.x += display_bounds.size.w; break; case RIGHT : start.origin.x -= display_bounds.size.w; break; } animate_layer(text_layer_get_layer(text_pin_layer), AnimationCurveEaseOut, &start, &text_pin_rect, 300, on_animation_stopped_callback); }
void recode(char *secretKey, bool keyChange) { static unsigned int lastCode = 0; static unsigned short oldTimeZoneIndex = 255; static unsigned int lastQuantizedTimeGenerated = 0; static int offset; static char offsetText[] = "-12:00"; const char *key = secretKey; if(timeZoneIndex != oldTimeZoneIndex) { text_layer_set_text(currentTime, tz_names[timeZoneIndex]); oldTimeZoneIndex = timeZoneIndex; offset = (tz_offsets[timeZoneIndex]+(isDST ? 3600 : 0)); snprintf(offsetText, sizeof(offsetText), "%d:%.2d", offset/(60*60), abs((offset/60)%60)); text_layer_set_text(currentOffset, offsetText); } unsigned long utcTime = time(NULL)-offset; unsigned int quantized_time = utcTime/30; //Assuming generating a code is expensive, only generate it if //the time has changed or the key has changed. if(quantized_time == lastQuantizedTimeGenerated && !keyChange) return; lastQuantizedTimeGenerated = quantized_time; unsigned int code = generateCode(key, quantized_time); if(lastCode != code) { redraw(code); freshCode = true; } }
int generateCode(CodeInfo *codeInfo, TreeNode *node, int nodeIndex, int code, int codeSize) { if (node[nodeIndex].left == 0 && node[nodeIndex].right == 0) { codeInfo[nodeIndex].code = code; codeInfo[nodeIndex].codeSize = codeSize; return 1; } else { int count; count = generateCode(codeInfo, node, node[nodeIndex].left, code << 1, codeSize + 1); count += generateCode(codeInfo, node, node[nodeIndex].right, (code << 1) + 1, codeSize + 1); return count; } }
int main(int argc, char **argv) { int c; bool debug_mode = false; bool verbose_mode = false; while ((c = getopt(argc, argv, "dv")) != -1) { switch (c) { case 'd': debug_mode = true; break; case 'v': verbose_mode = true; break; default: /* '?' */ fprintf(stderr, "Anvendelse: %s [-d] [-v]\n", argv[0]); exit(1); } } lineno = 1; if (verbose_mode) { fprintf(stderr, "Leksikalsk og syntaktisk analyse udføres ...\n"); } int parse = yyparse(); if (parse != 0) { fprintf(stderr, "Der opstod en fejl under den leksikalske eller syntaktiske analyse.\n"); return 1; } if (verbose_mode) { fprintf(stderr, "Leksikalsk og syntaktisk analyse blev udført.\n"); } if (debug_mode) { fprintf(stderr, "Pæn udskrift efter leksikalsk og syntaktisk analyse:\n"); prettyMAIN(theprogram); } if (verbose_mode) { fprintf(stderr, "Semantisk analyse udføres ...\n"); } SymbolTable *mscope = initSymbolTable(); int traversalerr = traversal(theprogram, mscope); if (traversalerr != 0) { fprintf(stderr, "Der opstod i alt %d fejl under den semantiske analyse.\n", traversalerr); return 1; } if (verbose_mode) { fprintf(stderr, "Semantisk analyse blev udført.\n"); } if (debug_mode) { dumpsymbol(theprogram, mscope); } if (verbose_mode) { fprintf(stderr, "Kodegenerering udføres ...\n"); } LINKED_LIST *l = generateCode(theprogram, mscope); l = registerAllocation(l); if (verbose_mode) { fprintf(stderr, "Kodegenerering blev udført.\n"); } emission(l); return 0; }
MIPS::MIPS(std::string _fileName){ keywords = {{"if",true},{"goto",true},{"param",true},{"call",true}}; std::ofstream out(("mips_"+_fileName).c_str()); freopen(file_name.c_str(), "r", stdin); string s; generateCode(); fclose(stdin); }
/** * Compile a signal * @param sig the signal expression to compile. * @return the C code translation of sig as a string */ string DocCompiler::CS (Tree sig, int priority) { string code; if (!getCompiledExpression(sig, code)) { // not compiled yet. code = generateCode(sig, priority); setCompiledExpression(sig, code); } return code; }
Exception::Exception(unsigned code, const QString msg, const char *file, const int line) { this->_msg = msg; this->file = file; this->line = line; this->userCode = code; extractCore(); generateCode(); Logger::log("Error at " + QTime::currentTime().toString() + ": " + description()); }
/* * Process input from a stream. */ static void processInput(FILE *stream, FILE *outstream) { char buffer[BUFSIZ]; while(readLine(buffer, stream)) { if(parseRule(buffer)) { generateCode(outstream); } } }
// **************************************************************************** // Constructor: XMLEdit::XMLEdit // // Programmer: Jeremy Meredith // Creation: October 17, 2002 // // Modifications: // Brad Whitlock, Fri Mar 7 13:19:55 PST 2008 // Added "Generate code" menu option. // // Cyrus Harrison, Thu May 15 16:00:46 PDT 200 // First pass at porting to Qt 4.4.0 // // **************************************************************************** XMLEdit::XMLEdit(const QString &file, QWidget *p) : QMainWindow(p) { setWindowTitle(tr("XMLEdit: %1").arg(file)); QMenu *filemenu = menuBar()->addMenu(tr("&File")); filemenu->addAction( tr("&New"), this, SLOT(newdoc()), QKeySequence(Qt::CTRL + Qt::Key_N)); filemenu->addAction(tr("&Open"), this, SLOT(open()), QKeySequence(Qt::CTRL + Qt::Key_O)); filemenu->addAction(tr("&Save"), this, SLOT(save()), QKeySequence(Qt::CTRL + Qt::Key_S)); filemenu->addAction(tr("Save &as"), this, SLOT(saveAs()), QKeySequence(Qt::CTRL + Qt::Key_A)); filemenu->addSeparator(); filemenu->addAction(tr("&Generate code"), this, SLOT(generateCode()), QKeySequence(Qt::CTRL + Qt::Key_G)); filemenu->addSeparator(); filemenu->addAction( tr("E&xit"), this, SLOT(close()), QKeySequence(Qt::CTRL + Qt::Key_X) ); tabs = new QTabWidget(this); tabs->setContentsMargins(5,5,5,5); plugintab = new XMLEditPlugin(this); tabs->addTab(plugintab, tr("Plugin")); makefiletab = new XMLEditMakefile(this); tabs->addTab(makefiletab, tr("CMake")); attributetab = new XMLEditAttribute(this); tabs->addTab(attributetab, tr("Attribute")); enumstab = new XMLEditEnums(this); tabs->addTab(enumstab, tr("Enums")); fieldstab = new XMLEditFields(this); tabs->addTab(fieldstab, tr("Fields")); functionstab = new XMLEditFunctions(this); tabs->addTab(functionstab, tr("Functions")); constantstab = new XMLEditConstants(this); tabs->addTab(constantstab, tr("Constants")); includestab = new XMLEditIncludes(this); tabs->addTab(includestab, tr("Includes")); codetab = new XMLEditCode(this); tabs->addTab(codetab, tr("Code")); connect(tabs, SIGNAL(currentChanged(int)), this, SLOT(updateTab(int))); setCentralWidget(tabs); codeGenerationWindow = 0; OpenFile(file); }
void CodeGenerator::generateCode(const Node *node) { if(node == 0) return; switch(node->kind) { case PROGRAM: symbolTable.openNewScope(); break; case VAR_DEC: printVarDec(node); break; case FUNC_DEC: printFuncDec(node); break; } generateCode(node->son); generateCode(node->bro); }
/** * Constructor. * @param parent the parent (wizard) of this wizard page */ CodeGenStatusPage::CodeGenStatusPage(QWidget *parent) : QWizardPage(parent), m_generationDone(false) { setTitle(i18n("Status of Code Generation Progress")); setSubTitle(i18n("Press the button Generate to start the code generation.\nCheck the success state for every class.")); setupUi(this); ui_tableWidgetStatus->setColumnCount(3); connect( ui_pushButtonGenerate, SIGNAL(clicked()), this, SLOT(generateCode()) ); }
int main(int argc, char *argv[]) { if (argc != 4) { printf("Usage: %s <source file or directory> <destination file> <marker>\nExample: %s specs ../TLValues.hpp TLValues\n", argv[0], argv[0]); return 0; } QCoreApplication app(argc, argv); static const QStringList arguments = app.arguments(); static const int indentation = 8; QString indentationStr(indentation, QChar(' ')); QString code; QDir argDir(arguments.at(1)); if (argDir.exists()) { const QStringList filesList = argDir.entryList(QStringList() << "*.txt", QDir::Files|QDir::Readable, QDir::Name); for (int i = 0; i < filesList.count(); ++i) { bool closeEnum = i == filesList.count() - 1; code.append(indentationStr + QString("// From %1:\n").arg(filesList.at(i))); code.append(generateCode(argDir.absolutePath() + "/" + filesList.at(i), indentation, closeEnum)); if (!closeEnum) { code.append(QChar('\n')); } } } else { code.append(generateCode(arguments.at(1), indentation, /* closeEnum */ true)); } if (replacingHelper(arguments.at(2), indentation, arguments.at(3), code)) { printf("File successfully updated.\n"); } return 0; }
bool CodeDialog::showCodeDialog(const QDesignerFormWindowInterface *fw, QWidget *parent, QString *errorMessage) { QString code; if (!generateCode(fw, &code, errorMessage)) return false; CodeDialog dialog(parent); dialog.setWindowTitle(tr("%1 - [Code]").arg(fw->mainContainer()->windowTitle())); dialog.setCode(code); dialog.setFormFileName(fw->fileName()); dialog.exec(); return true; }
QString CodeGenerator::generateSprite(const Sprite *sprite, bool stage) { QString str; _eventCounters.clear(); _indentCounter = 1; QStringList *costumeRegSnippet = &_snippets["costume_register"]; QStringList *constructSnippet = stage ? &_snippets["construct_stage"] : &_snippets["construct"]; QString costumeRegister; for (CostumeVector::const_iterator it = sprite->getCostumeVector()->begin(); it != sprite->getCostumeVector()->end(); it++) { costumeRegister += indentCode(costumeRegSnippet, 2) .replace(QLatin1String("%entity%"), QLatin1String("self")) .replace(QLatin1String("%name%"), addQuotes((*it)->getName())) .replace(QLatin1String("%file%"), addQuotes((*it)->getFilename())); } // create class file str += indentCode(&_snippets["import"]); str += indentCode(&_snippets["class"]).replace(QLatin1String("%name%"), sprite->getName()); str += indentCode(constructSnippet, 1, costumeRegister); str += "%events%\n"; // check every block for "header"-block const DragElemVector *eleVec = sprite->getDragElemVector(); for(DragElemVector::const_iterator elemIt = eleVec->begin(); elemIt != eleVec->end(); elemIt++) { if ((*elemIt)->getType() == DraggableElement::Hat) { str += generateCode(*elemIt, 1) + '\n'; } } // add Event registration QString events; for(QMap<QString, int>::const_iterator eventIt = _eventCounters.constBegin(); eventIt != _eventCounters.constEnd(); eventIt++) { for(int i = 1; i <= eventIt.value(); i++) { QString event = indent(2) + _events[eventIt.key()]._register + "\n"; events += event.replace(QLatin1String("%counter%"), QString::number(i)); } } str.replace(QLatin1String("%events%"), events); return str; }
/** * Compile a signal * @param sig the signal expression to compile. * @return the C code translation of sig as a string */ string VectorCompiler::CS (Tree sig) { string code; //cerr << "ENTER VectorCompiler::CS : "<< ppsig(sig) << endl; if (!getCompiledExpression(sig, code)) { code = generateCode(sig); //cerr << "CS : " << code << " for " << ppsig(sig) << endl; setCompiledExpression(sig, code); } else { // we require an already compiled expression // therefore we must update the dependencies of // the current loop int i; Tree x, d, r; Loop* ls; Loop* tl = fClass->topLoop(); if (fClass->getLoopProperty(sig,ls)) { // sig has a loop property //cerr << "CASE SH : fBackwardLoopDependencies.insert : " << tl << " --depend(A)son--> " << ls << endl; tl->fBackwardLoopDependencies.insert(ls); } else if (isSigFixDelay(sig, x, d) && fClass->getLoopProperty(x,ls)) { //cerr << "CASE DL : fBackwardLoopDependencies.insert : " << tl << " --depend(B)son--> " << ls << endl; tl->fBackwardLoopDependencies.insert(ls); } else if (isSigFixDelay(sig, x, d) && isProj(x, &i, r) && fClass->getLoopProperty(r,ls)) { //cerr << "CASE DR : fBackwardLoopDependencies.insert : " << tl << " --depend(B)son--> " << ls << endl; tl->fBackwardLoopDependencies.insert(ls); } else if (isProj(sig, &i, r) && fClass->getLoopProperty(r,ls)) { //cerr << "CASE R* : fBackwardLoopDependencies.insert : " << tl << " --depend(B)son--> " << ls << endl; tl->fBackwardLoopDependencies.insert(ls); } else { if (isProj(sig, &i, r)) { //cerr << "SYMBOL RECURSIF EN COURS ??? " << *r << endl; } else if (getCertifiedSigType(sig)->variability()<kSamp) { //cerr << "SLOW EXPRESSION " << endl; } else { //cerr << "Expression absorbée" << *sig << endl; } } } //cerr << "EXIT VectorCompiler::CS : "<< ppsig(sig) << "---code---> " << code << endl; return code; }
void keyboard(unsigned char key , int x ,int y) { if(key == 'c') { current_point = 0; current_shape = -1; selected_point = -1; } else if (key == 'g') { generateCode(); } else if (key == 'n') { newShape(); } else if ( key == '1') { shapes_array[current_shape][2] = GL_LINES; } else if ( key == '2') { shapes_array[current_shape][2] = GL_LINE_STRIP; } else if ( key == '3') { shapes_array[current_shape][2] = GL_LINE_LOOP; } else if ( key == '4') { shapes_array[current_shape][2] = GL_POINTS; } else if ( key == '5') { shapes_array[current_shape][2] = 6 ; } glutPostRedisplay(); }
int main(int argc, char **argv) { if(argc != 4) { printf("Syntax: %s <function> <binary> <map>\n", argv[0]); return 1; } std::string strFunction = argv[1]; std::string strBinaryFile = argv[2]; std::string strMapFile = argv[3]; if(!Symbols::parseSymFile(strMapFile)) { return 0; } Function aFunction; aFunction.parseFromFile(strFunction, strBinaryFile); //dumpInstructions(collInstList); resolveDelaySlots(aFunction.m_collInstList); //dumpInstructions(collInstList); aFunction.detectStackOffset(); updateJumpTargets(aFunction.m_collInstList); while(optimizeInstructions(aFunction)) { aFunction.applyDelayedInserts(); aFunction.applyDelayedDeletes(); updateJumpTargets(aFunction.m_collInstList); //dumpInstructions(collInstList); aFunction.uOptimizationPasses++; } //dumpInstructions(collInstList); FILE *pCodeFile = fopen("code.c", "w"); generateCode(pCodeFile, aFunction); fclose(pCodeFile); return 0; }
/*-----------------------------------------------------------------*/ int main(int argc, char *const argv[]) { if (argc != 2) { fprintf(stderr, "usage: ga-cmd keyfile\n"); return 1; } char *key; int keyLen; if (!(keyLen = load_key(argv[1], &key))) { return 1; } int verf_code = generateCode(key, time(0) / 30); fprintf(stderr, "%s: ", argv[1]); fflush(stderr); fprintf(stdout, "%d", verf_code); fflush(stdout); fprintf(stderr, "\n"); return EXIT_SUCCESS; }
static void multi_code_menu_draw_row_callback(GContext *ctx, Layer *cell_layer, MenuIndex *cell_index, void *context) { GRect bounds = layer_get_bounds(cell_layer); graphics_context_set_fill_color(ctx, bg_color); graphics_context_set_text_color(ctx, fg_color); #ifdef PBL_COLOR if (menu_cell_layer_is_highlighted(cell_layer)) { graphics_context_set_fill_color(ctx, fg_color); graphics_context_set_text_color(ctx, bg_color); graphics_fill_rect(ctx, bounds, 0, 0); } #endif if (watch_otp_count >= 1) { graphics_draw_text(ctx, generateCode(otp_keys[cell_index->row], timezone_offset), font_pin.font, GRect(0, pin_origin_y, bounds.size.w, 30), GTextOverflowModeTrailingEllipsis, GTextAlignmentCenter, NULL); graphics_draw_text(ctx, otp_labels[cell_index->row], fonts_get_system_font(FONT_KEY_GOTHIC_18), GRect(0, 30, bounds.size.w, 25), GTextOverflowModeTrailingEllipsis, GTextAlignmentCenter, NULL); } else { graphics_draw_text(ctx, "123456", font_pin.font, GRect(0, pin_origin_y, bounds.size.w, 30), GTextOverflowModeTrailingEllipsis, GTextAlignmentCenter, NULL); graphics_draw_text(ctx, "EMPTY", fonts_get_system_font(FONT_KEY_GOTHIC_18), GRect(0, 30, bounds.size.w, 25), GTextOverflowModeTrailingEllipsis, GTextAlignmentCenter, NULL); } }
void Function::generateCode(const string& filename, bool generate_main) { // Detect a C++ ending vector<string> cpp_endings; cpp_endings.push_back(".cpp"); cpp_endings.push_back(".cxx"); cpp_endings.push_back(".cc"); cpp_endings.push_back(".cp"); cpp_endings.push_back(".c++"); for (vector<string>::const_iterator it=cpp_endings.begin(); it!=cpp_endings.end(); ++it) { if (filename.size()>it->size() && filename.compare(filename.size()-it->size(), it->size(), *it)==0) { casadi_warning("Function::generateCode: Detected C++ file ending " "(generated code is C, not C++)"); } } // Create a file std::ofstream cfile; cfile.open(filename.c_str()); generateCode(cfile, generate_main); cfile.close(); }
bool Application::compile(bool parseOnly) { delegate_->begin(); try { factorUnderscorePackage<Package>(); underscorePackage_->parse(); if (parseOnly) { return !hasError_; } analyse(underscorePackage_.get()); packagesLoadingOrder_.emplace_back(std::move(underscorePackage_)); underscorePackage_ = nullptr; } catch (CompilerError &ce) { error(ce); } if (!hasError_) { generateCode(); } delegate_->finish(); return !hasError_; }
int main() { //Opens the program FILE* prog = fopen("input.txt", "r"); //Opens file for program output output = fopen("output.txt", "w"); char list[2000][20]; //Scans program and converts to lexeme list int lexError = scan(prog); fclose(prog); if (lexError == -1) return 0; //Opens lexeme list to be parsed FILE* input = fopen("lexlist.txt", "r"); int size = 0; //Reads lexeme list while(!feof(input)) { fscanf(input, "%s", list[size]); size++; } fprintf(output, "A print out of the token (internal representation) file:\n\n"); int i; for (i = 0; i < size; i++) fprintf(output, "%s ", list[i]); fprintf(output, "\n\nAnd its symbolic representation:\n\n"); symbolRepresent(list, size); fprintf(output, "\n\n"); //Determines if program is syntactically correct and generates intermediate code int correct = program(list, size); if (correct) fprintf(output, "No errors, program is syntactically correct.\n\n"); else { symbolRepresent(list, err); fprintf(output, " ***** "); error(err2); return 0; } //Writes intermediate code to file generateCode(); //Runs intermediate code on virtual machine makeStack(); fclose(input); fclose(output); return 0; }
void Board::restartGame() { generateCode(); m_remaining = 10; }
int main(int argc, char **argv) { char *filename, *docFile, *codeDir, *srcSuffix, *flagFile, *consModule; char arg, *optarg, *buildFile, *apiFile, *xmlFile, *pyiFile; int optnr, exceptions, tracing, releaseGIL, parts, protHack, docs; int timestamp, was_flagFile; KwArgs kwArgs; FILE *file; sipSpec spec; stringList *versions, *backstops, *xfeatures, *extracts; /* Initialise. */ sipVersion = SIP_VERSION_STR; includeDirList = NULL; versions = NULL; backstops = NULL; xfeatures = NULL; buildFile = NULL; codeDir = NULL; docFile = NULL; srcSuffix = NULL; flagFile = NULL; was_flagFile = FALSE; apiFile = NULL; xmlFile = NULL; pyiFile = NULL; consModule = NULL; extracts = NULL; exceptions = FALSE; tracing = FALSE; releaseGIL = FALSE; parts = 0; kwArgs = NoKwArgs; protHack = FALSE; docs = FALSE; timestamp = TRUE; /* Parse the command line. */ optnr = 1; while ((arg = parseopt(argc, argv, "hVa:b:B:ec:d:fgI:j:km:op:Prs:t:Twx:X:y:z:", &flagFile, &optnr, &optarg)) != '\0') switch (arg) { case 'o': /* Generate docstrings. */ docs = TRUE; break; case 'p': /* The name of the consolidated module. */ consModule = optarg; break; case 'P': /* Enable the protected/public hack. */ protHack = TRUE; break; case 'a': /* Where to generate the API file. */ apiFile = optarg; break; case 'm': /* Where to generate the XML file. */ xmlFile = optarg; break; case 'y': /* Where to generate the .pyi file. */ pyiFile = optarg; break; case 'b': /* Generate a build file. */ buildFile = optarg; break; case 'B': /* Define a backstop. */ appendString(&backstops, optarg); break; case 'e': /* Enable exceptions. */ exceptions = TRUE; break; case 'g': /* Always release the GIL. */ releaseGIL = TRUE; break; case 'j': /* Generate the code in this number of parts. */ parts = parseInt(optarg,'j'); break; case 'z': /* Read a file for the next flags. */ if (flagFile != NULL) fatal("The -z flag cannot be specified in an argument file\n"); flagFile = optarg; was_flagFile = TRUE; break; case 'c': /* Where to generate the code. */ codeDir = optarg; break; case 'd': /* Where to generate the documentation. */ docFile = optarg; break; case 't': /* Which platform or version to generate code for. */ appendString(&versions,optarg); break; case 'T': /* * Disable the timestamp in the header of generated files. It is * now ignored apart from triggering a deprecation warning. */ timestamp = FALSE; break; case 'x': /* Which features are disabled. */ appendString(&xfeatures,optarg); break; case 'X': /* Which extracts are to be created. */ appendString(&extracts, optarg); break; case 'I': /* Where to get included files from. */ appendString(&includeDirList,optarg); break; case 'r': /* Enable tracing. */ tracing = TRUE; break; case 's': /* The suffix to use for source files. */ srcSuffix = optarg; break; case 'w': /* Enable warning messages. */ warnings = TRUE; break; case 'f': /* Warning messages are fatal. */ warnings_are_fatal = TRUE; break; case 'k': /* Allow keyword arguments in functions and methods. */ kwArgs = AllKwArgs; break; case 'h': /* Help message. */ help(); break; case 'V': /* Display the version number. */ version(); break; default: usage(); } if (optnr < argc) { file = NULL; filename = argv[optnr++]; if (optnr < argc) usage(); } else { file = stdin; filename = "stdin"; } /* Issue warnings after they (might) have been enabled. */ if (docFile != NULL) warning(DeprecationWarning, "the -d flag is deprecated\n"); if (kwArgs != NoKwArgs) warning(DeprecationWarning, "the -k flag is deprecated\n"); if (!timestamp) warning(DeprecationWarning, "the -T flag is ignored and deprecated\n"); if (was_flagFile) warning(DeprecationWarning, "the -z flag is deprecated\n"); /* Parse the input file. */ parse(&spec, file, filename, versions, backstops, xfeatures, kwArgs, protHack); /* Verify and transform the parse tree. */ transform(&spec); /* Generate code. */ generateCode(&spec, codeDir, buildFile, docFile, srcSuffix, exceptions, tracing, releaseGIL, parts, versions, xfeatures, consModule, docs, FALSE); /* Generate any extracts. */ generateExtracts(&spec, extracts); /* Generate the API file. */ if (apiFile != NULL) generateAPI(&spec, spec.module, apiFile); /* Generate the XML export. */ if (xmlFile != NULL) generateXML(&spec, spec.module, xmlFile); /* Generate the .pyi file. */ if (pyiFile != NULL) generateTypeHints(&spec, spec.module, pyiFile); /* All done. */ return 0; }
int main(int argc, char *argv[]) { uint8_t buf[SECRET_BITS/8 + SCRATCHCODES*BYTES_PER_SCRATCHCODE]; static const char hotp[] = "\" HOTP_COUNTER 1\n"; static const char totp[] = "\" TOTP_AUTH\n"; static const char disallow[] = "\" DISALLOW_REUSE\n"; static const char window[] = "\" WINDOW_SIZE 17\n"; static const char ratelimit[] = "\" RATE_LIMIT 3 30\n"; char secret[(SECRET_BITS + BITS_PER_BASE32_CHAR-1)/BITS_PER_BASE32_CHAR + 1 /* newline */ + sizeof(hotp) + // hotp and totp are mutually exclusive. sizeof(disallow) + sizeof(window) + sizeof(ratelimit) + 5 + // NN MMM (total of five digits) SCRATCHCODE_LENGTH*(SCRATCHCODES + 1 /* newline */) + 1 /* NUL termination character */]; enum { ASK_MODE, HOTP_MODE, TOTP_MODE } mode = ASK_MODE; enum { ASK_REUSE, DISALLOW_REUSE, ALLOW_REUSE } reuse = ASK_REUSE; int force = 0, quiet = 0; int r_limit = 0, r_time = 0; char *secret_fn = NULL; char *label = NULL; int window_size = 0; int idx; for (;;) { static const char optstring[] = "+hctdDfl:qQ:r:R:us:w:W"; static struct option options[] = { { "help", 0, 0, 'h' }, { "counter-based", 0, 0, 'c' }, { "time-based", 0, 0, 't' }, { "disallow-reuse", 0, 0, 'd' }, { "allow-reuse", 0, 0, 'D' }, { "force", 0, 0, 'f' }, { "label", 1, 0, 'l' }, { "quiet", 0, 0, 'q' }, { "qr-mode", 1, 0, 'Q' }, { "rate-limit", 1, 0, 'r' }, { "rate-time", 1, 0, 'R' }, { "no-rate-limit", 0, 0, 'u' }, { "secret", 1, 0, 's' }, { "window-size", 1, 0, 'w' }, { "minimal-window", 0, 0, 'W' }, { 0, 0, 0, 0 } }; idx = -1; int c = getopt_long(argc, argv, optstring, options, &idx); if (c > 0) { for (int i = 0; options[i].name; i++) { if (options[i].val == c) { idx = i; break; } } } else if (c < 0) { break; } if (idx-- <= 0) { // Help (or invalid argument) err: usage(); if (idx < -1) { fprintf(stderr, "Failed to parse command line\n"); _exit(1); } exit(0); } else if (!idx--) { // counter-based if (mode != ASK_MODE) { fprintf(stderr, "Duplicate -c and/or -t option detected\n"); _exit(1); } if (reuse != ASK_REUSE) { reuse_err: fprintf(stderr, "Reuse of tokens is not a meaningful parameter " "when in counter-based mode\n"); _exit(1); } mode = HOTP_MODE; } else if (!idx--) { // time-based if (mode != ASK_MODE) { fprintf(stderr, "Duplicate -c and/or -t option detected\n"); _exit(1); } mode = TOTP_MODE; } else if (!idx--) { // disallow-reuse if (reuse != ASK_REUSE) { fprintf(stderr, "Duplicate -d and/or -D option detected\n"); _exit(1); } if (mode == HOTP_MODE) { goto reuse_err; } reuse = DISALLOW_REUSE; } else if (!idx--) { // allow-reuse if (reuse != ASK_REUSE) { fprintf(stderr, "Duplicate -d and/or -D option detected\n"); _exit(1); } if (mode == HOTP_MODE) { goto reuse_err; } reuse = ALLOW_REUSE; } else if (!idx--) { // force if (force) { fprintf(stderr, "Duplicate -f option detected\n"); _exit(1); } force = 1; } else if (!idx--) { // label if (label) { fprintf(stderr, "Duplicate -l option detected\n"); _exit(1); } label = strdup(optarg); } else if (!idx--) { // quiet if (quiet) { fprintf(stderr, "Duplicate -q option detected\n"); _exit(1); } quiet = 1; } else if (!idx--) { // qr-mode if (qr_mode != QR_UNSET) { fprintf(stderr, "Duplicate -Q option detected\n"); _exit(1); } if (!strcasecmp(optarg, "none")) { qr_mode = QR_NONE; } else if (!strcasecmp(optarg, "ansi")) { qr_mode = QR_ANSI; } else if (!strcasecmp(optarg, "utf8")) { qr_mode = QR_UTF8; } else { fprintf(stderr, "Invalid qr-mode \"%s\"\n", optarg); _exit(1); } } else if (!idx--) { // rate-limit if (r_limit > 0) { fprintf(stderr, "Duplicate -r option detected\n"); _exit(1); } else if (r_limit < 0) { fprintf(stderr, "-u is mutually exclusive with -r\n"); _exit(1); } char *endptr; errno = 0; long l = strtol(optarg, &endptr, 10); if (errno || endptr == optarg || *endptr || l < 1 || l > 10) { fprintf(stderr, "-r requires an argument in the range 1..10\n"); _exit(1); } r_limit = (int)l; } else if (!idx--) { // rate-time if (r_time > 0) { fprintf(stderr, "Duplicate -R option detected\n"); _exit(1); } else if (r_time < 0) { fprintf(stderr, "-u is mutually exclusive with -R\n"); _exit(1); } char *endptr; errno = 0; long l = strtol(optarg, &endptr, 10); if (errno || endptr == optarg || *endptr || l < 15 || l > 600) { fprintf(stderr, "-R requires an argument in the range 15..600\n"); _exit(1); } r_time = (int)l; } else if (!idx--) { // no-rate-limit if (r_limit > 0 || r_time > 0) { fprintf(stderr, "-u is mutually exclusive with -r/-R\n"); _exit(1); } if (r_limit < 0) { fprintf(stderr, "Duplicate -u option detected\n"); _exit(1); } r_limit = r_time = -1; } else if (!idx--) { // secret if (secret_fn) { fprintf(stderr, "Duplicate -s option detected\n"); _exit(1); } if (!*optarg) { fprintf(stderr, "-s must be followed by a filename\n"); _exit(1); } secret_fn = strdup(optarg); if (!secret_fn) { perror("malloc()"); _exit(1); } } else if (!idx--) { // window-size if (window_size) { fprintf(stderr, "Duplicate -w/-W option detected\n"); _exit(1); } char *endptr; errno = 0; long l = strtol(optarg, &endptr, 10); if (errno || endptr == optarg || *endptr || l < 1 || l > 21) { fprintf(stderr, "-w requires an argument in the range 1..21\n"); _exit(1); } window_size = (int)l; } else if (!idx--) { // minimal-window if (window_size) { fprintf(stderr, "Duplicate -w/-W option detected\n"); _exit(1); } window_size = -1; } else { fprintf(stderr, "Error\n"); _exit(1); } } idx = -1; if (optind != argc) { goto err; } if (reuse != ASK_REUSE && mode != TOTP_MODE) { fprintf(stderr, "Must select time-based mode, when using -d or -D\n"); _exit(1); } if ((r_time && !r_limit) || (!r_time && r_limit)) { fprintf(stderr, "Must set -r when setting -R, and vice versa\n"); _exit(1); } if (!label) { uid_t uid = getuid(); const char *user = getUserName(uid); char hostname[128] = { 0 }; if (gethostname(hostname, sizeof(hostname)-1)) { strcpy(hostname, "unix"); } label = strcat(strcat(strcpy(malloc(strlen(user) + strlen(hostname) + 2), user), "@"), hostname); free((char *)user); } int fd = open("/dev/urandom", O_RDONLY); if (fd < 0) { perror("Failed to open \"/dev/urandom\""); return 1; } if (read(fd, buf, sizeof(buf)) != sizeof(buf)) { urandom_failure: perror("Failed to read from \"/dev/urandom\""); return 1; } base32_encode(buf, SECRET_BITS/8, (uint8_t *)secret, sizeof(secret)); int use_totp; if (mode == ASK_MODE) { use_totp = maybe("Do you want authentication tokens to be time-based"); } else { use_totp = mode == TOTP_MODE; } if (!quiet) { displayQRCode(secret, label, use_totp); printf("Your new secret key is: %s\n", secret); printf("Your verification code is %06d\n", generateCode(secret, 0)); printf("Your emergency scratch codes are:\n"); } free(label); strcat(secret, "\n"); if (use_totp) { strcat(secret, totp); } else { strcat(secret, hotp); } for (int i = 0; i < SCRATCHCODES; ++i) { new_scratch_code:; int scratch = 0; for (int j = 0; j < BYTES_PER_SCRATCHCODE; ++j) { scratch = 256*scratch + buf[SECRET_BITS/8 + BYTES_PER_SCRATCHCODE*i + j]; } int modulus = 1; for (int j = 0; j < SCRATCHCODE_LENGTH; j++) { modulus *= 10; } scratch = (scratch & 0x7FFFFFFF) % modulus; if (scratch < modulus/10) { // Make sure that scratch codes are always exactly eight digits. If they // start with a sequence of zeros, just generate a new scratch code. if (read(fd, buf + (SECRET_BITS/8 + BYTES_PER_SCRATCHCODE*i), BYTES_PER_SCRATCHCODE) != BYTES_PER_SCRATCHCODE) { goto urandom_failure; } goto new_scratch_code; } if (!quiet) { printf(" %08d\n", scratch); } snprintf(strrchr(secret, '\000'), sizeof(secret) - strlen(secret), "%08d\n", scratch); } close(fd); if (!secret_fn) { char *home = getenv("HOME"); if (!home || *home != '/') { fprintf(stderr, "Cannot determine home directory\n"); return 1; } secret_fn = malloc(strlen(home) + strlen(SECRET) + 1); if (!secret_fn) { perror("malloc()"); _exit(1); } strcat(strcpy(secret_fn, home), SECRET); } if (!force) { printf("\nDo you want me to update your \"%s\" file (y/n) ", secret_fn); fflush(stdout); char ch; do { ch = getchar(); } while (ch == ' ' || ch == '\r' || ch == '\n'); if (ch != 'y' && ch != 'Y') { exit(0); } } secret_fn = realloc(secret_fn, 2*strlen(secret_fn) + 3); if (!secret_fn) { perror("malloc()"); _exit(1); } char *tmp_fn = strrchr(secret_fn, '\000') + 1; strcat(strcpy(tmp_fn, secret_fn), "~"); // Add optional flags. if (use_totp) { if (reuse == ASK_REUSE) { maybeAddOption("Do you want to disallow multiple uses of the same " "authentication\ntoken? This restricts you to one login " "about every 30s, but it increases\nyour chances to " "notice or even prevent man-in-the-middle attacks", secret, sizeof(secret), disallow); } else if (reuse == DISALLOW_REUSE) { addOption(secret, sizeof(secret), disallow); } if (!window_size) { maybeAddOption("By default, tokens are good for 30 seconds and in order " "to compensate for\npossible time-skew between the " "client and the server, we allow an extra\ntoken before " "and after the current time. If you experience problems " "with poor\ntime synchronization, you can increase the " "window from its default\nsize of 1:30min to about 4min. " "Do you want to do so", secret, sizeof(secret), window); } else { char buf[80]; sprintf(buf, "\" WINDOW_SIZE %d\n", window_size); addOption(secret, sizeof(secret), buf); } } else { if (!window_size) { maybeAddOption("By default, three tokens are valid at any one time. " "This accounts for\ngenerated-but-not-used tokens and " "failed login attempts. In order to\ndecrease the " "likelihood of synchronization problems, this window " "can be\nincreased from its default size of 3 to 17. Do " "you want to do so", secret, sizeof(secret), window); } else { char buf[80]; sprintf(buf, "\" WINDOW_SIZE %d\n", window_size > 0 ? window_size : use_totp ? 3 : 1); addOption(secret, sizeof(secret), buf); } } if (!r_limit && !r_time) { maybeAddOption("If the computer that you are logging into isn't hardened " "against brute-force\nlogin attempts, you can enable " "rate-limiting for the authentication module.\nBy default, " "this limits attackers to no more than 3 login attempts " "every 30s.\nDo you want to enable rate-limiting", secret, sizeof(secret), ratelimit); } else if (r_limit > 0 && r_time > 0) { char buf[80]; sprintf(buf, "\"RATE_LIMIT %d %d\n", r_limit, r_time); addOption(secret, sizeof(secret), buf); } fd = open(tmp_fn, O_WRONLY|O_EXCL|O_CREAT|O_NOFOLLOW|O_TRUNC, 0400); if (fd < 0) { fprintf(stderr, "Failed to create \"%s\" (%s)", secret_fn, strerror(errno)); free(secret_fn); return 1; } if (write(fd, secret, strlen(secret)) != (ssize_t)strlen(secret) || rename(tmp_fn, secret_fn)) { perror("Failed to write new secret"); unlink(secret_fn); close(fd); free(secret_fn); return 1; } free(secret_fn); close(fd); return 0; }