void TextTestResult::print (std::ostream &stream)
{
	printHeader (stream);
	printErrors (stream);
	printFailures (stream);

}
Ejemplo n.º 2
0
FSBANK_RESULT buildBank(const char **fileNames, unsigned int numFileNames, const char *outputFileName)
{
    FSBANK_RESULT    result    = FSBANK_OK;
    FSBANK_SUBSOUND *subSounds = (FSBANK_SUBSOUND *)alloca(numFileNames * sizeof(FSBANK_SUBSOUND));

    for (unsigned int i = 0; i < numFileNames; i++)
    {
        memset(&subSounds[i], 0, sizeof(FSBANK_SUBSOUND));

        subSounds[i].fileNames          = &fileNames[i];
        subSounds[i].numFileNames       = 1;
        subSounds[i].speakerMap         = FSBANK_SPEAKERMAP_DEFAULT;        
        subSounds[i].overrideFlags      = FSBANK_BUILD_DEFAULT;
        subSounds[i].overrideQuality    = 0;
        subSounds[i].desiredSampleRate  = 0;
    }

    printf("Building %s...\n", outputFileName);

    result = FSBank_Build(subSounds, numFileNames, FSBANK_FORMAT_MP3, FSBANK_BUILD_DEFAULT | FSBANK_BUILD_DONTLOOP, 0, NULL, outputFileName);
    if (result != FSBANK_OK)
    {
        printErrors(subSounds);
        return result;
    }

    printf("done.\n");
    return FSBANK_OK;
}
Ejemplo n.º 3
0
void Simulator::startSimulation()
{
	// number of threads shall not exceed number of houses
	if (numOfThreads > numOfHouses)
		numOfThreads = numOfHouses;

	// for each algorithm -> initialize array of scores for each house
	for (string algorithmName : registrar.getAlgorithmNames())
		scores[algorithmName] = make_unique<int[]>(numOfHouses);
	
	if (numOfThreads > 1)
	{
		// create threads and start them
		vector<unique_ptr<thread>> threads(numOfThreads);
		for (auto& thread_ptr : threads)
			thread_ptr = make_unique<thread>(&Simulator::threadSimulation, this);

		// join all threads
		for (auto& thread_ptr : threads)
			thread_ptr->join();
	}
	else // numOfThreads = 1
	{
		threadSimulation();
	}
	
	// print results
	printScores();
	printErrors();
}
Ejemplo n.º 4
0
int analyzeError (const Specification &lSpec, const TestDiagnosticHandler& errHandler) 
{
  if (isErrorExpected(errHandler, &lSpec)) {
    printErrors(errHandler, "The following execution error occurred as expected", false);
    return EXPECTED_ERROR;
  } else {
    printErrors(errHandler, "Unexpected error executing query", false);
    std::cout << "Expected error(s):";
    for (std::vector<std::string>::const_iterator lIter = lSpec.errorsBegin();
         lIter != lSpec.errorsEnd(); ++lIter)
      {
        std::cout << " " << *lIter;
      }
    if (lSpec.errorsSize () == 0) { std::cout << " (none)"; }
    std::cout << std::endl;
    return UNEXPECTED_ERROR;
  }
}
Ejemplo n.º 5
0
char*	strJoin(char* a, char* b){
	char* c = (char*)malloc(strlen(a)+strlen(b)+1);
	if(c == NULL){
		printErrors("malloc failed");
	}
	strcat(c, a);
	strcat(c, b);

	return c;
}
Ejemplo n.º 6
0
void main( int argc, char *argv[] )
{

	calibrateClock();
	filterBank[actualFilter] = defaultIirFilterInfo();

	for( i=1; i<argc; i++ ) {
		parseInput(argv[i], INPUT_BUF_SIZE);
		if( getErrors() ) {
			printErrors();
			clearErrors();
		}
	}

	while(1) {
		scanf("%s", inputBuffer);
		parseInput(inputBuffer, INPUT_BUF_SIZE);
		if( getErrors() ) {
			printErrors();
			clearErrors();
		}
	}

}
Ejemplo n.º 7
0
QQmlComponent* TestSimpleQmlLoad::compileAndLoad(QQmlEngine *engine, const QString &file, const QList<QString> &dependencies)
{
    QString url("qrc" + file);
    QmlC c(engine);
    QByteArray outputBuf;
    QDataStream output(&outputBuf, QIODevice::WriteOnly);
    bool success = c.compile(url, output);
    if (!success || outputBuf.length() < 500) {
        printErrors(c.errors());
        return NULL;
    }

    QList<QByteArray*> outputBufs;
    foreach (const QString & dependency, dependencies) {
        QByteArray *buf = new QByteArray;
        QDataStream out(buf, QIODevice::WriteOnly);
        bool ret = false;
        QString u("qrc" + dependency);
        QQmlEngine *e = new QQmlEngine;
        if (dependency.endsWith(".js")) {
            ScriptC jsc(e);
            ret = jsc.compile(u, out);
            if (!ret)
                printErrors(jsc.errors());
        } else {
            QmlC qmlc(e);
            ret = qmlc.compile(u, out);
            if (!ret)
                printErrors(qmlc.errors());
        }
        delete e;
        if (!ret || buf->length() < 500) {
            return NULL;
        }
        outputBufs.append(buf);
    }
Ejemplo n.º 8
0
QQmlComponent* TestSimpleQmlLoad::load(QQmlEngine *engine, const QString &file)
{
    QQmlEnginePrivate::get(engine)->v4engine()->iselFactory.reset(new QV4::JIT::ISelFactory);
    QUrl url("qrc" + file);
    QQmlComponent* component = new QQmlComponent(engine, url, QQmlComponent::PreferSynchronous);

    if (!component)
        return NULL;

    if (component->isError() || !component->isReady()) {
        printErrors(component->errors());
        delete component;
        return NULL;
    }

    return component;
}
Ejemplo n.º 9
0
/*! Main function run from the command line
    @param argc     argument count (the number of arguments given)
    @param argv     argument values (the array of arguments given)
    @return         the return code of the program (EXIT_SUCCESS for a successful output, another code for an error)
*/
int main (int argc, char* argv[]) {
    if (argc >= 2) {
        initializeGlobals();
        expression* parsed = parse(argv[1]);
        expression* evaluated;
        if (errors == NULL) {
            evaluated = evaluate(parsed);
        } else {
            evaluated = newExpressionOfType(TYPE_NIL);
        }
        char* printed = printExpression(evaluated);
        char* errortext = printErrors();
        printf("%s\n%s", printed, errortext);
        free(printed);
        freeExpr(evaluated);
        freeGlobals();
        return EXIT_SUCCESS;
    } else {
        return EXIT_NO_ARGS;
    }
}
PanelFirmware::PanelFirmware(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PanelFirmware)
{
    ui->setupUi(this);
    scroll = false;
    upload = new QProcess(this);
    connect(this, SIGNAL(initializePanel(QMap<QString,QString>)), this, SLOT(initialize(QMap<QString,QString>)));
    connect(this, SIGNAL(messageIn(QByteArray)), this, SLOT(parseMessage(QByteArray)));
    connect(this, SIGNAL(connectionState(bool)), this, SLOT(updateConnectionState(bool)));
    connect(upload, SIGNAL(readyReadStandardOutput()), this, SLOT(printConsole()));
    connect(upload, SIGNAL(readyReadStandardError()), this, SLOT(printErrors()));
    connect(ui->webView->page(), SIGNAL(loadStarted()), this, SLOT(startFirmwareUpload()));
    connect(ui->webView->page(), SIGNAL(loadProgress(int)), this, SLOT(scrollToBottom(int)));
    connect(ui->webView->page(), SIGNAL(loadFinished(bool)), this, SLOT(downloadFirmware(bool)));
    connect(&networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(firmwareDownloaded(QNetworkReply*)));

    QFont consoleFont = ui->console->font();
    consoleFont.setPointSize(12);
    ui->console->setFont(consoleFont);
    ui->console->append("To return the board it's default factory configuration, select the Bootloader button.  To upload existing firmware, select the Firmware button.\n\nTo create and upload new firmware, complete the selections below.  You will need to be connected to the internet for this feature.");
}
Ejemplo n.º 11
0
void main(void)
{
	calibrateClock();
	initializeDevice();

	while(1) {
		if( pendingCommand ) {
		
			if( pendingCommand == LONG_COMMAND ) {
				// error
			} else {
				parseInput(inputBuffer, INPUT_BUF_SIZE);
			}
			
			if( getErrors() ) {
				printErrors();
				clearErrors();
			}
			
		}
	}
}
Ejemplo n.º 12
0
void plotCovMatrix(TString file, TString label1, TString label2) {
    ModTDRStyle();
    gStyle->SetPaintTextFormat(".3g");

    TFile f(file);

    TH2D *h_cov1 = (TH2D*)gDirectory->Get(label1+"_h_cov");
    TH2D *h_cov2 = (TH2D*)gDirectory->Get(label2+"_h_cov");
    TH2D *h_cor1 = (TH2D*)gDirectory->Get(label1+"_h_cor");
    TH2D *h_cor2 = (TH2D*)gDirectory->Get(label2+"_h_cor");

    // TH2D *h_cov3 = (TH2D*)h_cov1->Clone("syst_h_cov");
    // h_cov3->Add(h_cov2, -1);

    // TH2D *h_cor3 = (TH2D*)h_cov3->Clone("syst_h_cor");

    // for (int i = 1; i <= h_cov3->GetNbinsX(); ++i) {
    //   for (int j = 1; j <= h_cov3->GetNbinsY(); ++j) {
    //     int n = h_cov3->GetNbinsX();
    //     int bx = TranslateToX(i, j, n);
    //     int by = TranslateToY(i, j, n);
    //     h_cor3->SetBinContent(bx, by, h_cov3->GetBinContent(bx, by) / (
    //        TMath::Sqrt(h_cov3->GetBinContent(TranslateToX(i, i, n), TranslateToY(i, i, n)))
    //      * TMath::Sqrt(h_cov3->GetBinContent(TranslateToX(j, j, n), TranslateToY(j, j, n)))));
    //   }
    // }


    drawMatrix(h_cov1, label1+"_cov");
    drawMatrix(h_cov2, label2+"_cov");
    drawMatrix(h_cor1, label1+"_cor");
    drawMatrix(h_cor2, label2+"_cor");
    // drawMatrix(h_cov3, "syst_cov");
    // drawMatrix(h_cor3, "syst_cor");

    printErrors(h_cov1, h_cov2);
}
Ejemplo n.º 13
0
/////////////////////////////////////////////////////////
// main testing function 
/////////////////////////////////////////////////////////
int main(int argc, const char * const argv[])
{
  (void)argc;
  (void)argv;

  int coreid;
  int it;

  boolean_T pass;
  boolean_T flag;
  float y[10];
  int ix;
  float b_y;
  int b_k;
  float xbar;
  float r;
  float c_y;
  float check[2];
  float golden[4];



  /////////////////////////////////////////////////////////
  // main test loop 
  // each core loops over a kernel instance
  /////////////////////////////////////////////////////////
  coreid = get_core_id();

  printf("starting %d kernel iterations... (coreid = %d)\n",KERNEL_ITS,coreid);

  if (coreid>3)
    coreid=coreid-4;

  synch_barrier();

  perf_begin();

  for(it = 0; it < getKernelIts(); it++)
  {
    // matlab kernel
    for (ix = 0; ix < 10; ix++) {
      b_y = 0.0F;
      for (b_k = 0; b_k < 10; b_k++) {
        b_y += fv1[(ix + 10 * b_k) + 100 * coreid] * fv0[b_k + 10 * coreid];
      }
      y[ix] = b_y + fv3[coreid] * fv2[ix + 10 * coreid];
    }
  }

  synch_barrier();

  perf_end();

  synch_barrier();

  /////////////////////////////////////////////////////////
  // check results
  /////////////////////////////////////////////////////////

  b_y = y[0];
  ix = 0;
  xbar = y[0];
  for (b_k = 0; b_k < 9; b_k++) {
    b_y += y[b_k + 1];
    ix++;
    xbar += y[ix];
  }

  xbar *= 1.0F/10.0F;
  ix = 0;
  r = y[0] - xbar;
  c_y = r * r;
  for (b_k = 0; b_k < 9; b_k++) {
    ix++;
    r = y[ix] - xbar;
    c_y += r * r;
  }

  c_y *= 1.0F/9.0F;
  check[0] = b_y;
  check[1] = c_y;
  pass = true;
  for (ix = 0; ix < 2; ix++) {
    for (b_k = 0; b_k < 2; b_k++) {
      golden[b_k + (ix << 1)] = fv4[(b_k + (ix << 1)) + (coreid << 2)];
    }
    flag = true;
    flag = pass && (check[ix] <= golden[ix << 1]);
    flag = pass && (check[ix] >= golden[1 + (ix << 1)]);
    printErrors(!flag, ix, check[ix], golden[ix<<1], golden[1+(ix<<1)]);
    pass = pass && flag;
  }
  flagPassFail(pass, get_core_id());


/////////////////////////////////////////////////////////
// synchronize and exit
/////////////////////////////////////////////////////////

  return !pass;
}
Ejemplo n.º 14
0
/////////////////////////////////////////////////////////
// main testing function 
/////////////////////////////////////////////////////////
int main(int argc, const char * const argv[])
{
  (void)argc;
  (void)argv;

  int coreid;
  int it;

  int k;
  boolean_T pass, flag;
  float y[100];
  int ix;
  float b_y;
  float xbar;
  float r;
  float c_y;
  float tmp[2];
  float golden[4];


  /////////////////////////////////////////////////////////
  // main test loop 
  // each core loops over a kernel instance
  /////////////////////////////////////////////////////////

  coreid = get_core_id();

  printf("starting %d kernel iterations... (coreid = %d)\n",KERNEL_ITS,coreid);

  if (coreid>3)
    coreid=coreid-4;

  synch_barrier();

  perf_begin();

  for(it = 0; it < KERNEL_ITS; it++)
  {
    // matlab kernel
    for (ix = 0; ix < 100; ix++) {
      y[ix] = (real32_T)fLog(fv0[ix + 100 * coreid]);
    }
  }

  synch_barrier();

  perf_end();

  synch_barrier();

  /////////////////////////////////////////////////////////
  // check results
  /////////////////////////////////////////////////////////

  pass = true;
  b_y = y[0];
  ix = 0;
  xbar = y[0];
  for (k = 0; k < 99; k++) {
    b_y += y[k + 1];
    ix++;
    xbar += y[ix];
  }

  xbar *= 1.0F/100.0F;
  ix = 0;
  r = y[0] - xbar;
  c_y = r * r;
  for (k = 0; k < 99; k++) {
    ix++;
    r = y[ix] - xbar;
    c_y += r * r;
  }

  c_y *= 1.0F/99.0F;
  tmp[0] = b_y;
  tmp[1] = c_y;
  pass  = true;

  for (ix = 0; ix < 2; ix++) {
    for (k = 0; k < 2; k++) {
      golden[k + (ix << 1)] = fv1[(k + (ix << 1)) + (coreid << 2)];
    }
    flag = true;
    flag = flag && (tmp[ix] <= golden[ix << 1]);
    flag = flag && (tmp[ix] >= golden[1 + (ix << 1)]);
    printErrors(!flag, ix, tmp[ix] ,golden[(ix << 1)] ,golden[1 + (ix << 1)]);
    pass = pass && flag;
  }

  flagPassFail(pass, get_core_id());
  
  synch_barrier();

/////////////////////////////////////////////////////////
// synchronize and exit
/////////////////////////////////////////////////////////

  return !pass;
}
Ejemplo n.º 15
0
/////////////////////////////////////////////////////////
// main testing function 
/////////////////////////////////////////////////////////
int main(int argc, const char * const argv[])
{
  (void)argc;
  (void)argv;

  boolean_T pass, flag;
  int coreid;
  
  float omega, ampl, runningPhase;
  float sig[200];
  int k;
  int i;
  float y;
  int ix;
  float xbar;
  float r;
  float b_y;
  float tmp[2];

  float golden[4];
  boolean_T c_y;
  boolean_T exitg1;
  
  /////////////////////////////////////////////////////////
  // main test loop 
  // each core loops over a kernel instance
  /////////////////////////////////////////////////////////
  
  coreid = get_core_id();

  printf("starting %d kernel iterations... (coreid = %d)\n",KERNEL_ITS,coreid);
  
  if (coreid>3)
    coreid=coreid-4;

  synch_barrier();
  
  perf_begin();

  omega =  fv1[coreid];
  ampl  =  fv2[coreid];
  
  for(k = 0; k < getKernelIts(); k++)
  {
    runningPhase = omega;
  
    // matlab kernel
    for (i = 0; i < 200; i++) {
      sig[i] = ampl * fSin(runningPhase);
      runningPhase += omega;

      if(runningPhase > pi2[0])
      {
	runningPhase -= pi2[0];
      }    
    }
  }

  synch_barrier();

  perf_end();

  /////////////////////////////////////////////////////////
  // check results
  /////////////////////////////////////////////////////////

  synch_barrier();


  y = sig[0];
  ix = 0;
  xbar = sig[0];
  for (k = 0; k < 199; k++) {
    y += sig[k + 1];
    ix++;
    xbar += sig[ix];
  }

  xbar = fDiv(xbar,200.0F);
  ix = 0;
  r = sig[0] - xbar;
  b_y = r * r;
  for (k = 0; k < 199; k++) {
    ix++;
    r = sig[ix] - xbar;
    b_y += r * r;
  }

  b_y = fDiv(b_y,199.0F);
  tmp[0] = y;
  tmp[1] = b_y;

  pass = true;
  for (k = 0; k < 2; k++) {
    for (ix = 0; ix < 2; ix++) {
      golden[ix + (k << 1)] = fv0[(ix + (k << 1)) + (coreid << 2)];
    }
    flag = true;
    flag = flag && (tmp[k] <= golden[k << 1]);
    flag = flag && (tmp[k] >= golden[1 + (k << 1)]);
    printErrors(!flag, k, tmp[k] ,golden[k << 1], golden[1 + (k << 1)]);
    pass = pass && flag;
  }

  flagPassFail(pass, get_core_id());

/////////////////////////////////////////////////////////
// synchronize and exit
/////////////////////////////////////////////////////////

  return !pass;
}
Ejemplo n.º 16
0
/*! \fn solve system with Newton-Raphson
 *
 *  \param [in]  [n] size of equation
 *                [eps] tolerance for x
 *                [h] tolerance for f'
 *                [k] maximum number of iterations
 *                [work] work array size of (n*X)
 *                [f] user provided function
 *                [data] userdata
 *                [info]
 *				  [calculate_jacobian] flag which decides whether Jacobian is calculated
 *					(0)  once for the first calculation
 * 					(i)  every i steps (=1 means original newton method)
 * 					(-1) never, factorization has to be given in A
 *
 */
int _omc_newton(int(*f)(int*, double*, double*, void*, int), DATA_NEWTON* solverData, void* userdata)
{

  int i, j, k = 0, l = 0, nrsh = 1;
  int *n = &(solverData->n);
  double *x = solverData->x;
  double *fvec = solverData->fvec;
  double *eps = &(solverData->ftol);
  double *fdeps = &(solverData->epsfcn);
  int * maxfev = &(solverData->maxfev);
  double *fjac = solverData->fjac;
  double *work = solverData->rwork;
  int *iwork = solverData->iwork;
  int *info = &(solverData->info);
  int calc_jac = 1;

  double error_f  = 1.0 + *eps, scaledError_f = 1.0 + *eps, delta_x = 1.0 + *eps, delta_f = 1.0 + *eps, delta_x_scaled = 1.0 + *eps, lambda = 1.0;
  double current_fvec_enorm, enorm_new;


  if(ACTIVE_STREAM(LOG_NLS_V))
  {
    infoStreamPrint(LOG_NLS_V, 1, "######### Start Newton maxfev: %d #########", (int)*maxfev);

    infoStreamPrint(LOG_NLS_V, 1, "x vector");
    for(i=0; i<*n; i++)
      infoStreamPrint(LOG_NLS_V, 0, "x[%d]: %e ", i, x[i]);
    messageClose(LOG_NLS_V);

    messageClose(LOG_NLS_V);
  }

  *info = 1;

  /* calculate the function values */
  (*f)(n, x, fvec, userdata, 1);

  solverData->nfev++;

  /* save current fvec in f_old*/
  memcpy(solverData->f_old, fvec, *n*sizeof(double));

  error_f = current_fvec_enorm = enorm_(n, fvec);

  while(error_f > *eps && scaledError_f > *eps  &&  delta_x > *eps  &&  delta_f > *eps  && delta_x_scaled > *eps)
  {
    if(ACTIVE_STREAM(LOG_NLS_V))
    {
      infoStreamPrint(LOG_NLS_V, 0, "\n**** start Iteration: %d  *****", (int) l);

      /*  Debug output */
      infoStreamPrint(LOG_NLS_V, 1, "function values");
      for(i=0; i<*n; i++)
        infoStreamPrint(LOG_NLS_V, 0, "fvec[%d]: %e ", i, fvec[i]);
      messageClose(LOG_NLS_V);
    }

    /* calculate jacobian if no matrix is given */
    if (calc_jac == 1 && solverData->calculate_jacobian >= 0)
    {
      (*f)(n, x, fvec, userdata, 0);
      solverData->factorization = 0;
      calc_jac = solverData->calculate_jacobian;
    }
    else
    {
      solverData->factorization = 1;
      calc_jac--;
    }


    /* debug output */
    if(ACTIVE_STREAM(LOG_NLS_JAC))
    {
      char buffer[4096];

      infoStreamPrint(LOG_NLS_JAC, 1, "jacobian matrix [%dx%d]", (int)*n, (int)*n);
      for(i=0; i<solverData->n;i++)
      {
        buffer[0] = 0;
        for(j=0; j<solverData->n; j++)
          sprintf(buffer, "%s%10g ", buffer, fjac[i*(*n)+j]);
        infoStreamPrint(LOG_NLS_JAC, 0, "%s", buffer);
      }
      messageClose(LOG_NLS_JAC);
    }

    if (solveLinearSystem(n, iwork, fvec, fjac, solverData) != 0)
    {
      *info=-1;
      break;
    }
    else
    {
      for (i =0; i<*n; i++)
        solverData->x_new[i]=x[i]-solverData->x_increment[i];

      infoStreamPrint(LOG_NLS_V,1,"x_increment");
      for(i=0; i<*n; i++)
        infoStreamPrint(LOG_NLS_V, 0, "x_increment[%d] = %e ", i, solverData->x_increment[i]);
      messageClose(LOG_NLS_V);

      if (solverData->newtonStrategy == NEWTON_DAMPED)
      {
        damping_heuristic(x, f, current_fvec_enorm, n, fvec, &lambda, &k, solverData, userdata);
      }
      else if (solverData->newtonStrategy == NEWTON_DAMPED2)
      {
        damping_heuristic2(0.75, x, f, current_fvec_enorm, n, fvec, &k, solverData, userdata);
      }
      else if (solverData->newtonStrategy == NEWTON_DAMPED_LS)
      {
        LineSearch(x, f, current_fvec_enorm, n, fvec, &k, solverData, userdata);
      }
      else if (solverData->newtonStrategy == NEWTON_DAMPED_BT)
      {
        Backtracking(x, f, current_fvec_enorm, n, fvec, solverData, userdata);
      }
      else
      {
        /* calculate the function values */
        (*f)(n, solverData->x_new, fvec, userdata, 1);
        solverData->nfev++;
      }

      calculatingErrors(solverData, &delta_x, &delta_x_scaled, &delta_f, &error_f, &scaledError_f, n, x, fvec);

      /* updating x */
      memcpy(x, solverData->x_new, *n*sizeof(double));

      /* updating f_old */
      memcpy(solverData->f_old, fvec, *n*sizeof(double));

      current_fvec_enorm = error_f;

      /* check if maximum iteration is reached */
      if (++l > *maxfev)
      {
        *info = -1;
        warningStreamPrint(LOG_NLS_V, 0, "Warning: maximal number of iteration reached but no root found");
        break;
      }
    }

    if(ACTIVE_STREAM(LOG_NLS_V))
    {
      infoStreamPrint(LOG_NLS_V,1,"x vector");
      for(i=0; i<*n; i++)
        infoStreamPrint(LOG_NLS_V, 0, "x[%d] = %e ", i, x[i]);
      messageClose(LOG_NLS_V);
      printErrors(delta_x, delta_x_scaled, delta_f, error_f, scaledError_f, eps);
    }
  }

  solverData->numberOfIterations  += l;
  solverData->numberOfFunctionEvaluations += solverData->nfev;

  return 0;
}
Ejemplo n.º 17
0
GLProgram *GLCompiler::make( )
{
    bool errors= false;
    bool shaders= false;
    for(unsigned int i= 0; i < GLProgram::SHADERTYPE_LAST; i++)
    {
        if(sources[i].source.empty()) continue;
        
        // construit le source
        shaders= true;
        sources[i].build= build_source(i);
        
        // cree le program
        if(program == GLProgram::null())
            program= (new GLProgram(program_label))->create();
        
        // cree le shader
        GLuint shader= program->shaders[i];
        if(shader == 0)
        {
            shader= glCreateShader(GLProgram::types[i]);
            glAttachShader(program->name, shader);
            program->shaders[i]= shader;
        }
        
        // compile le shader
        const char *text[]= { sources[i].build.c_str() };
        glShaderSource(shader, 1, text, NULL);
        glCompileShader(shader);
        
        GLint status= 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
        if(status == GL_FALSE)
        {
            errors= true;
            GLint length= 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
            if(length > 0)
            {
                char *log= new char[length +1];
                glGetShaderInfoLog(shader, length, NULL, log);
                ERROR("error compiling %s shader:\n", GLProgram::labels[i]);
                printErrors(log, sources[i]);
                ERROR("shader defines:\n%s\n", sources[i].definitions.c_str());
                delete [] log;
            }
            else
                MESSAGE("error compiling %s shader: no log. failed.\n", GLProgram::labels[i]);
        }
        
        #if 0
        {
            GLint length= 0;
            glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &length);
            if(length > 0)
            {
                char log[4096];
                glGetShaderSource(shader, sizeof(log), NULL, log);
                DEBUGLOG("shader:\n%s\n", log);
            }
        }
        #endif
    }
    
    if(shaders == false || program == GLProgram::null())
    {
        ERROR("no shader. failed.\n");
        return program;
    }
    
    if(errors == true)
    {
        program->resources();
        program->errors= true;
        return program;
    }
    
    // link
    GLint status= 0;
    glLinkProgram(program->name);
    glGetProgramiv(program->name, GL_LINK_STATUS, &status);
    if(status == GL_FALSE)
    {
        GLint length= 0;
        glGetProgramiv(program->name, GL_INFO_LOG_LENGTH, &length);
        if(length > 0)
        {
            char *log= new char[length +1];
            glGetProgramInfoLog(program->name, length, NULL, log);
            MESSAGE("error linking program:\n%s\nfailed.\n", log);
            delete [] log;
        }
        else
            MESSAGE("error linking program: no log. failed.\n");
        
        program->errors= true;

        return program;
    }
    
    //~ #ifdef GK_OPENGL4
    #if 0
    {
        // interface matching
        // introspection opengl >= 4.3
        // recompile chaque shader dans un program separe et recupere les varyings avec queryinterface(program_inputs / program_outputs)...
        
        std::vector<parameter> stage_inputs[GLProgram::SHADERTYPE_LAST];
        std::vector<parameter> stage_outputs[GLProgram::SHADERTYPE_LAST];
        
        for(unsigned int i= 0; i < GLProgram::SHADERTYPE_LAST; i++)
        {
            if(program->shaders[i] == 0)
                continue;
            
            // recupere le source du shader
            GLint stage_length= 0;
            glGetShaderiv(program->shaders[i], GL_SHADER_SOURCE_LENGTH, &stage_length);
            std::vector<GLchar> stage_source(stage_length +1);
            glGetShaderSource(program->shaders[i], stage_source.size(), NULL, &stage_source.front());

            // construit un program pipeline avec uniquement ce shader
            const GLchar *sources[]= { &stage_source.front() };
            GLuint stage= glCreateShader(GLProgram::types[i]);
            glShaderSource(stage, 1, sources, NULL);
            glCompileShader(stage);
            
            GLuint pipeline= glCreateProgram();
            glProgramParameteri(pipeline, GL_PROGRAM_SEPARABLE, GL_TRUE);
            glAttachShader(pipeline, stage);
            glLinkProgram(pipeline);
            glValidateProgram(pipeline);
            
            // recupere les varyings in / out
            GLint inputs;
            glGetProgramInterfaceiv(pipeline, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &inputs);
            for(int k= 0; k < inputs; k++)
            {
                GLenum properties[3]= { GL_TYPE, GL_LOCATION, GL_LOCATION_COMPONENT };
                GLint values[3]= { 0, -1, -1 };
                glGetProgramResourceiv(pipeline, GL_PROGRAM_INPUT, k, 3, properties, 3, NULL, values);
                
                GLchar name[4096]= { 0 };
                glGetProgramResourceName(pipeline, GL_PROGRAM_INPUT, k, sizeof(name), NULL, name);
                
                stage_inputs[i].push_back( parameter(name, k, values[0], values[1], -1, values[2]) );
            }
            std::stable_sort(stage_inputs[i].begin(), stage_inputs[i].end());
            
            GLint outputs;
            glGetProgramInterfaceiv(pipeline, GL_PROGRAM_OUTPUT, GL_ACTIVE_RESOURCES, &outputs);
            for(int k= 0; k < outputs; k++)
            {
                GLenum properties[4]= { GL_TYPE, GL_LOCATION, GL_LOCATION_INDEX, GL_LOCATION_COMPONENT };
                GLint values[4]= { 0, -1, -1, -1 };
                glGetProgramResourceiv(pipeline, GL_PROGRAM_OUTPUT, k, 4, properties, 4, NULL, values);
                
                GLchar name[4096]= { 0 };
                glGetProgramResourceName(pipeline, GL_PROGRAM_OUTPUT, k, sizeof(name), NULL, name);
                
                stage_outputs[i].push_back( parameter(name, k, values[0], values[1], values[2], values[3]) );
            }
            std::stable_sort(stage_outputs[i].begin(), stage_outputs[i].end());
            
            // nettoyage
            glDeleteShader(stage);
            glDeleteProgram(pipeline);
        }
        
        // affichage : les sorties d'un shader doivent correspondre aux entrees du shader suivant dans le pipeline
        printf("program interfaces...\n");
        for(unsigned int i= 0; i < GLProgram::SHADERTYPE_LAST; i++)
        {
            if(stage_inputs[i].size())
            {
                printf("  %s shader inputs:\n", GLProgram::labels[i]);
                for(unsigned int k= 0; k < stage_inputs[i].size(); k++)
                {
                    const char *type= glsl::type_string(stage_inputs[i][k].type);
                    if(type)
                        printf("    %02d/-1: '%s', type '%s'\n", 
                            stage_inputs[i][k].location, stage_inputs[i][k].name.c_str(), type);
                    else
                        printf("    %02d/-1: '%s', type 0x%x\n", 
                            stage_inputs[i][k].location, stage_inputs[i][k].name.c_str(), stage_inputs[i][k].type);
                }
            }
            
            if(stage_outputs[i].size())
            {
                printf("  %s shader outputs:\n", GLProgram::labels[i]);
                for(unsigned int k= 0; k < stage_outputs[i].size(); k++)
                {
                    const char *type= glsl::type_string(stage_outputs[i][k].type);
                    if(type)
                        printf("    %02d/%02d: '%s', type '%s'\n", 
                            stage_outputs[i][k].location, stage_outputs[i][k].location_index, stage_outputs[i][k].name.c_str(), type);
                    else
                        printf("    %02d/%02d: '%s', type 0x%x\n", 
                            stage_outputs[i][k].location, stage_outputs[i][k].location_index, stage_outputs[i][k].name.c_str(), stage_outputs[i][k].type);
                }
            }
            
            //! \todo verification des interfaces
        }
    }
    #endif
    
    program->resources();
    program->errors= false;
    
    MESSAGE("done.\n");
    return program;
}
Ejemplo n.º 18
0
int MacroExtender::macroExtend() {
	bool canWrite = false;
	int numLine;
	int macroBound = 0;
	int macroLastStart = 0,macroLastEnd = 0;
	bool textSegment = false;
	bool dataSegment = false;
	bool isMacroBody = false;
	smatch auxMatch;
	string curLine;
	vector<string> currentCode;
	vector<string> macroParams;
	vector<string> macroLines;
	fileIn.append(".pre");
	fileOut.append(".mcr");
	ifstream inputFile(fileIn,ios::in);
		
	if (!inputFile) {
		cerr	<< "Fatal Error: Could not open file " << fileIn << endl; 
		return -1;
	}
	cout << "Opened " << fileIn << " for macro-extending..." << endl;
	ofstream outputFile(fileOut,ios::out);
	if (!outputFile) {
		cerr	<< "Fatal Error: Could not create file " << fileOut << endl; 
		return -1;
	}

	while (getline(inputFile,curLine)) {
		// prepareLine(curLine);
		if (curLine.find("SECTION ")!=string::npos && regex_search(curLine,auxMatch,regex("\\bSECTION "))) {
			if (regex_search(curLine,auxMatch,regex("\\bTEXT$"))) {
				textSegment = true;
			}
			else {
				textSegment = false;
			}
			if (regex_search(curLine,auxMatch,regex("\\bDATA$"))) {
				dataSegment = true;
			}
			else {
				dataSegment = false;
			}
		}
		else if (curLine.find(" MACRO ")!=string::npos || regex_search(curLine,auxMatch,regex(" MACRO$")) || regex_search(curLine,auxMatch,regex("\\bMACRO "))) {
			macroBound++;
			macroLastStart = numLine;
			if (textSegment || dataSegment) {
				addError(numLine,string("Semantical Error: MACRO definitions must go before all"));
			}
		}
		else if (regex_search(curLine,auxMatch,regex("\\bMACRO "))) {
			macroBound++;
			macroLastStart = numLine;
			if (textSegment || dataSegment) {
				addError(numLine,string("Semantical Error: MACRO definitions must go before all"));
			}
		}
		else if (regex_search(curLine,auxMatch,regex("\\bENDMACRO$"))) {
			macroBound--;
			macroLastEnd = numLine;
			if (textSegment || dataSegment) {
				addError(numLine,string("Semantical Error: ENDMACRO must go before all"));
			}
		}
		currentCode.push_back(curLine);
		currentCode.shrink_to_fit();
		numLine++;
	}
	//cout << "Macro Bound: " << macroBound << endl;
	if (macroBound>0) {
		addError(macroLastStart,string("Semantical Error: Caught at least one MACRO without a corresponding ENDMACRO"));
	}
	else if (macroBound<0) {
		addError(macroLastEnd,string("Semantical Error: Caught at least one ENDMACRO without a corresponding MACRO"));
	}

	vector<string>::iterator codeIterator;
	for (numLine=1,codeIterator=currentCode.begin();codeIterator!=currentCode.end();codeIterator++,numLine++) {
		curLine = *codeIterator;
		canWrite = true;
		//cout << "@" << hasMacro(curLine) << endl; 
		if (curLine.find("SECTION ")!=string::npos && regex_search(curLine,auxMatch,regex("\\bSECTION "))) {
			if (regex_search(curLine,auxMatch,regex("\\bTEXT$"))) {
				textSegment = true;
			}
			else {
				textSegment = false;
			}
			outputFile << curLine << "\n";
		}
		else if (curLine.find(" MACRO ")!=string::npos || regex_search(curLine,auxMatch,regex(" MACRO$")) || regex_search(curLine,auxMatch,regex("\\bMACRO "))) {
			macroParams.clear();
			macroLines.clear();
			if (regex_search(curLine,auxMatch,regex("\\bMACRO ")) && curLine.find("MACRO ")==0) {
				addError(numLine,string("Syntactical Error: MACRO must have a definition label"));
			}
			else if (!regex_search(curLine,auxMatch,regex(labelReg))) {
				addError(numLine,string("Syntactical Error: MACRO must have a definition label"));
			}
			else if (macroBound<=0 || (macroBound>0 && numLine!=macroLastStart)) {
				int macroDefLine = numLine;
				int numParameters; 
				string macroLabel = curLine.substr(0,curLine.find_last_of(':'));
				if (directiveTable.isDirective(macroLabel) || opcodeTable.isInstruction(macroLabel)) {
					addError(numLine,string("Semantical Error: Invalid use of keyword"));
				}
				if (macroLabel.find(':')!=string::npos) {
					addError(numLine,string("Syntactical Error: Too many definitions for MACRO constructor"));
				}
				if (curLine.find(" MACRO ") == string::npos) {
					numParameters = 0;
				}
				else {
					string auxParameters = curLine.substr(curLine.find(" MACRO ")+7);
					splitTokenize(auxParameters,macroParams,",");
					if (hasDuplicates(macroParams)) {
						addError(numLine,"Semantical Errors: Duplicate parameter detected");
					}
					for (const string &macroRef : macroParams) {
						if (!regex_match(macroRef,regex("\\&[\\w]"))) {
							addError(numLine,"Syntactical Error: Invalid parameter(s) for MACRO statement");
							break;
						}
					}
					numParameters = macroParams.size();
					if (numParameters > MACRO_MAX_PARAMS) {
						string pError = "Semantical Error: Too many parameters for MACRO definition (max at ";
						pError.append(to_string(MACRO_MAX_PARAMS));
						pError.append(" )");
						pError.shrink_to_fit();
						addError(numLine,pError);
					}
					//cout << macroParams << endl;
				}
				if (MNT.find(macroLabel) != MNT.end()) {
					addError(numLine,"Semantical Error: Macro redefinition detected");
				}
				MNT.emplace(macroLabel,make_pair(macroDefLine,numParameters));
				isMacroBody = true;
				codeIterator++;
				while (isMacroBody && codeIterator != currentCode.end()) {
					curLine = *codeIterator;
					if (curLine.find(" EXTERN") != string::npos && regex_search(curLine,auxMatch,regex(" EXTERN$"))) {
						addError(numLine,"Semantical Error: EXTERN directive inside a macro body is forbidden");
					}
					if (curLine.find(" BEGIN") != string::npos && regex_search(curLine,auxMatch,regex(" BEGIN$"))) {
						addError(numLine,"Semantical Error: BEGIN directive inside a macro body is forbidden");
					}
					if (regex_search(curLine,auxMatch,regex("^\\bEND[\\b]?$"))) {
						addError(numLine,"Semantical Error: END directive inside a macro body is forbidden");
					}
					if (curLine.find("PUBLIC ") != string::npos && regex_search(curLine,auxMatch,regex("^PUBLIC "))) {
						addError(numLine,"Semantical Error: PUBLIC directive inside a macro body is forbidden");
					}
					if (curLine.find(':') != string::npos) {
						addError(numLine,"Semantical Error: MACRO does not support labels inside");
						continue;
					}
					if (regex_search(curLine,auxMatch,regex("\\bENDMACRO$"))) {
						isMacroBody = false;
						break;
					}
					if (curLine.find("SECTION ")!=string::npos && regex_search(curLine,auxMatch,regex("^SECTION "))) {
						addError(numLine,"Semantical Error: SECTION directive inside a macro body is forbidden");
					}
					else {
						for (unsigned i=0;i<macroParams.size();i++) {
							string paramRegex = macroParams[i];
							string paramSub = string("#") + to_string(i+1);
							curLine = regex_replace(curLine,regex(paramRegex),paramSub);
						}
						if(regex_search(curLine,auxMatch,regex("\\&[\\w]"))) {
							addError(numLine,"Semantical Error: MACRO has less parameters than it uses");
						}
						macroLines.push_back(curLine);
					}
					codeIterator++;
					numLine++;
				}
				numLine++;
				MDT.emplace(macroLabel,macroLines);
			}
		}
		//else if (regex_search(curLine,auxMatch,regex("\\bENDMACRO\\b"))) {
		//	canWrite = false;
		//}
		else if (hasMacro(curLine)!=";") {
			string macroFound = hasMacro(curLine);
			//cout << "Found Macro \"" << macroFound << "\"at line " << numLine << endl;
			map<string,std::pair<int,int> >::iterator MNTCell = MNT.find(macroFound);
			map<string,vector<string> >::iterator MDTCell = MDT.find(macroFound);
			std::pair<int,int> MNTDefs = MNTCell->second;
			vector<string> auxiliarLines = MDTCell->second;
			vector<string> paramsToSub;
			try	{
				string finalLine = curLine.substr(curLine.find(macroFound)+macroFound.length()+1);
				if (curLine.find(':') != string::npos) {
					string curLabel = curLine.substr(0,curLine.find(':')+1);
					outputFile << curLabel << " ";
				}
				splitTokenize(finalLine,paramsToSub,",");
				if (paramsToSub.size() != static_cast<unsigned>(MNTDefs.second)) {
					addError(numLine,"Syntactical Error: Wrong number of parameters for current MACRO");
				}
				else {
					for (const string &subLines : auxiliarLines) {
						string auxSubLine = subLines;
						for (int j=0;j<MNTDefs.second;j++) {
							string MDTParamRegex = string("#") + to_string(j+1);
							auxSubLine = regex_replace(auxSubLine,regex(MDTParamRegex),paramsToSub[j]);
						}
						outputFile << auxSubLine << "\n";	
					}
				}
			}
			catch (std::out_of_range &e) {
				//cout << "Macro without params: " << e.what() << endl;
				if (curLine.find(':') != string::npos) {
					string curLabel = curLine.substr(0,curLine.find(':')+1);
					outputFile << curLabel << " ";
				}
				for (const string &subLines : auxiliarLines) {
					outputFile << subLines << "\n";	
				}
			}
		}
		else {
			if (!canWrite) {
				canWrite = true;
			}
			else {
				if (curLine.size()) {
					outputFile << curLine << "\n";
				}
			}
		}
	}
	//cout << "MNT: " << endl;
	//cout << MNT << endl;
	//cout << "MDT: " << endl;
	//cout << MDT << endl;
	if (this->errorList.size()) {
		printErrors();
		outputFile.close();
		remove(fileOut.c_str());
	}
	return this->errorList.size();
}