Esempio n. 1
0
static char *
format_size(uint64_t size)
{
	char *s = format_human_readable_size(size);
	reformat(&s, "%11s", s);
	return s;
}
Esempio n. 2
0
//------------------------------------------------------------------------------
AQTest::AQTest(unsigned int formatOptions)
    : m_formatOptions(formatOptions)
    , m_shmStartGuardSize(SHM_GUARD_SIZE)
    , m_shmSize(SHM_SIZE + ((formatOptions & AQ::OPTION_CRC32) ? SHM_CRC32_OVERHEAD_SIZE : 0)
                         + ((formatOptions & (AQ::OPTION_LINK_IDENTIFIER | AQ::OPTION_EXTENDABLE)) ? SHM_LINK_IDENTIFIER_OVERHEAD_SIZE : 0))
    , m_shmEndGuardSize(SHM_GUARD_SIZE + SHM_SIZE + SHM_CRC32_OVERHEAD_SIZE + SHM_LINK_IDENTIFIER_OVERHEAD_SIZE - m_shmSize)
    , m_sm(&m_shm[SHM_GUARD_SIZE], m_shmSize)
    , ctrl((aq::CtrlOverlay *)&m_shm[SHM_GUARD_SIZE])
    , reader(m_sm, m_tm.createBuffer("rdr"))
    , writer(m_sm, m_tm.createBuffer("wrt"))
    , trace(m_tm.createBuffer("tst"))

{
    // Install the guards.
    memset(m_shm, SHM_GUARD_BYTE, m_shmStartGuardSize);
    memset(&m_shm[m_shmStartGuardSize + m_shmSize], SHM_GUARD_BYTE, m_shmEndGuardSize);

    // Fill the rest with random data.
    srand(7);
    for (size_t i = m_shmStartGuardSize; i < m_shmStartGuardSize + m_shmSize; ++i)
    {
        m_shm[i] = 'A' + rand() % 26;
    }

    // Create the random data array.
    for (size_t i = 0; i < sizeof(m_data); ++i)
    {
        m_data[i] = 'A' + rand() % 26;
    }

    reformat();
}
Esempio n. 3
0
/*
** 'read_bbcfile' reads a tokenised Acorn Basic file. It converts the
** file to this this interpreter's format, saving it in the Basic
** workspace at the address given by 'base'. It returns the number
** of bytes occupied by the loaded file.
** On entry, the 'carriage return' at the start of the file has been
** read and the file pointer is pointing at the first byte of the
** line number of the first line
*/
static int32 read_bbcfile(FILE *bbcfile, byte *base, byte *limit) {
  int length, count;
  byte line[INPUTLEN], *filebase;
  byte tokenline[MAXSTATELEN];
  basicvars.linecount = 0;	/* Number of line being read from file */
  filebase = base;
  do {
    line[0] = fgetc(bbcfile);	/* High order byte of line number */
    if (line[0]==ACORN_ENDMARK) break;	/* Found 0xFF at end of file so end */
    line[1] = fgetc(bbcfile);	/* Low order byte of line number */
    line[2] = length = fgetc(bbcfile);	/* Line length */
    count = fread(&line[3], sizeof(byte), length - 3, bbcfile);
    if (count != length - 3) {	/* Incorrect number of bytes read */
      fclose(bbcfile);
      error(ERR_READFAIL, basicvars.filename);
    }
    basicvars.linecount++;
    length = reformat(line, tokenline);
    if (length > 0) {	/* Line length is not zero so include line */
      if (base + length >= limit) {
        fclose(bbcfile);
        error(ERR_NOROOM);
      }
      memmove(base, tokenline, length);
      base+=length;
    }
  } while (!feof(bbcfile));
  fclose(bbcfile);
  basicvars.linecount = 0;
  if (base + ENDMARKSIZE >= limit) error(ERR_NOROOM);
  mark_end(base);
  return ALIGN(base - filebase + ENDMARKSIZE);
}
Esempio n. 4
0
static int eep0018_control(ErlDrvData drv_data,
                           unsigned int command,
                           char* buf,
                           int len,
                           char **rbuf,
                           int rlen)
{
    ErlDrvPort port = (ErlDrvPort)drv_data;

    switch(command)
    {
        case 0:
            term_to_json(port, buf, len);
            break;
        case 1:
            json_to_term(port, buf, len);
            break;
        case 2:
            reformat(port, buf, len);
            break;
    }

    *rbuf = 0;
    return 0;
}
Esempio n. 5
0
		int MiniConsole::dump()
		{
			/*
			 * We dump on screen the textual console contents.
			 * We care about user set variables.
			 * */
			int co=getGlobalIntVariable(FIM_VID_CONSOLE_LINE_OFFSET);
			int lw=getGlobalIntVariable(FIM_VID_CONSOLE_LINE_WIDTH );
			int ls=getGlobalIntVariable(FIM_VID_CONSOLE_ROWS       );
			setGlobalVariable(FIM_VID_CONSOLE_BUFFER_TOTAL,bsize);
			setGlobalVariable(FIM_VID_CONSOLE_BUFFER_FREE,(int)bsize-(int)(bp-buffer));
			setGlobalVariable(FIM_VID_CONSOLE_BUFFER_USED,(int)(bp-buffer));
			// we eventually update internal variables now
			setRows(ls);
			if( lw > 0 && lw!=lwidth ) reformat(lw);
			if(co>=0)
			{
				scroll=scroll%(rows+1);
				if(scroll>0)
					return do_dump((cline-rows+1-co)>=0?(cline-(rows-scroll)+1-co):0,cline-co);
				else
					return do_dump((cline-rows+1-co)>=0?(cline-rows+1-co):0,cline-co);
			}
			else
				return do_dump(-co-1,cline);
			return -1;
		}
