Ejemplo n.º 1
0
SDLShader::SDLShader( ShaderPathPair const & xShaderPaths )
        : mProgramID( 0 )
        , mVertexShaderSource( fileToString( xShaderPaths.VertexPath ) )
        , mFragmentShaderSource( fileToString(  xShaderPaths.FragmentPath ) )
{
        SISULOG( "In SDLShader Ctor" );
}
Ejemplo n.º 2
0
bool createBandwidthTestJob (JobToPUM *job) {
  job->probID = myid;
  job->nDimensions = 1;
  job->nItems[0] = 1;
  job->nGroupItems[0] = 1;
  job->startingKernel = malloc(sizeof("setupBandwidthTest") * sizeof(char));
  strcpy(job->startingKernel, "setupBandwidthTest");

  job->taskSource = fileToString(DATADIR"/pumanager/setupBandwidthTest.cl");
  if (job->taskSource == NULL) {
    fprintf(stderr,"FILE NOT FOUND! (building setupBandwidthTest)\n");
    return false;
  }

  job->taskSourceSize = strlen(job->taskSource)+1;


  job->nTotalArgs = 1;
  job->argTypes = calloc(job->nTotalArgs, sizeof(argument_type));
  job->argTypes[0] = INPUT;
  job->argSizes = calloc(job->nTotalArgs, sizeof(void *));
  job->argSizes[0] = sizeof(cl_char) * PUInfoStruct.availablePUs[job->runOn].max_memory_alloc - (100.0*1024*1024); //512MB
  fprintf(stderr,"running with %i Byte\n",job->argSizes[0]);
  job->arguments = calloc(job->nTotalArgs, sizeof(void *));
  job->arguments[0] = malloc(job->argSizes[0]);
  return true;
}
Ejemplo n.º 3
0
void compileShader(const char* fp, GLuint id){

    printf("%s\n", fp);

    char *src = fileToString(fp);

    glShaderSource(id, 1, &src, NULL);
    glCompileShader(id);

    GLint success = 0;
    glGetShaderiv(id, GL_COMPILE_STATUS, &success);

    if(success == GL_FALSE){

        GLint maxLength = 0;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength);

        char *log = malloc(maxLength + 1);
        glGetShaderInfoLog(id, maxLength, &maxLength, &log[0]);

        printf("%s\n", log);

        glDeleteShader(id);
        printf("%s %s\n", "GL_COMPILE_STATUS FALSE", fp);

        free(log);
    }

    free(src);
}
Ejemplo n.º 4
0
static void findXRefSymbols(FileDef *fd)
{
  // get the interface to a parser that matches the file extension
  ParserInterface *pIntf=Doxygen::parserManager->getParser(fd->getDefFileExtension());

  // get the programming language from the file name
  SrcLangExt lang = getLanguageFromFileName(fd->name());

  // reset the parsers state
  pIntf->resetCodeParserState();

  // create a new backend object 
  XRefDummyCodeGenerator *xrefGen = new XRefDummyCodeGenerator(fd);

  // parse the source code
  pIntf->parseCode(*xrefGen,
                0,
                fileToString(fd->absFilePath()),
                lang,
                FALSE,
                0,
                fd);

  // dismiss the object.
  delete xrefGen;
}
Ejemplo n.º 5
0
int main( int argc, char** argv )
{
    if( argc != 2 )
    {
        printf( "Nombre d'arguments incorrect. %i\n", argc);
        return -1;
    }

    FILE* file = fopen( argv[0], "r" );
    if( file != NULL )
    {
        unsigned long len;
        char* fileStr = fileToString( file, &len );
        fclose( file );
        char* enc = encryptString( fileStr, len );
        file = fopen( argv[1], "w" );
        writeStringToFile( file, enc );
        fclose( file );
    }
    else
    {
        printf( "Impossible d'ouvrir le fichier %s.\n", argv[0] );
        return -1;
    }

    return 0;
}
Ejemplo n.º 6
0
string HRBUSTJudger::getCEinfo() {
	string outer_oj_runid;
	stringstream sStream;
//	prepareCurl();
	cout << "GET ceinfo ....." << judgeResult.getRunId() << endl;
	sStream << judgeResult.getRunId();
	sStream >> outer_oj_runid;
	string res_url = "http://acm.hrbust.edu.cn/index.php?m=Status&a=showCompileError&run_id=" + outer_oj_runid; 
	cout << "RES_URL is: " << res_url << endl;
	curl_easy_setopt(easy_handle, CURLOPT_URL, res_url.c_str());
	performCurl("tmpfiles/cedata.html");
	cout << "GET res_url done!" << endl;

	string info = fileToString("tmpfiles/cedata.html");

	cout << "[CEinfo] down info.................." << endl;
	cout << "length of info : " << info.length() << endl;
	//cout << info << endl;
	
	if (code != CURLE_OK) {
		syslog(LOG_ERR, "getCEInfo failed.");
		return "NULL";
	} else {
		cout << "[CEinfo] regex info...................." << endl;
		string result;
		if (!RE2::PartialMatch(info, "(?s)showcode_mod_info.*?>(.*?)</td>", &result)) {
			cout << "[CEinfo] CEinfo is: " << "NULL" << endl;
			return "NULL";
		}
		cout << "[CEinfo] Ceinfo is: " << result << endl;
		return result;
	}
	
	return "NULL";
}
Ejemplo n.º 7
0
void WelcomePageView::slotThemeChanged()
{
    QString infoPageCss      = KStandardDirs::locate("data", "kdeui/about/kde_infopage.css");
    QString digikamCss       = KStandardDirs::locate("data", "digikam/about/digikam.css");
    QString fontSize         = QString::number(12);
    QString appTitle         = i18n("digiKam");
    QString slogan           = DAboutData::digiKamSlogan().toString();
    QString locationHtml     = KStandardDirs::locate("data", "digikam/about/main.html");
    QString locationRtl      = KStandardDirs::locate("data", "kdeui/about/kde_infopage_rtl.css" );
    QString rtl              = kapp->isRightToLeft() ? QString("@import \"%1\";" ).arg(locationRtl)
                               : QString();

    begin(KUrl(locationHtml).toLocalFile());

    QString content = fileToString(locationHtml);
    content         = content.arg(infoPageCss) // %1
                      .arg(rtl)                // %2
                      .arg(fontSize)           // %3
                      .arg(appTitle)           // %4
                      .arg(slogan)             // %5
                      .arg(infoPage())         // %6
                      .arg(digikamCss);        // %7

    //    kDebug() << content;

    write(content);
    end();
    show();
}
Ejemplo n.º 8
0
cl_program ClWrapper::createProgram(const char* fileName){
  char* programSource = NULL;
  int len = 0;
  int errorFlag = -1;
  if(!fileToString(fileName, programSource, len)){
    std::cerr << "Error loading program: " << fileName << std::endl;
    exit(EXIT_FAILURE);
  }
  cl_program program = 0;
  program = clCreateProgramWithSource(_context, 1, (const char**)&programSource, NULL, NULL);
  if (!program) {
    std::cerr << "Error: Failed to create compute program!" << std::endl;
    exit(EXIT_FAILURE);
  }

  cl_int err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
  if (err != CL_SUCCESS) {
    size_t len;
    char buffer[2048];

    std::cerr << "Error: Failed to build program executable!" << std::endl;
    clGetProgramBuildInfo(program, _device_id, CL_PROGRAM_BUILD_LOG,
			  sizeof(buffer), buffer, &len);
    std::cerr << buffer << std::endl;
    exit(1);
  }
  return program;
}
string Preprocessor::preprocess(string file_name) {
    string resultCode = fileToString(file_name);
    Preprocessor preprocessor = Preprocessor();
    resultCode = preprocessor.deleteComments(resultCode);
    resultCode = preprocessor.applyDefines(resultCode);
    resultCode = preprocessor.applyIncludes(resultCode, "", includeDirectory);
    return resultCode;
}
string Preprocessor::preprocess(string file_name, string filePath, string includeDirectory) {
    this->includeDirectory = includeDirectory;
    println(this->includeDirectory);
    string resultCode = fileToString(file_name);
    Preprocessor preprocessor = Preprocessor();
    resultCode =  preprocessor.deleteComments(resultCode);
    resultCode = preprocessor.applyDefines(resultCode);
    resultCode = preprocessor.applyIncludes(resultCode, filePath, includeDirectory);
    return resultCode;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QFile _log;
    for(int i=1;i<argc; ++i)
    {
        QString arg(argv[i]);
        if(arg=="-c")
        {
            //lisence.txt
            if(i+1==argc)return 1;
            copyright_header=fileToString(QString(argv[i+1]));
            ++i;
            continue;
        }
        if(arg=="-mask")
        {
            //mask.txt
            if(i+1==argc)return 1;
            fileToStringList(QString(argv[i+1]));
            ++i;
            continue;
        }
        if(arg=="-log")
        {
            //log.txt
            if(i+1==argc)return 1;
            _log.setFileName(QString(argv[i+1]));
            if(!_log.open(QIODevice::WriteOnly | QIODevice::Text))return 1;
            log=&_log;
            continue;
        }

        if(arg=="-a")
        {
            onlyalerts=true;
            continue;
        }
        if(arg=="-i")
        {
            infomode=true;
            continue;
        }
        if(arg=="-t")
        {
            testmode=true;
            continue;
        }
        QFileInfo file(arg);
        parseFile(file);
    }
    qDebug()<<gray_copyrights;
    return 0;
    //return a.exec();
}
Ejemplo n.º 12
0
void FileDef::parseSource()
{
  static bool filterSourceFiles = Config_getBool("FILTER_SOURCE_FILES");
  DevNullCodeDocInterface devNullIntf;
  ParserInterface *pIntf = Doxygen::parserManager->getParser(getDefFileExtension());
  pIntf->resetCodeParserState();
  pIntf->parseCode(
            devNullIntf,0,
            fileToString(absFilePath(),filterSourceFiles,TRUE),
            FALSE,0,this
           );
}
Ejemplo n.º 13
0
void HRBUSTJudger::getStatus() {
//	prepareCurl();
	while (true) {
		stringstream sStream;
		string lang, outer_oj_id;
		char *lang_tmp, *outer_oj_id_tmp;
		sStream << judgeInfo.getLang();
		sStream >> lang;
		sStream << judgeInfo.getId();
		sStream >> outer_oj_id;
		string res_url = "http://acm.hrbust.edu.cn/index.php?m=Status&a=showStatus&problem_id=" + outer_oj_id + "&user_name=acmstep&language=" + lang; 
		curl_easy_setopt(easy_handle, CURLOPT_URL, res_url.c_str());
	cout << "Before performCurl()................." << endl;
		performCurl("tmpfiles/statusdata.html");
	cout << "After performCurl()................." << endl;
		string res, runid, result, time_used, memory_used;
		string html = fileToString("tmpfiles/statusdata.html");
		if (code != CURLE_OK) syslog(LOG_ERR, "getStatus failed.");
		else {
			if (html.find("var is_login=\"\";") != string::npos || !RE2::PartialMatch(html, "(?s)<table class=\"ojlist\".*?<tr.*?(<tr.*?</tr>)", &res)) {
				syslog(LOG_ERR, "[ERROR] HRBUSTJudger: Failed to get status row.");
			}
			if (!RE2::PartialMatch(res, "(?s)<td.*?<td>([0-9]*).*?<td.*?<td.*?>(.*?)</td>", &runid, &result)) {
				syslog(LOG_ERR, "[ERROR] HRBUSTJudger: Fail to get current result.");
			}
			result = convertResult(trim(result));
			cout << "Result is: " << result << endl;
			if (isFinalResult(result)) {
				if (!RE2::PartialMatch(res, "(?s)>([0-9]*)ms.*?>([0-9]*)k", &time_used, &memory_used)) {
					syslog(LOG_ERR, "[ERROR] HRBUSTJudger: Failed to parse details from status row.");
				}
				cout << "0---------------------------------" << endl;
				cout << "Time used: " << time_used << " Memory_used: " << memory_used<< endl;
				judgeResult.setCodeId(judgeInfo.getCodeId());
				judgeResult.setRunId(atoi(trim(runid).c_str()));
				judgeResult.setJudgeStatus(status_table[result]);
				judgeResult.setRunTime(atoi(trim(time_used).c_str()));
				judgeResult.setRunMemory(atoi(trim(memory_used).c_str()));

				cout << "[Result] Get JudgeStatus: " << judgeResult.getJudgeStatus() << endl;
				if (judgeResult.getJudgeStatus() == OJ_CE) {
					judgeResult.setErrorInfo(getCEinfo());
				} else {
					judgeResult.setErrorInfo("NULL");
				}
				break;
			} else {
				usleep(5000);
			}
		}
	}
}
Ejemplo n.º 14
0
void HtmlGenerator::init()
{
  QCString dname=Config_getString("HTML_OUTPUT");
  QDir d(dname);
  if (!d.exists() && !d.mkdir(dname))
  {
    err("Could not create output directory %s\n",dname.data());
    exit(1);
  }
  writeLogo(dname);
  if (!Config_getString("HTML_HEADER").isEmpty()) 
  {
    g_header=fileToString(Config_getString("HTML_HEADER"));
    //printf("g_header='%s'\n",g_header.data());
  }
  if (!Config_getString("HTML_FOOTER").isEmpty()) 
  {
    g_footer=fileToString(Config_getString("HTML_FOOTER"));
    //printf("g_footer='%s'\n",g_footer.data());
  }
  createSubDirs(d);
}
Ejemplo n.º 15
0
    bool GlShader::loadFromFiles(const std::vector<std::string>& fileNames)
    {
        _fileName = implicitName(fileNames, _type);

        std::vector<std::string> sources;
        for(const auto& file : fileNames)
        {
            sources.push_back( fileToString(file) );
            if(sources.back().empty())
                sources.pop_back();
        }

        return loadFromStrings( sources );
    }