Esempio n. 6
0
/**
 * Method that reades server's congiguration file
 * to set up threads and etc.
 *
 *
 */
void readConfig() {
	const char *options[] = { "THREADS", "PORT" };
	char *found, *token, *pos, *last;
	char buffer[BUFSIZ], tempchar;
	int fd = open(CONFIG, O_RDONLY), n = BUFSIZ - 1, loc = -1, i, ends = 0, c,
			value, info = 0;
	if (fd < 0)
		return;
	while (n == BUFSIZ - 1) {
		n = read(fd, buffer, BUFSIZ - 1);
		c = reformat(buffer, n);
		last = &buffer[c];
		for (i = 0; i < 2; i++) {
			pos = strstr(buffer, options[i]);
			if (pos != NULL ) {
				pos += strlen(options[i]) + 1;
				ends = 0;
				while (&pos[ends] != last && pos[ends] != '\n') {
					ends++;
				}
				tempchar = pos[ends];
				pos[ends] = '\0';
				value = atoi(pos);
				pos[ends] = tempchar;
				if (i == 0)
					threads = value;
				else
					port = value;
			}
		}
	}
}
Esempio n. 7
0
// Returns true on error.
static bool format(std::string FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  if (Code->getBufferSize() == 0)
    return true; // Empty files are formatted correctly.
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  std::vector<CharSourceRange> Ranges;
  if (fillRanges(Sources, ID, Code.get(), Ranges))
    return true;

  FormatStyle FormatStyle = getStyle(Style, FileName);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources,
            getFormattingLangOpts(FormatStyle.Standard));
  tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return false; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::sys::fs::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return true;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      if (Cursor.getNumOccurrences() != 0)
        outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
                                          Replaces, Cursor) << " }\n";
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
Esempio n. 8
0
void SpellHighlighter::slotMisspelling(const QString &word)
{
    bool *state = m_words.find(word);
    if (state)
        m_words.remove(word);
    m_words.insert(word, &WORD_BAD);
    m_bDirty = true;
    QTimer::singleShot(300, this, SLOT(reformat()));
}
BOOL CDataListSummary_dlg::OnInitDialog() 
{
  summary_fmt.set();
  reformat();

  CDialog::OnInitDialog();

  return TRUE;
}
Esempio n. 10
0
void CDataListSummary_dlg::OnFormat()
{
  CLocationFmt_dlg dlg(this,summary_fmt);
  if (dlg.DoModal()==IDOK) {
    summary_fmt.set();
    reformat();
    UpdateData(FALSE);
  }
}
Esempio n. 11
0
size_t strftime(char* str, size_t count, const std::string& format,
	const std::tm* time)
{
	bool ampm_supported = locale_supports_ampm(time);
	const std::string f = reformat(format, time, time_locale_correct(),
		ampm_supported);

	return std::strftime(str, count, f.c_str(), time);
}
Esempio n. 12
0
void CMapInfo_dlg::OnFormat()
{
  CLocationFmt_dlg dlg(this,info_fmt);
  if (dlg.DoModal()==IDOK) {
    info_fmt.set();
    reformat();
    UpdateData(FALSE);
  }
}
Esempio n. 13
0
 static std::string format(llvm::StringRef Code, unsigned Offset,
                           unsigned Length, const FormatStyle &Style) {
   DEBUG(llvm::errs() << "---\n");
   DEBUG(llvm::errs() << Code << "\n\n");
   std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
   tooling::Replacements Replaces = reformat(Style, Code, Ranges);
   std::string Result = applyAllReplacements(Code, Replaces);
   EXPECT_NE("", Result);
   DEBUG(llvm::errs() << "\n" << Result << "\n\n");
   return Result;
 }
Esempio n. 14
0
 static std::string format(llvm::StringRef Code, unsigned Offset,
                           unsigned Length, const FormatStyle &Style) {
   LLVM_DEBUG(llvm::errs() << "---\n");
   LLVM_DEBUG(llvm::errs() << Code << "\n\n");
   std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
   tooling::Replacements Replaces = reformat(Style, Code, Ranges);
   auto Result = applyAllReplacements(Code, Replaces);
   EXPECT_TRUE(static_cast<bool>(Result));
   LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
   return *Result;
 }
Esempio n. 15
0
void SpellHighlighter::slotMisspelling(const QString &word)
{
	MAP_BOOL::iterator it = m_words.find(my_string(word.utf8()));
    if (it == m_words.end()){
		m_words.insert(MAP_BOOL::value_type(my_string(word.utf8()), false));
	}else{
		if (!(*it).second)
			return;
		(*it).second = false;
	}
    m_bDirty = true;
    QTimer::singleShot(300, this, SLOT(reformat()));
}
Esempio n. 16
0
// Returns true on error.
static bool format(StringRef FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  std::unique_ptr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  if (Code->getBufferSize() == 0)
    return false; // Empty files are formatted correctly.
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  std::vector<CharSourceRange> Ranges;
  if (fillRanges(Sources, ID, Code.get(), Ranges))
    return true;

  FormatStyle FormatStyle = getStyle(
      Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources,
            getFormattingLangOpts(FormatStyle.Standard));
  tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>";
      outputReplacementXML(I->getReplacementText());
      llvm::outs() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Rewrite.overwriteChangedFiles())
        return true;
    } else {
      if (Cursor.getNumOccurrences() != 0)
        outs() << "{ \"Cursor\": "
               << tooling::shiftedCodePosition(Replaces, Cursor) << " }\n";
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
Esempio n. 17
0
/*!
  Constructs a status bar with just a size grip.
  \sa setSizeGripEnabled()
*/
QStatusBar::QStatusBar( QWidget * parent, const char *name )
    : QWidget( parent, name )
{
    d = new QStatusBarPrivate;
    d->items.setAutoDelete( TRUE );
    d->box = 0;
    d->timer = 0;

#ifndef QT_NO_SIZEGRIP
    d->resizer = 0;
    setSizeGripEnabled(TRUE); // causes reformat()
#else
    reformat();
#endif
}
Esempio n. 18
0
//  setSlotExampleFormatText() --
bool NumericReadout::setSlotExampleFormatText(const base::String* const seftobj)
{
   bool ok = true;
   if (seftobj != nullptr) {
      if (width() == 0) width(seftobj->len());
      reformat(*seftobj);
   }
   else {
      if (isMessageEnabled(MSG_ERROR)) {
         std::cerr << "NumericReadout::setExampleFormatText: \"format\" must be a string!" << std::endl;
      }
      ok = false;
   }
   return ok;
}
Esempio n. 19
0
void
outcmd(int ch, int count)
{
    struct instruction * n;

    /* I need to count 'print' commands for the java functions */
    if (ch == '"') { add_cstring(get_string()); return; }

    n = node_calloc();
    n->ch = ch;
    n->count = count;
    n->icount = ++icount;
    n->prev = last;
    if (!last) {
        pgm = n;
    } else {
        last->next = n;
    }
    last = n;

    if (n->ch == '[') {
        n->loop = jmpstack; jmpstack = n;
    } else if (n->ch == ']') {
        n->loop = jmpstack; jmpstack = jmpstack->loop; n->loop->loop = n;
    } else if (ch == '"')
        n->cstr = strdup(get_string());

    if (ch != '~') return;

    last->ch = '}';	/* Make the end an end function */

    if (icount > MAXINSTR)
	reformat();

    for(n=pgm; n; n=n->next)
	loutcmd(n->ch, n->count, n);

    loutcmd('}', 0,0);	/* End of the class */

    while(pgm) {
        n = pgm;
        pgm = pgm->next;
        if (n->cstr)
            free(n->cstr);
        memset(n, '\0', sizeof*n);
        free(n);
    }
}
Esempio n. 20
0
void KStatusBar::changeItem( const QString& text, int id )
{
    QLabel *label = d->items[id];
    KSqueezedTextLabel *squeezed = qobject_cast<KSqueezedTextLabel*>( label );

    if ( squeezed ) {
        squeezed->setText( text );
    } else if ( label ) {
        label->setText( text );
        if ( label->minimumWidth () != label->maximumWidth () ) {
            reformat();
        }
    } else {
        kDebug() << "KStatusBar::changeItem: bad item id: " << id;
    }
}
Esempio n. 21
0
 std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length,
                    const FormatStyle &Style) {
   RewriterTestContext Context;
   FileID ID = Context.createInMemoryFile("input.cc", Code);
   SourceLocation Start =
       Context.Sources.getLocForStartOfFile(ID).getLocWithOffset(Offset);
   std::vector<CharSourceRange> Ranges(
       1,
       CharSourceRange::getCharRange(Start, Start.getLocWithOffset(Length)));
   LangOptions LangOpts;
   LangOpts.CPlusPlus = 1;
   Lexer Lex(ID, Context.Sources.getBuffer(ID), Context.Sources, LangOpts);
   tooling::Replacements Replace =
       reformat(Style, Lex, Context.Sources, Ranges);
   EXPECT_TRUE(applyAllReplacements(Replace, Context.Rewrite));
   return Context.getRewrittenText(ID);
 }