Ejemplo n.º 16
0
void HRBUSTJudger::login() {
	prepareCurl();
	string lgin_url = "http://acm.hrbust.edu.cn/index.php?m=User&a=login";
	curl_easy_setopt(easy_handle, CURLOPT_URL, lgin_url.c_str());
	string post = (string)"m=User&a=login&user_name=acmstep&password=acmstep&ajax=1";
	curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDS, post.c_str()); 
	performCurl("tmpfiles/logindata.html");
	cout << "Login performCurl done!" << endl;
	string res = fileToString("tmpfiles/logindata.html");

	if (res.find("{\"status\":0") != string::npos ||
			res.find("<div class='body'>Sorry!Login Error,Please Retry!</div>") != string::npos) {
		cout << "Login failed!" << endl;
	} else cout << "Login success!" << endl;
}
Ejemplo n.º 17
0
bool createHighProcJob (JobToPUM *job) {
  job->probID = myid;

//  if (job->runOn == CL_DEVICE_TYPE_CPU) {
    job->nDimensions = 1;
    job->nItems[0] = 1024;
    job->nGroupItems[0] = 1;
/*  }
  else {
    job->nDimensions = 2;
    job->nItems[0] = job->nItems[1] = 512;
    job->nGroupItems[0] = job->nGroupItems[1] = 16;
  }
*/
  job->startingKernel = malloc(sizeof("setupHighProcTest") * sizeof(char));
  strcpy(job->startingKernel, "setupHighProcTest");



  job->taskSource = fileToString(DATADIR"/pumanager/setupHighProcTest.cl");
  if (job->taskSource == NULL) {
    fprintf(stderr,"FILE NOT FOUND! (building setupHighProcTest)\n");
    return false;
  }

  job->taskSourceSize = strlen(job->taskSource)+1;


  job->nTotalArgs = 1;
  job->argTypes = calloc(job->nTotalArgs, sizeof(argument_type));
  job->argTypes[0] = OUTPUT;

  job->argSizes = calloc(job->nTotalArgs, sizeof(int));
  job->argSizes[0] = sizeof(int);


  job->arguments = calloc(job->nTotalArgs, sizeof(void *));
  for (int i = 0; i < job->nTotalArgs; i++) {
    job->arguments[i] = malloc(job->argSizes[i]);
  }

//  job->returnTo = defaultRCID; //not used

  return true;
}
Ejemplo n.º 18
0
void WelcomePageView::slotThemeChanged()
{
    QString appTitle         = i18n("digiKam");
    QString slogan           = DAboutData::digiKamSlogan();
    QString locationHtml     = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String("digikam/about/main.html"));

    QString content = QString::fromUtf8(fileToString(locationHtml));
    content         = content.arg(appTitle)
                             .arg(slogan)
                             .arg(i18n("Welcome to digiKam %1", QLatin1String(digikam_version)))
                             .arg(featuresTabContent()[0])
                             .arg(aboutTabContent()[0])
                             .arg(featuresTabContent()[1])
                             .arg(aboutTabContent()[1]);
    //qCDebug(DIGIKAM_GENERAL_LOG) << content;

    setHtml(content, QUrl::fromLocalFile(locationHtml));
}
Ejemplo n.º 19
0
    bool AbstractTeam::loadScene(
            const string& fileName)
    {
        bool ok = false;
        string stream = fileToString(fileName, &ok);

        if(ok)
        {
            StageSetJsonReader reader;
            reader.deserialize(*this, stream);
			return true;
        }
        else
        {
            getLog().postMessage(new Message('E', false,
                "StageSet failed to load from '" + fileName + "'.",
                "AbstractTeam"));
			return false;
        }
    }