Esempio n. 22
0
const char *_Getzone(void)
	{	/* get time zone information */
	const char *s;

	if (tzone)
		;
	else if ((s = getenv("TIMEZONE")) != NULL)
		{	/* copy desired format */
		if ((tzone = (char *)malloc(strlen(s) + 1)) != NULL)
			strcpy(tzone, s);
		}
	else if ((s = getenv("TZ")) != NULL)
		tzone = reformat(s);
	if (tzone == NULL)
		tzone = (char *)defzone;
	return (tzone);
	}
Esempio n. 23
0
int
mysprintf(char *s, const char *fmt, ...)
{
  va_list ap;
  char *fmt2;
  int nchar;

  va_start(ap, fmt);
  fmt2 = reformat(fmt);
  if (fmt2) {
    nchar = vsprintf(s, fmt2, ap);
    free(fmt2);
  } else {  /* il y a eu une erreur */
    vsprintf(s, fmt, ap);
    nchar = -1;
  }
  return nchar;
}
Esempio n. 24
0
/*!
  Enables or disables the QSizeGrip in the bottom right of the status bar.
  By default, the size grip is enabled.

  \sa isSizeGripEnabled()
*/
void QStatusBar::setSizeGripEnabled(bool enabled)
{
#ifndef QT_NO_SIZEGRIP
    if ( !enabled != !d->resizer ) {
	if ( enabled ) {
	    d->resizer = new QSizeGrip( this, "QStatusBar::resizer" );
	} else {
	    delete d->resizer;
	    d->resizer = 0;
	}
	reformat();
	if ( d->resizer && isVisible() )
	    d->resizer->show();
    }
#else
    Q_UNUSED(enabled);
#endif
}
Esempio n. 25
0
BOOL CMapInfo_dlg::OnInitDialog()
{
  m_file=name;
  if (modified) m_file+=" *";

  m_alloc_area=alloc.area;
  m_alloc_gp=alloc.ngp;
  m_defined_area=defined.area;
  m_defined_gp=defined.ngp;

  info_fmt.set();
  reformat();

  CDialog::OnInitDialog();

  return TRUE;  // return TRUE unless you set the focus to a control
	        // EXCEPTION: OCX Property Pages should return FALSE
}
Esempio n. 26
0
void QStatusBar::removeWidget( QWidget* widget )
{
    if ( !widget )
	return;
    bool found = FALSE;
    QStatusBarPrivate::SBItem* item = d->items.first();
    while ( item && !found ) {
	if ( item->w == widget ) {
	    d->items.remove();
	    found = TRUE;
	}
	item = d->items.next();
    }

    if ( found )
	reformat();
#if defined(DEBUG)
    else
	qDebug( "QStatusBar::removeWidget(): Widget not found." );
#endif
}
Esempio n. 27
0
void QStatusBar::addWidget( QWidget * widget, int stretch, bool permanent )
{
    if ( !widget ) {
#if defined(CHECK_NULL)
	qWarning( "QStatusBar::addWidget(): Cannot add null widget" );
#endif
	return;
    }

    QStatusBarPrivate::SBItem* item
	= new QStatusBarPrivate::SBItem( widget, stretch, permanent );

    d->items.last();
    while( !permanent && d->items.current() && d->items.current()->p )
	d->items.prev();

    d->items.insert( d->items.at() >= 0 ? d->items.at()+1 : 0, item );

    if ( !d->tempItem.isEmpty() && !permanent )
	widget->hide();

    reformat();
}
Esempio n. 28
0
int
myprintf(const char *fmt, ...)
{
  va_list ap;
  char *fmt2;
  int nchar;

  if (isatty(STDOUT_FILENO)) {
    myprintf_enable_color();
  } else {
    myprintf_disable_ansi_codes();
  }
  va_start(ap, fmt);
  fmt2 = reformat(fmt);
  if (fmt2) {
    nchar = vprintf(fmt2, ap);
    free(fmt2);
  } else {  /* il y a eu une erreur */
    vprintf(fmt, ap);
    nchar = -1;
  }
  return nchar;
}
Esempio n. 29
0
bool
conf_print_items(struct conf *conf,
                 void (*printer)(const char *descr, const char *origin,
                                 void *context),
                 void *context)
{
	char *s = x_strdup("");
	char *s2;

	reformat(&s, "base_dir = %s", conf->base_dir);
	printer(s, conf->item_origins[find_conf("base_dir")->number], context);

	reformat(&s, "cache_dir = %s", conf->cache_dir);
	printer(s, conf->item_origins[find_conf("cache_dir")->number], context);

	reformat(&s, "cache_dir_levels = %u", conf->cache_dir_levels);
	printer(s, conf->item_origins[find_conf("cache_dir_levels")->number],
	        context);

	reformat(&s, "compiler = %s", conf->compiler);
	printer(s, conf->item_origins[find_conf("compiler")->number], context);

	reformat(&s, "compiler_check = %s", conf->compiler_check);
	printer(s, conf->item_origins[find_conf("compiler_check")->number], context);

	reformat(&s, "compression = %s", conf->compression ? "true" : "false");
	printer(s, conf->item_origins[find_conf("compression")->number], context);

	reformat(&s, "compression_level = %u", conf->compression_level);
	printer(s, conf->item_origins[find_conf("compression_level")->number],
	        context);

	reformat(&s, "cpp_extension = %s", conf->cpp_extension);
	printer(s, conf->item_origins[find_conf("cpp_extension")->number], context);

	reformat(&s, "direct_mode = %s", conf->direct_mode ? "true" : "false");
	printer(s, conf->item_origins[find_conf("direct_mode")->number], context);

	reformat(&s, "disable = %s", conf->disable ? "true" : "false");
	printer(s, conf->item_origins[find_conf("disable")->number], context);

	reformat(&s, "extra_files_to_hash = %s", conf->extra_files_to_hash);
	printer(s, conf->item_origins[find_conf("extra_files_to_hash")->number],
	        context);

	reformat(&s, "hard_link = %s", conf->hard_link ? "true" : "false");
	printer(s, conf->item_origins[find_conf("hard_link")->number], context);

	reformat(&s, "hash_dir = %s", conf->hash_dir ? "true" : "false");
	printer(s, conf->item_origins[find_conf("hash_dir")->number], context);

	reformat(&s, "log_file = %s", conf->log_file);
	printer(s, conf->item_origins[find_conf("log_file")->number], context);

	reformat(&s, "max_files = %u", conf->max_files);
	printer(s, conf->item_origins[find_conf("max_files")->number], context);

	s2 = format_parsable_size_with_suffix(conf->max_size);
	reformat(&s, "max_size = %s", s2);
	printer(s, conf->item_origins[find_conf("max_size")->number], context);
	free(s2);

	reformat(&s, "path = %s", conf->path);
	printer(s, conf->item_origins[find_conf("path")->number], context);

	reformat(&s, "prefix_command = %s", conf->prefix_command);
	printer(s, conf->item_origins[find_conf("prefix_command")->number], context);

	reformat(&s, "read_only = %s", conf->read_only ? "true" : "false");
	printer(s, conf->item_origins[find_conf("read_only")->number], context);

	reformat(&s, "recache = %s", conf->recache ? "true" : "false");
	printer(s, conf->item_origins[find_conf("recache")->number], context);

	reformat(&s, "run_second_cpp = %s", conf->run_second_cpp ? "true" : "false");
	printer(s, conf->item_origins[find_conf("run_second_cpp")->number], context);

	reformat(&s, "sloppiness = ");
	if (conf->sloppiness & SLOPPY_FILE_MACRO) {
		reformat(&s, "%sfile_macro, ", s);
	}
	if (conf->sloppiness & SLOPPY_INCLUDE_FILE_MTIME) {
		reformat(&s, "%sinclude_file_mtime, ", s);
	}
	if (conf->sloppiness & SLOPPY_INCLUDE_FILE_CTIME) {
		reformat(&s, "%sinclude_file_ctime, ", s);
	}
	if (conf->sloppiness & SLOPPY_TIME_MACROS) {
		reformat(&s, "%stime_macros, ", s);
	}
	if (conf->sloppiness & SLOPPY_FILE_STAT_MATCHES) {
		reformat(&s, "%sfile_stat_matches, ", s);
	}
	if (conf->sloppiness) {
		/* Strip last ", ". */
		s[strlen(s) - 2] = '\0';
	}
	printer(s, conf->item_origins[find_conf("sloppiness")->number], context);

	reformat(&s, "stats = %s", conf->stats ? "true" : "false");
	printer(s, conf->item_origins[find_conf("stats")->number], context);

	reformat(&s, "temporary_dir = %s", conf->temporary_dir);
	printer(s, conf->item_origins[find_conf("temporary_dir")->number], context);

	if (conf->umask == UINT_MAX) {
		reformat(&s, "umask = ");
	} else {
		reformat(&s, "umask = %03o", conf->umask);
	}
	printer(s, conf->item_origins[find_conf("umask")->number], context);

	reformat(&s, "unify = %s", conf->unify ? "true" : "false");
	printer(s, conf->item_origins[find_conf("unify")->number], context);

	free(s);
	return true;
}
Esempio n. 30
0
// Returns true on error.
static bool format(std::string FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
  if (Offsets.empty())
    Offsets.push_back(0);
  if (Offsets.size() != Lengths.size() &&
      !(Offsets.size() == 1 && Lengths.empty())) {
    llvm::errs()
        << "error: number of -offset and -length arguments must match.\n";
    return true;
  }
  std::vector<CharSourceRange> Ranges;
  for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
    if (Offsets[i] >= Code->getBufferSize()) {
      llvm::errs() << "error: offset " << Offsets[i]
                   << " is outside the file\n";
      return true;
    }
    SourceLocation Start =
        Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
    SourceLocation End;
    if (i < Lengths.size()) {
      if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
        llvm::errs() << "error: invalid length " << Lengths[i]
                     << ", offset + length (" << Offsets[i] + Lengths[i]
                     << ") is outside the file.\n";
        return true;
      }
      End = Start.getLocWithOffset(Lengths[i]);
    } else {
      End = Sources.getLocForEndOfFile(ID);
    }
    Ranges.push_back(CharSourceRange::getCharRange(Start, End));
  }
  tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return false; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::raw_fd_ostream::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return true;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}