Ejemplo n.º 20
0
END_TEST

/* Test passes!*/
START_TEST(core_fileToString){
/* testing method: generate a new text file with specified content, read the content, and delete the file*/
   FILE *fp;
   char *ch=NULL;
   char filename[]="this_is_test_file.txt";
   fp=fopen(filename, "w");
   fprintf(fp, "testing words");

   fclose(fp);
   fp=fopen(filename, "r");

   ch = fileToString(fp);
   fclose(fp);
   remove(filename);

   fail_unless(strcmp(ch, "testing words") == 0, "fileToString function test failed");

  }
Ejemplo n.º 21
0
int moduleLoadJS(JSContext *cx, char *moduleName){
	char *fName = NULL;
	fName = (char*)malloc(sizeof (MODULES_DIR) + sizeof(moduleName) + sizeof(JSCRIPT_EXT) + 1);
	if(fName){
		strcpy(fName,MODULES_DIR);
		strcat(fName,moduleName);
		strcat(fName,JSCRIPT_EXT);
		jsval vl;
		char *script = fileToString(fName);
		if(script){
			if(JS_EvaluateScript(cx, JS_GetGlobalObject(cx), script, strlen(script), fName, 0, &vl) == JS_FALSE)
				fprint(stderr,"Error evaluating script %s\n",fName);
		} else {
			fprint(stderr,"Couldn't read script: %s\n",fName);
		}	
		free(fName);
		free(script);
		return 1;
	}
	fprint(stderr,"Error loading Module %s\n",moduleName);
	return FALSE;
}
Ejemplo n.º 22
0
bool createLowProcJob (JobToPUM *job) {
  job->probID = myid;

  //job->jobID //TO BE FILLED BY THE PUM
  //job->runOn = CL_DEVICE_TYPE_CPU;//TO BE FILLED BY THE PUM
  job->nDimensions = 0;

  job->startingKernel = malloc(sizeof("setupLowProcTest"));
  strcpy(job->startingKernel,"setupLowProcTest");
  job->startingNameSize = strlen(job->startingKernel)+1;

  job->taskSource = fileToString(DATADIR"/pumanager/setupLowProcTest.cl");
  if (job->taskSource == NULL) {
    fprintf(stderr,"FILE NOT FOUND! (while creating LowProcJob)\n");
    return false;
  }
  job->taskSourceSize = strlen(job->taskSource)+1;

  ///Setting up arguments
  job->nTotalArgs = 2;
  job->argTypes = calloc(job->nTotalArgs, sizeof(argument_type));
  job->argTypes[0] = INPUT;
  job->argTypes[1] = OUTPUT;

  job->argSizes = calloc(job->nTotalArgs, sizeof(argument_type));
  job->argSizes[0] = job->argSizes[1] = sizeof(cl_uint);

  cl_uint *inBuff = malloc(sizeof(cl_uint));
  cl_uint *outBuff = malloc(sizeof(cl_uint));
  inBuff[0] = 100;

  job->arguments = calloc(job->nTotalArgs, sizeof(void *));
  job->arguments[0] = inBuff;
  job->arguments[1] = outBuff;

//  job->returnTo = defaultRCID; //not used

  return true;
}
Ejemplo n.º 23
0
void HtmlGenerator::writeStyleInfo(int part)
{
  //printf("writeStyleInfo(%d)\n",part);
  if (part==0)
  {
    if (Config_getString("HTML_STYLESHEET").isEmpty()) // write default style sheet
    {
      //printf("write doxygen.css\n");
      startPlainFile("doxygen.css"); 
      
      // alternative, cooler looking titles
      //t << "H1 { text-align: center; border-width: thin none thin none;" << endl;
      //t << "     border-style : double; border-color : blue; padding-left : 1em; padding-right : 1em }" << endl;

      t << defaultStyleSheet;
      endPlainFile();
    }
    else // write user defined style sheet
    {
      QCString cssname=Config_getString("HTML_STYLESHEET");
      QFileInfo cssfi(cssname);
      if (!cssfi.exists() || !cssfi.isFile() || !cssfi.isReadable())
      {
        err("Error: style sheet %s does not exist or is not readable!", Config_getString("HTML_STYLESHEET").data());
      }
      else
      {
        // convert style sheet to string
        QCString fileStr = fileToString(cssname);
        // write the string into the output dir
        startPlainFile(cssfi.fileName());
        t << fileStr;
        endPlainFile();
      }
    }
  }
}
Ejemplo n.º 24
0
int lookAndLoadjsModule(char *name,JSContext *cx){
	char *fName = NULL;
	fName = (char*)malloc(strlen(name) + strlen(JSCRIPT_EXT) +  + strlen(MODULES_DIR) + 1);
	if(!fName) return 0;
	strcpy(fName,name);
	strcat(fName,JSCRIPT_EXT);
	DIR *directory = NULL;
	struct dirent *ent = NULL;
	directory = opendir(MODULES_DIR);
	if(directory == NULL){
		fprint(stderr,"Unable to open Modules directory\n");
		return 0;
	} else {
		while((ent = readdir(directory)) != NULL){
			if(!strcmp(ent->d_name,fName)){
				//Execute it here:
				strcpy(fName,MODULES_DIR);
				strcat(fName,ent->d_name);
				jsval vl;
				char *script = fileToString(fName);
				if(script){
					if(JS_EvaluateScript(cx, JS_GetGlobalObject(cx), script, strlen(script), fName, 0, &vl) == JS_FALSE)
						fprint(stderr,"Error evaluating script %s\n",fName);
				}else {
					fprint(stderr,"Couldn't read script: %s\n",fName);
				}	
				closedir(directory);
				free(fName);
				free(script);
				return 1;
			}
		}
		closedir(directory);
		free(fName);
	}
	return 0;
}
Ejemplo n.º 25
0
void processMakeFile(const QFileInfo& file, bool assume_our)
{
    int offset(0);
    bool skipfile(false), modify_file(assume_our);
    QString text=fileToString(file.absoluteFilePath());
    QStringList output;
    while(offset<text.length())
    {
        //qDebug()<<"==========================";
        int off_ss=text.indexOf('#', offset);

        if(off_ss<0)
        {
            //qDebug()<<"tail="<<text.mid(offset);
            output<<text.mid(offset);
            break;
        }

        bool comment_from_newline(true);
        int newlinebefore=off_ss==0 ? 0 : text.lastIndexOf('\n', off_ss)+1;
        for(int i=newlinebefore+1; i<off_ss; ++i)
        {
            if(!text.at(i).isSpace()){
                comment_from_newline=false;
                break;
            }
        }
        int end=text.indexOf('\n', off_ss);
        if(end<0)end=text.length();else ++end;//end if after \n
        //grab more lines
        if(comment_from_newline)
        {
            int tabspace=off_ss-newlinebefore;
            //find more comments from newline
            while(end<text.length())
            {
                int nextss=text.indexOf('#',end);
                if(nextss<0)break;
                //check if there is \n between // and end
                int moreN=text.indexOf('\n', end);
                if(moreN>=0 && moreN<nextss)break;
                //check for [end]...spaces...//
                bool spaces_between(true);
                for(int i=end; i<nextss; ++i)
                {
                    if(!text.at(i).isSpace()){
                        spaces_between=false;
                        break;
                    }
                }
                if(!spaces_between || nextss-end!=tabspace)
                    break;
                end=text.indexOf('\n', nextss);
                if(end<0)end=text.length();else ++end;
            }
        }
        //qDebug()<<"... ... comment at "<<off_ss<<"--"<<end;
        //qDebug()<<text.mid(off_ss, end-off_ss);
        if(RemoveComment(file.absoluteFilePath(), text, off_ss, end, skipfile, modify_file))
        {
            if(offset<off_ss)
            {
                //qDebug()<<"output {"<<text.mid(offset, off_ss-offset)<<"}";
                output<<text.mid(offset,off_ss-offset);
            }
        }
        else
        {
            //qDebug()<<"output2{"<<text.mid(offset, end-offset)<<"}";
            output<<text.mid(offset, end-offset);
        }
        offset=end;
    }
    storeFile(text, file.absoluteFilePath(), output, skipfile, modify_file, true);
}
Ejemplo n.º 26
0
char* launchApp(char *appName,int isMenu){
	static int nruns = 0;
	char* tmp = NULL,*script = NULL, *addrBack = NULL;
	if(appName){
		static JSContext *cx = NULL;
		static JSObject *gl = NULL;
		script = fileToString(LIBRARY);
		if(!(cx = JS_NewContext(runtime, 8192))){
			fprint(stderr,"Problem creating runtime\n");
			exit(EXIT_FAILURE);
		}
		JS_SetErrorReporter(cx, reportError);
		//if(!(gl = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL))){
		
		static struct JSPrincipals def_principles = {0};
		if(!(gl = JS_NewGlobalObject(cx, &global_class, NULL))){
			fprint(stderr,"Problem creating global object\n");
			exit(EXIT_FAILURE);
		}
		JSCompartment *cmp = JS_EnterCompartment(cx, gl);
		
		if (!(JS_InitStandardClasses(cx, gl))){
			fprint(stderr,"Problem creating standard classes\n");
			exit(EXIT_FAILURE);
		}
		if(!JS_DefineFunctions(cx, gl, jsFunctions)){
			fprint(stderr,"Unable to load native functions\n");
			exit(EXIT_FAILURE);
		}
		globalObject = gl;
		char *pathToFile = NULL;
		if(isMenu){
			pathToFile = (char*)malloc(1+strlen(MENU_DIR));
			strcpy(pathToFile,MENU_DIR);
		} else {
			pathToFile = (char*)malloc(strlen(appName) + 1 + strlen(GAMES_DIR));
			strcpy(pathToFile,GAMES_DIR);
			strcat(pathToFile,appName);
			//strcat(pathToFile,"/");
		}
		
		
		JSBool ran = JS_FALSE;
		jsval retVal;
		
		obj.chrootPath = pathToFile;
		
		JS_SetPrivate(cx,gl,&obj);
		
		SDL_FlushEvents(); //clear queue of events before starting a new app.
		if(isMenu && 0 == nruns) {
			//define the property first_run = true;
			JS_DefineProperty(cx,JS_GetGlobalObject(cx),"first_run",BOOLEAN_TO_JSVAL(JS_TRUE),NULL,NULL,0);
		}
		
		if(script){
			loadBaseClasses(appName,pathToFile,cx); //appName is without the extension, appPath needs the directory to chroot
			ran = JS_EvaluateScript(cx, gl, script, strlen(script) , LIBRARY,0, &retVal);
		}
		nruns++;
		
		clearModules(cx);
		JS_GC(JS_GetRuntime(cx));
		JS_LeaveCompartment(cx,cmp);
		//The user requested to quit.
		if(SDL_QuitRequested()){
			if(script)free(script);
			exitProgram(cx);
			exit(EXIT_SUCCESS);
		}

		if(isMenu && (ran == JS_FALSE)){
			if(script) free(script);
			exitProgram(cx);
			exit(EXIT_FAILURE);
		}
		if(ran != JS_FALSE){
			if(JSVAL_IS_STRING(retVal)){
				addrBack = JS_EncodeString(cx,JSVAL_TO_STRING(retVal));
				tmp = (char*)malloc(strlen(addrBack) +1);
				strcpy(tmp,addrBack);
				JS_free(cx,addrBack);
				addrBack = tmp;
			} 
			if(JSVAL_IS_BOOLEAN(retVal) && isMenu){
				if(script) free(script);
				if(pathToFile) free(pathToFile);
				exitProgram(cx);
				exit(EXIT_SUCCESS);
			}
		} else {
			addrBack = NULL;
		}
		if(script) free(script);
		if(pathToFile) free(pathToFile);
		JS_DestroyContext(cx);
		return addrBack;
	}
}
Ejemplo n.º 27
0
void ClangParser::start(const char *fileName,QStrList &filesInTranslationUnit)
{
  static bool clangAssistedParsing = Config_getBool(CLANG_ASSISTED_PARSING);
  static QStrList &includePath = Config_getList(INCLUDE_PATH);
  static QStrList clangOptions = Config_getList(CLANG_OPTIONS);
  static QCString clangCompileDatabase = Config_getList(CLANG_COMPILATION_DATABASE_PATH);
  if (!clangAssistedParsing) return;
  //printf("ClangParser::start(%s)\n",fileName);
  p->fileName = fileName;
  p->index    = clang_createIndex(0, 0);
  p->curLine  = 1;
  p->curToken = 0;
  QDictIterator<void> di(Doxygen::inputPaths);
  int argc=0;
  std::string error;
  // load a clang compilation database (https://clang.llvm.org/docs/JSONCompilationDatabase.html)
  // this only needs to be loaded once, and could be refactored to a higher level function
  static std::unique_ptr<clang::tooling::CompilationDatabase> db =
      clang::tooling::CompilationDatabase::loadFromDirectory(clangCompileDatabase.data(), error);
  int clang_option_len = 0;
  std::vector<clang::tooling::CompileCommand> command;
  if (strcmp(clangCompileDatabase, "0") != 0) {
      if (db == nullptr) {
          // user specified a path, but DB file was not found
          err("%s using clang compilation database path of: \"%s\"\n", error.c_str(),
              clangCompileDatabase.data());
      } else {
          // check if the file we are parsing is in the DB
          command = db->getCompileCommands(fileName);
          if (!command.empty() ) {
              // it's possible to have multiple entries for the same file, so use the last entry
              clang_option_len = command[command.size()-1].CommandLine.size();
          }
      }
  }
  char **argv = (char**)malloc(sizeof(char*)*(4+Doxygen::inputPaths.count()+includePath.count()+clangOptions.count()+clang_option_len));
  if (!command.empty() ) {
      std::vector<std::string> options = command[command.size()-1].CommandLine;
      // copy each compiler option used from the database. Skip the first which is compiler exe.
      for (auto option = options.begin()+1; option != options.end(); option++) {
          argv[argc++] = strdup(option->c_str());
      }
      // this extra addition to argv is accounted for as we are skipping the first entry in
      argv[argc++]=strdup("-w"); // finally, turn off warnings.
  } else {
  // add include paths for input files
  for (di.toFirst();di.current();++di,++argc)
  {
    QCString inc = QCString("-I")+di.currentKey();
    argv[argc]=strdup(inc.data());
    //printf("argv[%d]=%s\n",argc,argv[argc]);
  }
  // add external include paths
  for (uint i=0;i<includePath.count();i++)
  {
    QCString inc = QCString("-I")+includePath.at(i);
    argv[argc++]=strdup(inc.data());
  }
  // user specified options
  for (uint i=0;i<clangOptions.count();i++)
  {
    argv[argc++]=strdup(clangOptions.at(i));
  }
  // extra options
  argv[argc++]=strdup("-ferror-limit=0");
  argv[argc++]=strdup("-x");

  // Since we can be presented with a .h file that can contain C/C++ or
  // Objective C code and we need to configure the parser before knowing this,
  // we use the source file to detected the language. Detection will fail if you
  // pass a bunch of .h files containing ObjC code, and no sources :-(
  SrcLangExt lang = getLanguageFromFileName(fileName);
  if (lang==SrcLangExt_ObjC || p->detectedLang!=ClangParser::Private::Detected_Cpp)
  {
    QCString fn = fileName;
    if (p->detectedLang==ClangParser::Private::Detected_Cpp && 
        (fn.right(4).lower()==".cpp" || fn.right(4).lower()==".cxx" ||
         fn.right(3).lower()==".cc" || fn.right(2).lower()==".c"))
    { // fall back to C/C++ once we see an extension that indicates this
      p->detectedLang = ClangParser::Private::Detected_Cpp;
    }
    else if (fn.right(3).lower()==".mm") // switch to Objective C++
    {
      p->detectedLang = ClangParser::Private::Detected_ObjCpp;
    }
    else if (fn.right(2).lower()==".m") // switch to Objective C
    {
      p->detectedLang = ClangParser::Private::Detected_ObjC;
    }
  }
  switch(p->detectedLang)
  {
    case ClangParser::Private::Detected_Cpp: 
      argv[argc++]=strdup("c++"); 
      break;
    case ClangParser::Private::Detected_ObjC: 
      argv[argc++]=strdup("objective-c"); 
      break;
    case ClangParser::Private::Detected_ObjCpp: 
      argv[argc++]=strdup("objective-c++"); 
      break;
  }

  // provide the input and and its dependencies as unsaved files so we can
  // pass the filtered versions
  argv[argc++]=strdup(fileName);
  }
  static bool filterSourceFiles = Config_getBool(FILTER_SOURCE_FILES);
  //printf("source %s ----------\n%s\n-------------\n\n",
  //    fileName,p->source.data());
  uint numUnsavedFiles = filesInTranslationUnit.count()+1;
  p->numFiles = numUnsavedFiles;
  p->sources = new QCString[numUnsavedFiles];
  p->ufs     = new CXUnsavedFile[numUnsavedFiles];
  p->sources[0]      = detab(fileToString(fileName,filterSourceFiles,TRUE));
  p->ufs[0].Filename = strdup(fileName);
  p->ufs[0].Contents = p->sources[0].data();
  p->ufs[0].Length   = p->sources[0].length();
  QStrListIterator it(filesInTranslationUnit);
  uint i=1;
  for (it.toFirst();it.current() && i<numUnsavedFiles;++it,i++)
  {
    p->fileMapping.insert(it.current(),new uint(i));
    p->sources[i]      = detab(fileToString(it.current(),filterSourceFiles,TRUE));
    p->ufs[i].Filename = strdup(it.current());
    p->ufs[i].Contents = p->sources[i].data();
    p->ufs[i].Length   = p->sources[i].length();
  }

  // let libclang do the actual parsing
  p->tu = clang_parseTranslationUnit(p->index, 0,
                                     argv, argc, p->ufs, numUnsavedFiles, 
                                     CXTranslationUnit_DetailedPreprocessingRecord);
  // free arguments
  for (int i=0;i<argc;++i)
  {
    free(argv[i]);
  }
  free(argv);

  if (p->tu)
  {
    // filter out any includes not found by the clang parser
    determineInputFilesInSameTu(filesInTranslationUnit);

    // show any warnings that the compiler produced
    for (uint i=0, n=clang_getNumDiagnostics(p->tu); i!=n; ++i) 
    {
      CXDiagnostic diag = clang_getDiagnostic(p->tu, i); 
      CXString string = clang_formatDiagnostic(diag,
          clang_defaultDiagnosticDisplayOptions()); 
      err("%s [clang]\n",clang_getCString(string));
      clang_disposeString(string);
      clang_disposeDiagnostic(diag);
    }

    // create a source range for the given file
    QFileInfo fi(fileName);
    CXFile f = clang_getFile(p->tu, fileName);
    CXSourceLocation fileBegin = clang_getLocationForOffset(p->tu, f, 0);
    CXSourceLocation fileEnd   = clang_getLocationForOffset(p->tu, f, p->ufs[0].Length);
    CXSourceRange    fileRange = clang_getRange(fileBegin, fileEnd);

    // produce a token stream for the file
    clang_tokenize(p->tu,fileRange,&p->tokens,&p->numTokens);

    // produce cursors for each token in the stream
    p->cursors=new CXCursor[p->numTokens];
    clang_annotateTokens(p->tu,p->tokens,p->numTokens,p->cursors);
  }
  else
  {
    p->tokens    = 0;
    p->numTokens = 0;
    p->cursors   = 0;
    err("clang: Failed to parse translation unit %s\n",fileName);
  }
}
Ejemplo n.º 28
0
void ClangParser::start(const QString &fileName, QStringList &includeFiles)
{
   static QStringList includePath = Config::getList("include-path");    
   static QStringList clangFlags  = Config::getList("clang-flags");

   p->fileName = fileName;
   p->index    = clang_createIndex(0, 0);
   p->curLine  = 1;
   p->curToken = 0;

   char **argv = (char **)malloc(sizeof(char *) * (4 + Doxy_Globals::inputPaths.count() + includePath.count() + clangFlags.count()));
   int argc = 0;

   // add include paths for input files  
   for (auto item : Doxy_Globals::inputPaths) { 
      QString inc = "-I" + item;
      argv[argc] = strdup(inc.toUtf8());  

      ++argc;
   }

   // add external include paths
   for (uint i = 0; i < includePath.count(); i++) {  
      QString inc = "-I" + includePath.at(i);
      argv[argc++] = strdup(inc.toUtf8());  
   }

   // user specified options
   for (uint i = 0; i < clangFlags.count(); i++) {
      argv[argc++] = strdup(clangFlags.at(i).toUtf8());
   }

   // extra options
   argv[argc++] = strdup("-ferror-limit=0");
   argv[argc++] = strdup("-x");

   // Since we can be presented with an .h file that can contain C, C++, or Objective C,
   // we need to configure the parser before knowing this.
   // Use the source file to detected the language. Detection will fail if you
   // pass a bunch of .h files containing ObjC code and no source 

   SrcLangExt lang = getLanguageFromFileName(fileName);

   if (lang == SrcLangExt_ObjC || p->detectedLang != ClangParser::Private::Detected_Cpp) {
      QString fn = fileName;

      if (p->detectedLang == ClangParser::Private::Detected_Cpp &&
            (fn.right(4).toLower() == ".cpp" || fn.right(4).toLower() == ".cxx" ||
             fn.right(3).toLower() == ".cc" || fn.right(2).toLower() == ".c")) {

         // fall back to C/C++ once we see an extension that indicates this
         p->detectedLang = ClangParser::Private::Detected_Cpp;

      } else if (fn.right(3).toLower() == ".mm") { 
         // switch to Objective C++
         p->detectedLang = ClangParser::Private::Detected_ObjCpp;

      } else if (fn.right(2).toLower() == ".m") { 
         // switch to Objective C
         p->detectedLang = ClangParser::Private::Detected_ObjC;
      }
   }

   switch (p->detectedLang) {
      case ClangParser::Private::Detected_Cpp:
         argv[argc++] = strdup("c++");
         break;

      case ClangParser::Private::Detected_ObjC:
         argv[argc++] = strdup("objective-c");
         break;

      case ClangParser::Private::Detected_ObjCpp:
         argv[argc++] = strdup("objective-c++");
         break;
   }

   // provide the input and and its dependencies as unsaved files so we can pass the filtered versions
   static bool filterSourceFiles = Config::getBool("filter-source-files");

   argv[argc++] = strdup(fileName.toUtf8());
 
   uint numUnsavedFiles = includeFiles.count() + 1;

   p->numFiles = numUnsavedFiles;
   p->sources  = new QByteArray[numUnsavedFiles];
   p->ufs      = new CXUnsavedFile[numUnsavedFiles];

   p->sources[0]      = detab(fileToString(fileName, filterSourceFiles, true)).toUtf8();
   p->ufs[0].Filename = strdup(fileName.toUtf8());
   p->ufs[0].Contents = p->sources[0].constData();
   p->ufs[0].Length   = p->sources[0].length();

   //  
   uint i = 1;
   for (auto item : includeFiles) {       

      p->fileMapping.insert(item, i);

      p->sources[i]      = detab(fileToString(item, filterSourceFiles, true)).toUtf8();
      p->ufs[i].Filename = strdup(item.toUtf8());
      p->ufs[i].Contents = p->sources[i].constData();
      p->ufs[i].Length   = p->sources[i].length();

      i++;
   }

   // let libclang do the actual parsing
   CXErrorCode errorCode = clang_parseTranslationUnit2(p->index, 0, argv, argc, 0, 0, 
                  CXTranslationUnit_DetailedPreprocessingRecord, &(p->tu) );

   // free arguments
   for (int i = 0; i < argc; ++i) {
      free(argv[i]);
   }
   free(argv);

   if (p->tu) {
      // filter out any includes not found by the clang parser
      determineInputFiles(includeFiles);

      // show any warnings the compiler produced
      uint n = clang_getNumDiagnostics(p->tu);

      for (uint i = 0; i != n; ++i) {
         CXDiagnostic diag = clang_getDiagnostic(p->tu, i);
         CXString string   = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());

         err("Clang parser warning -- %s\n", clang_getCString(string));
         clang_disposeString(string);

         clang_disposeDiagnostic(diag);
      }

      // create a source range for the given file
      QFileInfo fi(fileName);
      CXFile f = clang_getFile(p->tu, fileName.toUtf8());

      CXSourceLocation fileBegin = clang_getLocationForOffset(p->tu, f, 0);
      CXSourceLocation fileEnd   = clang_getLocationForOffset(p->tu, f, p->ufs[0].Length);
      CXSourceRange    fileRange = clang_getRange(fileBegin, fileEnd);

      // produce a token stream for the file
      clang_tokenize(p->tu, fileRange, &p->tokens, &p->numTokens);

      // produce cursors for each token in the stream
      p->cursors = new CXCursor[p->numTokens];
      clang_annotateTokens(p->tu, p->tokens, p->numTokens, p->cursors);

   } else {
      p->tokens    = 0;
      p->numTokens = 0;
      p->cursors   = 0;

      err("Clang failed to parse translation unit -- %s\n", qPrintable(fileName));
   }
}
Ejemplo n.º 29
0
/*! Write a source listing of this file to the output */
void FileDef::writeSource(OutputList &ol)
{
  static bool generateTreeView = Config_getBool("GENERATE_TREEVIEW");
  static bool filterSourceFiles = Config_getBool("FILTER_SOURCE_FILES");
  static bool latexSourceCode   = Config_getBool("LATEX_SOURCE_CODE");
  QCString title = docname;
  if (!fileVersion.isEmpty())
  {
    title+=(" ("+fileVersion+")");
  }
  QCString pageTitle = theTranslator->trSourceFile(title);
  ol.disable(OutputGenerator::Man);
  ol.disable(OutputGenerator::RTF);
  if (!latexSourceCode) ol.disable(OutputGenerator::Latex);

  if (Config_getBool("SHOW_DIRECTORIES") && getDirDef())
  {
    startFile(ol,getSourceFileBase(),0,pageTitle,HLI_FileVisible,
        !generateTreeView,getOutputFileBase());
    if (!generateTreeView)
    {
      getDirDef()->writeNavigationPath(ol);
      ol.endQuickIndices();
    }
    startTitle(ol,getOutputFileBase());
    ol.parseText(name());
    endTitle(ol,getOutputFileBase(),title);
  }
  else
  {
    startFile(ol,getSourceFileBase(),0,pageTitle,HLI_FileVisible,
        !generateTreeView,getOutputFileBase());
    startTitle(ol,getSourceFileBase());
    ol.parseText(title);
    endTitle(ol,getSourceFileBase(),0);
  }

  ol.startContents();

  if (isLinkable())
  {
    if (latexSourceCode) ol.disable(OutputGenerator::Latex);
    ol.startTextLink(getOutputFileBase(),0);
    ol.parseText(theTranslator->trGotoDocumentation());
    ol.endTextLink();
    if (latexSourceCode) ol.enable(OutputGenerator::Latex);
  }

  ParserInterface *pIntf = Doxygen::parserManager->getParser(getDefFileExtension());
  pIntf->resetCodeParserState();
  ol.startCodeFragment();
  pIntf->parseCode(ol,0,
            fileToString(absFilePath(),filterSourceFiles,TRUE),
            FALSE,0,this
           );
  ol.endCodeFragment();
  ol.endContents();
  if (generateTreeView)
  {
    writeNavigationPath(ol);
    endFile(ol,TRUE);
  }
  else
  {
    endFile(ol);
  }
  ol.enableAll();
}
Ejemplo n.º 30
0
void ClangParser::start(const char *fileName,QStrList &filesInTranslationUnit)
{
  static bool clangAssistedParsing = Config_getBool("CLANG_ASSISTED_PARSING");
  static QStrList &includePath = Config_getList("INCLUDE_PATH");
  static QStrList clangOptions = Config_getList("CLANG_OPTIONS");
  if (!clangAssistedParsing) return;
  //printf("ClangParser::start(%s)\n",fileName);
  p->fileName = fileName;
  p->index    = clang_createIndex(0, 0);
  p->curLine  = 1;
  p->curToken = 0;
  char **argv = (char**)malloc(sizeof(char*)*(4+Doxygen::inputPaths.count()+includePath.count()+clangOptions.count()));
  QDictIterator<void> di(Doxygen::inputPaths);
  int argc=0;
  // add include paths for input files
  for (di.toFirst();di.current();++di,++argc)
  {
    QCString inc = QCString("-I")+di.currentKey();
    argv[argc]=strdup(inc.data());
    //printf("argv[%d]=%s\n",argc,argv[argc]);
  }
  // add external include paths
  for (uint i=0;i<includePath.count();i++)
  {
    QCString inc = QCString("-I")+includePath.at(i);
    argv[argc++]=strdup(inc.data());
  }
  // user specified options
  for (uint i=0;i<clangOptions.count();i++)
  {
    argv[argc++]=strdup(clangOptions.at(i));
  }
  // extra options
  argv[argc++]=strdup("-ferror-limit=0");
  argv[argc++]=strdup("-x");

  // Since we can be presented with a .h file that can contain C/C++ or
  // Objective C code and we need to configure the parser before knowing this,
  // we use the source file to detected the language. Detection will fail if you
  // pass a bunch of .h files containing ObjC code, and no sources :-(
  SrcLangExt lang = getLanguageFromFileName(fileName);
  if (lang==SrcLangExt_ObjC || p->detectedLang!=ClangParser::Private::Detected_Cpp)
  {
    QCString fn = fileName;
    if (p->detectedLang==ClangParser::Private::Detected_Cpp && 
        (fn.right(4).lower()==".cpp" || fn.right(4).lower()==".cxx" ||
         fn.right(3).lower()==".cc" || fn.right(2).lower()==".c"))
    { // fall back to C/C++ once we see an extension that indicates this
      p->detectedLang = ClangParser::Private::Detected_Cpp;
    }
    else if (fn.right(3).lower()==".mm") // switch to Objective C++
    {
      p->detectedLang = ClangParser::Private::Detected_ObjCpp;
    }
    else if (fn.right(2).lower()==".m") // switch to Objective C
    {
      p->detectedLang = ClangParser::Private::Detected_ObjC;
    }
  }
  switch(p->detectedLang)
  {
    case ClangParser::Private::Detected_Cpp: 
      argv[argc++]=strdup("c++"); 
      break;
    case ClangParser::Private::Detected_ObjC: 
      argv[argc++]=strdup("objective-c"); 
      break;
    case ClangParser::Private::Detected_ObjCpp: 
      argv[argc++]=strdup("objective-c++"); 
      break;
  }

  // provide the input and and its dependencies as unsaved files so we can
  // pass the filtered versions
  argv[argc++]=strdup(fileName);
  static bool filterSourceFiles = Config_getBool("FILTER_SOURCE_FILES");
  //printf("source %s ----------\n%s\n-------------\n\n",
  //    fileName,p->source.data());
  uint numUnsavedFiles = filesInTranslationUnit.count()+1;
  p->numFiles = numUnsavedFiles;
  p->sources = new QCString[numUnsavedFiles];
  p->ufs     = new CXUnsavedFile[numUnsavedFiles];
  p->sources[0]      = detab(fileToString(fileName,filterSourceFiles,TRUE));
  p->ufs[0].Filename = strdup(fileName);
  p->ufs[0].Contents = p->sources[0].data();
  p->ufs[0].Length   = p->sources[0].length();
  QStrListIterator it(filesInTranslationUnit);
  uint i=1;
  for (it.toFirst();it.current() && i<numUnsavedFiles;++it,i++)
  {
    p->fileMapping.insert(it.current(),new uint(i));
    p->sources[i]      = detab(fileToString(it.current(),filterSourceFiles,TRUE));
    p->ufs[i].Filename = strdup(it.current());
    p->ufs[i].Contents = p->sources[i].data();
    p->ufs[i].Length   = p->sources[i].length();
  }

  // let libclang do the actual parsing
  p->tu = clang_parseTranslationUnit(p->index, 0,
                                     argv, argc, p->ufs, numUnsavedFiles, 
                                     CXTranslationUnit_DetailedPreprocessingRecord);
  // free arguments
  for (int i=0;i<argc;++i)
  {
    free(argv[i]);
  }
  free(argv);

  if (p->tu)
  {
    // filter out any includes not found by the clang parser
    determineInputFilesInSameTu(filesInTranslationUnit);

    // show any warnings that the compiler produced
    for (uint i=0, n=clang_getNumDiagnostics(p->tu); i!=n; ++i) 
    {
      CXDiagnostic diag = clang_getDiagnostic(p->tu, i); 
      CXString string = clang_formatDiagnostic(diag,
          clang_defaultDiagnosticDisplayOptions()); 
      err("%s [clang]\n",clang_getCString(string));
      clang_disposeString(string);
      clang_disposeDiagnostic(diag);
    }

    // create a source range for the given file
    QFileInfo fi(fileName);
    CXFile f = clang_getFile(p->tu, fileName);
    CXSourceLocation fileBegin = clang_getLocationForOffset(p->tu, f, 0);
    CXSourceLocation fileEnd   = clang_getLocationForOffset(p->tu, f, p->ufs[0].Length);
    CXSourceRange    fileRange = clang_getRange(fileBegin, fileEnd);

    // produce a token stream for the file
    clang_tokenize(p->tu,fileRange,&p->tokens,&p->numTokens);

    // produce cursors for each token in the stream
    p->cursors=new CXCursor[p->numTokens];
    clang_annotateTokens(p->tu,p->tokens,p->numTokens,p->cursors);
  }
  else
  {
    p->tokens    = 0;
    p->numTokens = 0;
    p->cursors   = 0;
    err("clang: Failed to parse translation unit %s\n",fileName);
  }
}