Ejemplo n.º 1
0
void pdivuw() {
  enum { _end1, _end2 };

#define macro(_idx, _endlbl)                          \
  mov32_reg_mem(_ecx, _GPR_D(_rt, _idx));             \
  tst32_reg_reg(_ecx, _ecx);                          \
  jz(_endlbl);                                        \
  xor32_reg_reg(_edx, _edx);                          \
  mov32_eax_mem(_GPR_D(_rs, _idx));                   \
  div_reg(_ecx);                                      \
  mov32_reg_reg(_ecx, _edx);                          \
  cdq();                                              \
  mov32_mem_reg((u32)&g_cpu->m_lo.d[_idx], _eax);     \
  mov32_mem_reg((u32)&g_cpu->m_lo.d[_idx + 1], _edx); \
  mov32_reg_reg(_eax, _ecx);                          \
  cdq();                                              \
  mov32_mem_reg((u32)&g_cpu->m_hi.d[_idx], _eax);     \
  mov32_mem_reg((u32)&g_cpu->m_hi.d[_idx + 1], _edx);

  macro(0, _end1);  // 63-0
LABEL_DEF(_end1);
  macro(2, _end2);  // 127-64
LABEL_DEF(_end2);

#undef macro
}
Ejemplo n.º 2
0
//
// SLOT
// Effect: change the macro expansion referenced by a control entry to the named variable.
//
void
QEpicsAcqLocal::defVariable(  const QString &varName, const QString &scan, const QString &type, int varIndex)
{
	acqScan_t *sc;
	char **nameAddr = NULL;
	if( master == NULL)
		return;


	sc = lookup_acqScan( scan.toAscii().constData(), master);
	if( sc == NULL)
		return;
	if( type == "first" || type == "start" )
		nameAddr = &sc->acqControlList[varIndex].startMacro;
	else if( type == "delta")
		nameAddr = &sc->acqControlList[varIndex].deltaMacro;
	else if( type == "final" || type == "last" || type == "end" )
		nameAddr = &sc->acqControlList[varIndex].finalMacro;
	if(nameAddr)
	{
		QString macro( "$(" + varName + ")");
		if( *nameAddr)
			free(*nameAddr);
		*nameAddr = strdup(macro.toAscii().data() );
	}

}
Ejemplo n.º 3
0
    void PathgridMode::dragCompleted(const QPoint& pos)
    {
        if (mDragMode == DragMode_Move)
        {
            std::vector<osg::ref_ptr<TagBase> > selection = getWorldspaceWidget().getSelection (Mask_Pathgrid);
            for (std::vector<osg::ref_ptr<TagBase> >::iterator it = selection.begin(); it != selection.end(); ++it)
            {
                if (PathgridTag* tag = dynamic_cast<PathgridTag*>(it->get()))
                {
                    QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
                    QString description = "Move pathgrid node(s)";

                    CSMWorld::CommandMacro macro(undoStack, description);
                    tag->getPathgrid()->applyPosition(macro);
                }
            }
        }
        else if (mDragMode == DragMode_Edge)
        {
            WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());

            if (hit.tag)
            {
                if (PathgridTag* tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
                {
                    if (tag->getPathgrid()->getId() == mEdgeId)
                    {
                        unsigned short toNode = SceneUtil::getPathgridNode(static_cast<unsigned short>(hit.index0));

                        QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
                        QString description = "Add edge between nodes";

                        CSMWorld::CommandMacro macro(undoStack, description);
                        tag->getPathgrid()->applyEdge(macro, mFromNode, toNode);
                    }
                }
            }

            mEdgeId.clear();
            mFromNode = 0;
        }

        mDragMode = DragMode_None;
        getWorldspaceWidget().reset(Mask_Pathgrid);
    }
Ejemplo n.º 4
0
void pmultuw() {
#define macro(_idx)                                   \
  mov32_eax_mem(_GPR_D(_rs, _idx));                   \
  mul_mem(_GPR_D(_rt, _idx));                         \
  mov32_reg_reg(_ecx, _edx);                          \
  cdq();                                              \
  mov32_mem_reg((u32)&g_cpu->m_lo.d[_idx], _eax);     \
  mov32_mem_reg((u32)&g_cpu->m_lo.d[_idx + 1], _edx); \
  if (_rd) mov32_mem_reg(_GPR_D(_rd, _idx), _eax);    \
  mov32_reg_reg(_eax, _ecx);                          \
  cdq();                                              \
  mov32_mem_reg((u32)&g_cpu->m_hi.d[_idx], _eax);     \
  mov32_mem_reg((u32)&g_cpu->m_hi.d[_idx + 1], _edx); \
  if (_rd) mov32_mem_reg(_GPR_D(_rd, _idx + 1), _eax);

  macro(0);  // 63-0
  macro(2);  // 127-64

#undef macro
}
Ejemplo n.º 5
0
void CSVWorld::NestedTable::removeRowActionTriggered()
{
    CSMWorld::CommandMacro macro(mDocument.getUndoStack(),
        selectionModel()->selectedRows().size() > 1 ? tr("Remove rows") : "");

    // Remove rows in reverse order
    for (int i = selectionModel()->selectedRows().size() - 1; i >= 0; --i)
    {
        macro.push(new CSMWorld::DeleteNestedCommand(*(mModel->model()), mModel->getParentId(),
            selectionModel()->selectedRows()[i].row(), mModel->getParentColumn()));
    }
}
Ejemplo n.º 6
0
QVector<rpp::pp_macro*> computeGccStandardMacros(bool withStdCpp0x = true)
{
    QVector<rpp::pp_macro*> ret;
    //Get standard macros from gcc
    KProcess proc;
    proc.setOutputChannelMode(KProcess::MergedChannels);

    // The output of the following gcc commands is several line in the format:
    // "#define MACRO [definition]", where definition may or may not be present.
    // Parsing each line sequentially, we can easily build the macro set.
    proc << "gcc";
    if (withStdCpp0x) {
        // see also: https://bugs.kde.org/show_bug.cgi?id=298252
        proc << "-std=c++0x";
    }
    proc << "-xc++" << "-E" << "-dM" <<NULL_DEVICE;

    if (proc.execute(5000) == 0) {
        QString line;
        while (proc.canReadLine()) {
            QByteArray buff = proc.readLine();
            if (!buff.isEmpty()) {
                line = buff;
                if (line.startsWith("#define ")) {
                    line = line.right(line.length() - 8).trimmed();
                    int pos = line.indexOf(' ');
                    
                    ret.append(new rpp::pp_macro);
                    
                    rpp::pp_macro& macro(*ret.back());
                    if (pos != -1) {
                        macro.name = IndexedString( line.left(pos) );
                        macro.setDefinitionText( line.right(line.length() - pos - 1).toUtf8() );
                    } else {
                        macro.name = IndexedString( line );
                    }
                }
            }
        }
    } else if (withStdCpp0x) {
        // fallback to macro computation without -std=c++0x arg for old gcc versions
        return computeGccStandardMacros(false);
    } else {
        kDebug(9007) <<"Unable to read standard c++ macro definitions from gcc:" <<QString(proc.readAll()) ;
    }
    return ret;
}
Ejemplo n.º 7
0
void LTRTextBuilder::updateLTR_TokenFromVertex(
    const LinguisticGraphVertex& vertex,
    const LinguisticGraph& graph,
    LTR_Token* tokenRep,
    uint64_t offset) const {

    // get data from the result of the linguistic analysis
    Token* fullToken = get(vertex_token, graph, vertex);
    MorphoSyntacticData* data = get(vertex_data, graph, vertex);
    const FsaStringsPool& sp = (Common::MediaticData::MediaticData::single().stringsPool(m_language));

    sort(data->begin(),data->end(),ltNormProperty(m_macroAccessor));

    StringsPoolIndex norm(0),lastNorm(0);
    LinguisticCode macro(0),lastMacro(0);
    for (MorphoSyntacticData::const_iterator elemItr=data->begin();
         elemItr!=data->end(); elemItr++) {
        norm = elemItr->normalizedForm;
        macro = m_macroAccessor->readValue(elemItr->properties);
        if (norm == lastNorm && macro == lastMacro) {
            continue;
        }
        else {
            lastNorm=norm;
            lastMacro=macro;
            LimaString normStr= sp[norm];
            // test if the same word was not already met at this position
            bool selectionFlag = true;
            LTR_Token::const_iterator itTok = tokenRep->begin();
            while (selectionFlag && (itTok != tokenRep->end())) {
                selectionFlag = (itTok->first->getLemma() != normStr) ||
                                (itTok->first->getCategory() != macro);
                itTok ++;
            }
            if (selectionFlag) {
                // test if the current token is a plain word
                bool plainWordFlag =
                    this->isWordToSelect(normStr, macro,m_microAccessor->readValue(elemItr->properties));
                BoWToken* bowToken = new BoWToken(normStr,macro,
                                                  fullToken->position() + offset,
                                                  fullToken->length());
                bowToken->setInflectedForm(fullToken->stringForm());
                tokenRep->push_back(make_pair(bowToken, plainWordFlag));
            }
        }
    }
}
Ejemplo n.º 8
0
branch()
{
	register char	c;
	register int	i;
	extern char	getch();

#	ifdef xMTR2
	if (tTf(16, -1))
		printf(">>branch: ");
#	endif

	/* see if conditional */
	while ((c = getch()) > 0)
		if (c != ' ' && c != '\t')
			break;
	if (c == '?')
	{
		/* got a conditional; evaluate it */
		Oneline = TRUE;
		macinit(&getch, 0, 0);
		i = expr();

		if (i <= 0)
		{
			/* no branch */
#			ifdef xMTR2
			if (tTf(16, 0))
				printf("no branch\n");
#			endif
			getfilename();
			return;
		}
	}
	else
	{
		Peekch = c;
	}

	/* get the target label */
	if (branchto(getfilename()) == 0)
		if (branchto(macro("{default}")) == 0)
		{
			Peekch = -1;
			printf("Cannot branch\n");
		}
	return;
}
Ejemplo n.º 9
0
    void PathgridMode::primaryEditPressed(const WorldspaceHitResult& hitResult)
    {
        if (CSMPrefs::get()["3D Scene Input"]["context-select"].isTrue() &&
            dynamic_cast<PathgridTag*>(hitResult.tag.get()))
        {
            primarySelectPressed(hitResult);
        }
        else if (Cell* cell = getWorldspaceWidget().getCell (hitResult.worldPos))
        {
            // Add node
            QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
            QString description = "Add node";

            CSMWorld::CommandMacro macro(undoStack, description);
            cell->getPathgrid()->applyPoint(macro, hitResult.worldPos);
        }
    }
Ejemplo n.º 10
0
extern QList<QSharedPointer<Macro> > loadFromFile(const QString &fileName)
{
    QList<QSharedPointer<Macro> > result;
    QFile f(fileName);
    if (f.open(QIODevice::ReadOnly|QIODevice::Text)) {
        QDomDocument doc;
        doc.setContent(&f);
        const QDomNodeList macros = doc.elementsByTagName("macro");
        for (int i=0; i<macros.count(); i++) {
            QSharedPointer<Macro> macro(new Macro());
            if (loadMacro(macros.at(i).toElement(), macro)) {
                result << macro;
            }
        }
        f.close();
    }
    return result;
}
static void changed_cb(GtkComboBox *combo, gpointer user_data) {
	RyostklconfigProDimnessSelector *dimness_selector = RYOSTKLCONFIG_PRO_DIMNESS_SELECTOR(combo);
	RyostklconfigProDimnessSelectorPrivate *priv = dimness_selector->priv;
	guint type;

	type = get_active_type(dimness_selector);

	switch (type) {
	case RYOS_LIGHT_DIMNESS_TYPE_MACRO:
		type = macro(dimness_selector);
		break;
	default:
		break;
	}

	priv->dimness_type = type;
	update(dimness_selector);
}
Ejemplo n.º 12
0
    void PathgridMode::secondaryEditPressed(const WorldspaceHitResult& hit)
    {
        if (hit.tag)
        {
            if (PathgridTag* tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
            {
                if (tag->getPathgrid()->isSelected())
                {
                    unsigned short node = SceneUtil::getPathgridNode(static_cast<unsigned short>(hit.index0));

                    QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
                    QString description = "Connect node to selected nodes";

                    CSMWorld::CommandMacro macro(undoStack, description);
                    tag->getPathgrid()->applyEdges(macro, node);
                }
            }
        }
    }
Ejemplo n.º 13
0
shell()
{
	register int	i;
	register char	*p;
	register char	*shellfile;
	char		*getfilename();
	char		*macro();

	shellfile = getfilename();
	if (*shellfile == 0)
		shellfile = 0;

	fclose(Qryiop);
	if ((Xwaitpid = fork()) == -1)
		syserr("shell: fork");
	if (Xwaitpid == 0)
	{
		setuid(getuid());
#		ifndef xB_UNIX
		setgid(getgid());
#		endif
		for (i = 3; i < MAXFILES; i++)
			close(i);
		p = macro("{shell}");
#		ifdef xMTR3
		tTfp(7, 0, "{shell} = '%o'\n", p);
#		endif
		if (p != 0)
		{
			execl(p, p, shellfile, Qbname, 0);
			printf("Cannot call %s; using /bin/sh\n", p);
		}
		execl("/bin/sh", "sh", shellfile, Qbname, 0);
		syserr("shell: exec");
	}

	if (Nodayfile >= 0)
		printf(">>shell\n");
	/* wait for shell to complete */
	xwait();
}
Ejemplo n.º 14
0
// Write out the config file for the whole application
int configAppSaveXml()
{
	if (bCmdOptUsed) {
		return 1;
	}

	char configName[MAX_PATH];
	createConfigName(configName);

	try {
		char tempStr[64] = "";

		// root
		ticpp::Document doc;
		ticpp::Declaration decl("1.0", "UTF-8", "");
		doc.LinkEndChild(&decl);

		ticpp::Element root("configuration");
		setAttr(root, "version", configVersion);
		ticpp::Comment comment("Don't edit this file manually unless you know what you're doing\n" \
					APP_TITLE " will restore default settings when this file is deleted");
		doc.LinkEndChild(&comment);
		doc.LinkEndChild(&root);

		// title
		sprintf(tempStr, "0x%06X", nBurnVer);
		addTextNode(root, "version", tempStr);

		// emulation
		ticpp::Element emulation("emulation");
		root.LinkEndChild(&emulation);
		setAttr(emulation, "asm-68k", bBurnUseASM68K);
		setAttr(emulation, "all-ram", bDrvSaveAll);

		// video
		ticpp::Element video("video");
		root.LinkEndChild(&video);

		ticpp::Element fullscreen("fullscreen");
		video.LinkEndChild(&fullscreen);
		setAttr(fullscreen, "width", nVidWidth);
		setAttr(fullscreen, "height", nVidHeight);
		setAttr(fullscreen, "depth", nVidDepth);
		setAttr(fullscreen, "refresh", nVidRefresh);

		ticpp::Element adjust("adjust");
		video.LinkEndChild(&adjust);
		setAttr(adjust, "rotate-vertical", nVidRotationAdjust);

		ticpp::Element screen_size("screen-size");
		video.LinkEndChild(&screen_size);
		setAttr(screen_size, "window", nWindowSize);

		ticpp::Element window_position("window-position");
		video.LinkEndChild(&window_position);
		setAttr(window_position, "x", nWindowPosX);
		setAttr(window_position, "y", nWindowPosY);

		ticpp::Element stretch("stretch");
		video.LinkEndChild(&stretch);
		setAttr(stretch, "full-stretch", bVidFullStretch);
		setAttr(stretch, "correct-aspect", bVidCorrectAspect);

		ticpp::Element color("color");
		video.LinkEndChild(&color);
		setAttr(color, "enable", bcolorAdjust);
		setAttr(color, "contrast", color_contrast);
		setAttr(color, "brightness", color_brightness);
		setAttr(color, "gamma", color_gamma);
		setAttr(color, "grayscale", color_grayscale);
		setAttr(color, "invert", color_invert);

		ticpp::Element vsync("vsync");
		video.LinkEndChild(&vsync);
		setAttr(vsync, "enable", bVidVSync);

		ticpp::Element triple_buffer("triple-buffer");
		video.LinkEndChild(&triple_buffer);
		setAttr(triple_buffer, "enable", bVidTripleBuffer);

		// video render
		ticpp::Element render("render");
		video.LinkEndChild(&render);

		ticpp::Element render_driver("render-driver");
		render.LinkEndChild(&render_driver);
		setAttr(render_driver, "driver", nVidSelect);
		setAttr(render_driver, "adapter", nVidAdapter);

		ticpp::Element filter("filter");
		render.LinkEndChild(&filter);
		setAttr(filter, "linear", vidFilterLinear);
		setAttr(filter, "use-pixelfilter", vidUseFilter);
		setAttr(filter, "pixel-filter", nVidFilter);

		ticpp::Element option("option");
		render.LinkEndChild(&option);
		setAttr(option, "force-16bit", bVidForce16bit);
		setAttr(option, "hardware-vertex", vidHardwareVertex);
		setAttr(option, "motion-blur", vidMotionBlur);
		setAttr(option, "projection", nVid3DProjection);
		setAttr(option, "angel", fVidScreenAngle);
		setAttr(option, "curvature", fVidScreenCurvature);
		setAttr(option, "dxmanager", nVidDXTextureManager);

		setAttr(option, "x-offset", nXOffset);
		setAttr(option, "y-offset", nYOffset);
		setAttr(option, "x-scale",  nXScale);
		setAttr(option, "y-scale",  nYScale);

		// video others
		ticpp::Element monitor("monitor");
		video.LinkEndChild(&monitor);
		setAttr(monitor, "auto-aspect", autoVidScrnAspect);
		setAttr(monitor, "aspect-x", nVidScrnAspectX);
		setAttr(monitor, "aspect-y", nVidScrnAspectY);

		ticpp::Element frame("frame");
		video.LinkEndChild(&frame);
		setAttr(frame, "auto-frameskip", autoFrameSkip);
		setAttr(frame, "force-60hz", bForce60Hz);

		// audio
		ticpp::Element audio("audio");
		root.LinkEndChild(&audio);
		addTextNode(audio, "sound", audSelect);

		ticpp::Element device("device");
		audio.LinkEndChild(&device);
		setAttr(device, "ds", dsDevice);
		setAttr(device, "xa2", xa2Device);
		setAttr(device, "oal", oalDevice);

		ticpp::Element audio_set("setting");
		audio.LinkEndChild(&audio_set);
		setAttr(audio_set, "rate", nAudSampleRate);
		setAttr(audio_set, "frame", nAudSegCount);
		setAttr(audio_set, "dsp", nAudDSPModule);
		setAttr(audio_set, "pcm-interp", nInterpolation);
		setAttr(audio_set, "fm-interp", nFMInterpolation);
		setAttr(audio_set, "stereo-upmix", audStereoUpmixing);

		// gui
		ticpp::Element gui("gui");
		root.LinkEndChild(&gui);
		addTextNode(gui, "language", szLanguage);
		//addTextNode(gui, "gamelist", szTransGamelistFile);

		ticpp::Element chat("chat-font");
		gui.LinkEndChild(&chat);
		setAttr(chat, "min-size", nMinChatFontSize);
		setAttr(chat, "max-size", nMaxChatFontSize);

		ticpp::Element menu("menu");
		gui.LinkEndChild(&menu);
		setAttr(menu, "modeless", bModelessMenu);
		setAttr(menu, "style", menuNewStyle);

		ticpp::Element gui_misc("gui-misc");
		gui.LinkEndChild(&gui_misc);
		setAttr(gui_misc, "on-top", bShowOnTop);
		setAttr(gui_misc, "auto-fullscreen", bFullscreenOnStart);
		setAttr(gui_misc, "lastRom", nLastRom);
		setAttr(gui_misc, "lastFilter", nLastFilter);

		setAttr(gui_misc, "hideChildren", HideChildren);
		setAttr(gui_misc, "showThreeFourPlayerOnly", ThreeOrFourPlayerOnly);
		setAttr(gui_misc, "arcadeJoyStickSettings", ArcadeJoystick);

		// gui load game dialog
		ticpp::Element gamelist("gamelist-dlg");
		gui.LinkEndChild(&gamelist);
		setAttr(gamelist, "options", nLoadMenuShowX);
		//setAttr(gamelist, "drivers", nLoadDriverShowX);
		//setAttr(gamelist, "sys-sel", nSystemSel);
		//setAttr(gamelist, "tab-sel", nTabSel);
		//addTextNode(gamelist, "user-filter", szUserFilterStr);

		// gui ips
		ticpp::Element ips("ips");
		gui.LinkEndChild(&ips);
		setAttr(ips, "language", nPatchLang);
		setAttr(ips, "dependancy", bEnforceDep);

		//ticpp::Element skin("skin");
		//gui.LinkEndChild(&skin);
		//setAttr(skin, "use-placeholder", bVidUsePlaceholder);
		//setAttr(skin, "random", nRandomSkin);
		//addTextNode(skin, NULL, szPlaceHolder);

		// preferences
		ticpp::Element preference("preferences");
		root.LinkEndChild(&preference);

		ticpp::Element settings("settings");
		preference.LinkEndChild(&settings);
		setAttr(settings, "always-processkey", bAlwaysProcessKey);
		setAttr(settings, "auto-pause", bAutoPause);
		//setAttr(settings, "avi-audio", nAviIntAudio);
		//setAttr(settings, "use-gdip", bUseGdip);
		ticpp::Element fastforward("fastforward");
		preference.LinkEndChild(&fastforward);
		setAttr(fastforward, "speed", nFastSpeed);
		ticpp::Element thread("thread");
		preference.LinkEndChild(&thread);
		setAttr(thread, "priority", nAppThreadPriority);
		ticpp::Element autofire("autofire");
		preference.LinkEndChild(&autofire);
		setAttr(autofire, "enable", nAutofireEnabled);
		setAttr(autofire, "default-delay", autofireDefaultDelay);
		ticpp::Element macro("macro");
		preference.LinkEndChild(&macro);
		setAttr(macro, "enable", nInputMacroEnabled);

		// pref misc
		ticpp::Element pref_misc("misc");
		preference.LinkEndChild(&pref_misc);
		setAttr(pref_misc, "effect", nShowEffect);

		ticpp::Element controls("controls");
		preference.LinkEndChild(&controls);
		for (int i = 0; i < 4; i++) {
			sprintf(tempStr, "default%d", i);
			addTextNode(controls, tempStr, szPlayerDefaultIni[i]);
		}

		// paths
		ticpp::Element paths("paths");
		root.LinkEndChild(&paths);

		ticpp::Element rom_path("rom");
		paths.LinkEndChild(&rom_path);
		for (int i = 0; i < DIRS_MAX; i++) {
			addTextNode(rom_path, "path", szAppRomPaths[i]);
		}

		ticpp::Element misc_path("misc");
		paths.LinkEndChild(&misc_path);
		for (int i = PATH_PREVIEW; i < PATH_SUM; i++) {
			sprintf(tempStr, "path%d", i);
			addTextNode(misc_path, tempStr, szMiscPaths[i]);
		}

		// hotkeys
		ticpp::Element hotkeys("hotkeys");
		root.LinkEndChild(&hotkeys);

		/*for (int i = 0; !lastCustomKey(customKeys[i]); i++) {
			CustomKey& customkey = customKeys[i];

			ticpp::Element key(customkey.config_code);
			hotkeys.LinkEndChild(&key);
			setAttr(key, "key", customkey.key);
			setAttr(key, "mod", customkey.keymod);
		}*/

		// save file
		doc.SaveFile(configName, TIXML_ENCODING_UTF8);
	}
	catch (ticpp::Exception& ex) {
		return 1;
	}

	return 0;
}
Ejemplo n.º 15
0
bool Bass::executeInstruction(Instruction& i) {
  activeInstruction = &i;
  string s = i.statement;
  evaluateDefines(s);

  if(s.match("macro ?*(*) {") || s.match("global macro ?*(*) {")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    s.trim<1>("macro ", ") {");
    lstring p = s.split<1>("(");
    bool scoped = p(0).beginsWith("scope ");
    p(0).ltrim<1>("scope ");
    lstring a = p(1).empty() ? lstring{} : p(1).qsplit(",").strip();
    setMacro(p(0), a, ip, scoped, local);
    ip = i.ip;
    return true;
  }

  if(s.match("define ?*(*)") || s.match("global define ?*(*)")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    lstring p = s.trim<1>("define ", ")").split<1>("(");
    setDefine(p(0), p(1), local);
    return true;
  }

  if(s.match("evaluate ?*(*)") || s.match("global evaluate ?*(*)")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    lstring p = s.trim<1>("evaluate ", ")").split<1>("(");
    setDefine(p(0), evaluate(p(1)), local);
    return true;
  }

  if(s.match("variable ?*(*)") || s.match("global variable ?*(*)")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    lstring p = s.trim<1>("variable ", ")").split<1>("(");
    setVariable(p(0), evaluate(p(1)), local);
    return true;
  }

  if(s.match("if ?* {")) {
    s.trim<1>("if ", " {").strip();
    bool match = evaluate(s, Evaluation::Strict);
    ifStack.append(match);
    if(match == false) {
      ip = i.ip;
    }
    return true;
  }

  if(s.match("} else if ?* {")) {
    if(ifStack.last()) {
      ip = i.ip;
    } else {
      s.trim<1>("} else if ", " {").strip();
      bool match = evaluate(s, Evaluation::Strict);
      ifStack.last() = match;
      if(match == false) {
        ip = i.ip;
      }
    }
    return true;
  }

  if(s.match("} else {")) {
    if(ifStack.last()) {
      ip = i.ip;
    } else {
      ifStack.last() = true;
    }
    return true;
  }

  if(s.match("} endif")) {
    ifStack.removeLast();
    return true;
  }

  if(s.match("while ?* {")) {
    s.trim<1>("while ", " {").strip();
    bool match = evaluate(s, Evaluation::Strict);
    if(match == false) ip = i.ip;
    return true;
  }

  if(s.match("} endwhile")) {
    ip = i.ip;
    return true;
  }

  if(s.match("?*(*)")) {
    lstring p = string{s}.rtrim<1>(")").split<1>("(");
    lstring a = p(1).empty() ? lstring{} : p(1).qsplit(",").strip();
    string name = {p(0), ":", a.size()};  //arity overloading
    if(auto macro = findMacro({name})) {
      struct Parameter {
        enum class Type : unsigned { Define, Variable } type;
        string name;
        string value;
      };

      vector<Parameter> parameters;
      for(unsigned n = 0; n < a.size(); n++) {
        lstring p = macro().parameters(n).split<1>(" ").strip();
        if(p.size() == 1) p.prepend("define");

        if(p(0) == "define") parameters.append({Parameter::Type::Define, p(1), a(n)});
        else if(p(0) == "string") parameters.append({Parameter::Type::Define, p(1), text(a(n))});
        else if(p(0) == "evaluate") parameters.append({Parameter::Type::Define, p(1), evaluate(a(n))});
        else if(p(0) == "variable") parameters.append({Parameter::Type::Variable, p(1), evaluate(a(n))});
        else error("unsupported parameter type: ", p(0));
      }

      StackFrame frame;
      stackFrame.append(frame);
      stackFrame.last().ip = ip;
      stackFrame.last().scoped = macro().scoped;

      if(macro().scoped) {
        scope.append(p(0));
      }

      setDefine("#", {"_", macroInvocationCounter++}, true);
      for(auto& parameter : parameters) {
        if(parameter.type == Parameter::Type::Define) setDefine(parameter.name, parameter.value, true);
        if(parameter.type == Parameter::Type::Variable) setVariable(parameter.name, integer(parameter.value), true);
      }

      ip = macro().ip;
      return true;
    }
  }

  if(s.match("} endmacro")) {
    ip = stackFrame.last().ip;
    if(stackFrame.last().scoped) scope.removeLast();
    stackFrame.removeLast();
    return true;
  }

  if(assemble(s)) {
    return true;
  }

  evaluate(s);
  return true;
}
Ejemplo n.º 16
0
void
comline(void)
{
	long c1, c2;

	while(C==' ' || c=='\t')
		;
comx:
	if((c1=c) == '\n')
		return;
	c2 = C;
	if(c1=='.' && c2!='.')
		inmacro = NO;
	if(msflag && c1 == '['){
		refer(c2);
		return;
	}
	if(c2 == '\n')
		return;
	if(c1 == '\\' && c2 == '\"')
		SKIP;
	else
	if (filesp==files && c1=='E' && c2=='Q')
			eqn();
	else
	if(filesp==files && c1=='T' && (c2=='S' || c2=='C' || c2=='&')) {
		if(msflag)
			stbl(); 
		else
			tbl();
	}
	else
	if(c1=='T' && c2=='E')
		intable = NO;
	else if (!inmacro &&
			((c1 == 'd' && c2 == 'e') ||
		   	 (c1 == 'i' && c2 == 'g') ||
		   	 (c1 == 'a' && c2 == 'm')))
				macro();
	else
	if(c1=='s' && c2=='o') {
		if(iflag)
			SKIP;
		else {
			getfname();
			if(fname[0]) {
				if(infile = opn(fname))
					*++filesp = infile;
				else infile = *filesp;
			}
		}
	}
	else
	if(c1=='n' && c2=='x')
		if(iflag)
			SKIP;
		else {
			getfname();
			if(fname[0] == '\0')
				exits(0);
			if(Bfildes(&(infile->Biobufhdr)) != 0)
				Bterm(&(infile->Biobufhdr));
			infile = *filesp = opn(fname);
		}
	else
	if(c1 == 't' && c2 == 'm')
		SKIP;
	else
	if(c1=='h' && c2=='w')
		SKIP; 
	else
	if(msflag && c1 == 'T' && c2 == 'L') {
		SKIP_TO_COM;
		goto comx; 
	}
	else
	if(msflag && c1=='N' && c2 == 'R')
		SKIP;
	else
	if(msflag && c1 == 'A' && (c2 == 'U' || c2 == 'I')){
		if(mac==MM)SKIP;
		else {
			SKIP_TO_COM;
			goto comx; 
		}
	} else
	if(msflag && c1=='F' && c2=='S') {
		SKIP_TO_COM;
		goto comx; 
	}
	else
	if(msflag && (c1=='S' || c1=='N') && c2=='H') {
		SKIP_TO_COM;
		goto comx; 
	} else
	if(c1 == 'U' && c2 == 'X') {
		if(wordflag)
			Bprint(&(bout.Biobufhdr), "UNIX\n");
		else
			Bprint(&(bout.Biobufhdr), "UNIX ");
	} else
	if(msflag && c1=='O' && c2=='K') {
		SKIP_TO_COM;
		goto comx; 
	} else
	if(msflag && c1=='N' && c2=='D')
		SKIP;
	else
	if(msflag && mac==MM && c1=='H' && (c2==' '||c2=='U'))
		SKIP;
	else
	if(msflag && mac==MM && c2=='L') {
		if(disp || c1=='R')
			sdis('L', 'E');
		else {
			SKIP;
			Bprint(&(bout.Biobufhdr), " .");
		}
	} else
	if(!msflag && c1=='P' && c2=='S') {
		inpic();
	} else
	if(msflag && (c1=='D' || c1=='N' || c1=='K'|| c1=='P') && c2=='S') { 
		sdis(c1, 'E'); 
	} else
	if(msflag && (c1 == 'K' && c2 == 'F')) { 
		sdis(c1,'E'); 
	} else
	if(msflag && c1=='n' && c2=='f')
		sdis('f','i');
	else
	if(msflag && c1=='c' && c2=='e')
		sce();
	else {
		if(c1=='.' && c2=='.') {
			if(msflag) {
				SKIP;
				return;
			}
			while(C == '.')
				;
		}
		inmacro++;
		if(c1 <= 'Z' && msflag)
			regline(YES,ONE);
		else {
			if(wordflag)
				C;
			regline(YES,TWO);
		}
		inmacro--;
	}
}
Ejemplo n.º 17
0
int
main(int argc, char *argv[])
{
	int c;
	int n;
	int rval;
	char *p;

	setlocale(LC_ALL, "");

	traceout = stderr;

	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, onintr);

	initkwds();
	initspaces();
	STACKMAX = INITSTACKMAX;

	mstack = (stae *)xalloc(sizeof(stae) * STACKMAX);
	sstack = (char *)xalloc(STACKMAX);

	maxout = 0;
	outfile = NULL;
	resizedivs(MAXOUT);

	while ((c = getopt(argc, argv, "gst:d:D:U:o:I:")) != -1)
		switch(c) {
		case 'D':               /* define something..*/
			for (p = optarg; *p; p++)
				if (*p == '=')
					break;
			if (p == optarg)
				errx(1, "null variable cannot be defined");
			if (*p)
				*p++ = EOS;
			dodefine(optarg, p);
			break;
		case 'I':
			addtoincludepath(optarg);
			break;
		case 'U':               /* undefine...       */
			remhash(optarg, TOP);
			break;
		case 'g':
			mimic_gnu = 1;
			break;
		case 'd':
			set_trace_flags(optarg);
			break;
		case 's':
			synccpp = 1;
			break;
		case 't':
			mark_traced(optarg, 1);
			break;
		case 'o':
			trace_file(optarg);
                        break;
		case '?':
		default:
			usage();
		}

        argc -= optind;
        argv += optind;

	rval = 0;
	active = stdout;		/* default active output     */
	bbase[0] = bufbase;
        if (!argc) {
 		sp = -1;		/* stack pointer initialized */
		fp = 0; 		/* frame pointer initialized */
		set_input(infile+0, stdin, "stdin");
					/* default input (naturally) */
		if ((inname[0] = strdup("-")) == NULL)
			err(1, NULL);
		inlineno[0] = 1;
		emitline();
		macro();
	} else
		for (; argc--; ++argv) {
			p = *argv;
			if (p[0] == '-' && p[1] == EOS)
				set_input(infile, stdin, "stdin");
			else if (fopen_trypath(infile, p) == NULL) {
				warn("%s", p);
				rval = 1;
				continue;
			}
			sp = -1;
			fp = 0;
			if ((inname[0] = strdup(p)) == NULL)
				err(1, NULL);
			inlineno[0] = 1;
			emitline();
			macro();
		    	release_input(infile);
		}

	if (*m4wraps) { 		/* anything for rundown ??   */
		ilevel = 0;		/* in case m4wrap includes.. */
		bufbase = bp = buf;	/* use the entire buffer   */
		pbstr(m4wraps); 	/* user-defined wrapup act   */
		macro();		/* last will and testament   */
	}

	if (active != stdout)
		active = stdout;	/* reset output just in case */
	for (n = 1; n < maxout; n++)	/* default wrap-up: undivert */
		if (outfile[n] != NULL)
			getdiv(n);
					/* remove bitbucket if used  */
	if (outfile[0] != NULL) {
		(void) fclose(outfile[0]);
	}

	exit(rval);
}
Ejemplo n.º 18
0
static int scanpp(void) {
	int	c, t;

	if (Rejected != -1) {
		t = Rejected;
		Rejected = -1;
		strcpy(Text, Rejtext);
		Value = Rejval;
		return t;
	}
	for (;;) {
		Value = 0;
		c = skip();
		memset(Text, 0, 4);
		Text[0] = c;
		switch (c) {
		case '!':
			if ((c = next()) == '=') {
				Text[1] = '=';
				return NOTEQ;
			}
			else {
				putback(c);
				return XMARK;
			}
		case '%':
			if ((c = next()) == '=') {
				Text[1] = '=';
				return ASMOD;
			}
			else {
				putback(c);
				return MOD;
			}
		case '&':
			if ((c = next()) == '&') {
				Text[1] = '&';
				return LOGAND;
			}
			else if ('=' == c) {
				Text[1] = '=';
				return ASAND;
			}
			else {
				putback(c);
				return AMPER;
			}
		case '(':
			return LPAREN;
		case ')':
			return RPAREN;
		case '*':
			if ((c = next()) == '=') {
				Text[1] = '=';
				return ASMUL;
			}
			else {
				putback(c);
				return STAR;
			}
		case '+':
			if ((c = next()) == '+') {
				Text[1] = '+';
				return INCR;
			}
			else if ('=' == c) {
				Text[1] = '=';
				return ASPLUS;
			}
			else {
				putback(c);
				return PLUS;
			}
		case ',':
			return COMMA;
		case '-':
			if ((c = next()) == '-') {
				Text[1] = '-';
				return DECR;
			}
			else if ('=' == c) {
				Text[1] = '=';
				return ASMINUS;
			}
			else if ('>' == c) {
				Text[1] = '>';
				return ARROW;
			}
			else {
				putback(c);
				return MINUS;
			}
		case '/':
			if ((c = next()) == '=') {
				Text[1] = '=';
				return ASDIV;
			}
			else {
				putback(c);
				return SLASH;
			}
		case ':':
			return COLON;
		case ';':
			return SEMI;
		case '<':
			if ((c = next()) == '<') {
				Text[1] = '<';
				if ((c = next()) == '=') {
					Text[2] = '=';
					return ASLSHIFT;
				}
				else {
					putback(c);
					return LSHIFT;
				}
			}
			else if ('=' == c) {
				Text[1] = '=';
				return LTEQ;
			}
			else {
				putback(c);
				return LESS;
			}
		case '=':
			if ((c = next()) == '=') {
				Text[1] = '=';
				return EQUAL;
			}
			else {
				putback(c);
				return ASSIGN;
			}
		case '>':
			if ((c = next()) == '>') {
				Text[1] = '>';
				if ((c = next()) == '=') {
					Text[1] = '=';
					return ASRSHIFT;
				}
				else {
					putback(c);
					return RSHIFT;
				}
			}
			else if ('=' == c) {
				Text[1] = '=';
				return GTEQ;
			}
			else {
				putback(c);
				return GREATER;
			}
		case '?':
			return QMARK;
		case '[':
			return LBRACK;
		case ']':
			return RBRACK;
		case '^':
			if ((c = next()) == '=') {
				Text[1] = '=';
				return ASXOR;
			}
			else {
				putback(c);
				return CARET;
			}
		case '{':
			return LBRACE;
		case '|':
			if ((c = next()) == '|') {
				Text[1] = '|';
				return LOGOR;
			}
			else if ('=' == c) {
				Text[1] = '=';
				return ASOR;
			}
			else {
				putback(c);
				return PIPE;
			}
		case '}':
			return RBRACE;
		case '~':
			return TILDE;
		case EOF:
			strcpy(Text, "<EOF>");
			return XEOF;
		case '\'':
			Text[1] = Value = scanch();
			if ((c = next()) != '\'')
				error(
				 "expected '\\'' at end of char literal",
					NULL);
			Text[2] = '\'';
			return INTLIT;
		case '"':
			Value = scanstr(Text);
			return STRLIT;
		case '#':
			Text[0] = '#';
			scanident(next(), &Text[1], TEXTLEN-1);
			if ((t = keyword(Text)) != 0)
				return t;
			error("unknown preprocessor command: %s", Text);
			return IDENT;
		case '.':
			if ((c = next()) == '.') {
				Text[1] = Text[2] = '.';
				Text[3] = 0;
				if ((c = next()) == '.')
					return ELLIPSIS;
				putback(c);
				error("incomplete '...'", NULL);
				return ELLIPSIS;
			}
			putback(c);
			return DOT;
		default:
			if (isdigit(c)) {
				Value = scanint(c);
				return INTLIT;
			}
			else if (isalpha(c) || '_' == c) {
				Value = scanident(c, Text, TEXTLEN);
				if (Expandmac && macro(Text))
					break;
				if ((t = keyword(Text)) != 0)
					return t;
				return IDENT;
			}
			else {
				cerror("funny input character: %s", c);
				break;
			}
		}
	}
}
Ejemplo n.º 19
0
int
main(int argc, char *argv[])
{
	int c;
	int n;
	char *p;

	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, onintr);

	init_macros();
	initspaces();
	STACKMAX = INITSTACKMAX;

	mstack = xreallocarray(NULL, STACKMAX, sizeof(stae), NULL);
	sstack = xalloc(STACKMAX, NULL);

	maxout = 0;
	outfile = NULL;
	resizedivs(MAXOUT);

	while ((c = getopt(argc, argv, "gst:d:D:U:o:I:P")) != -1)
		switch(c) {

		case 'D':               /* define something..*/
			for (p = optarg; *p; p++)
				if (*p == '=')
					break;
			if (*p)
				*p++ = EOS;
			dodefine(optarg, p);
			break;
		case 'I':
			addtoincludepath(optarg);
			break;
		case 'P':
			prefix_builtins = 1;
			break;
		case 'U':               /* undefine...       */
			macro_popdef(optarg);
			break;
		case 'g':
			mimic_gnu = 1;
			break;
		case 'd':
			set_trace_flags(optarg);
			break;
		case 's':
			synch_lines = 1;
			break;
		case 't':
			mark_traced(optarg, 1);
			break;
		case 'o':
			trace_file(optarg);
                        break;
		case '?':
			usage();
		}

        argc -= optind;
        argv += optind;

	initkwds();
	if (mimic_gnu)
		setup_builtin("format", FORMATTYPE);

	active = stdout;		/* default active output     */
	bbase[0] = bufbase;
        if (!argc) {
		sp = -1;		/* stack pointer initialized */
		fp = 0;			/* frame pointer initialized */
		set_input(infile+0, stdin, "stdin");
					/* default input (naturally) */
		macro();
	} else
		for (; argc--; ++argv) {
			p = *argv;
			if (p[0] == '-' && p[1] == EOS)
				set_input(infile, stdin, "stdin");
			else if (fopen_trypath(infile, p) == NULL)
				err(1, "%s", p);
			sp = -1;
			fp = 0;
			macro();
			release_input(infile);
		}

	if (wrapindex) {
		int i;

		ilevel = 0;		/* in case m4wrap includes.. */
		bufbase = bp = buf;	/* use the entire buffer   */
		if (mimic_gnu) {
			while (wrapindex != 0) {
				for (i = 0; i < wrapindex; i++)
					pbstr(m4wraps[i]);
				wrapindex =0;
				macro();
			}
		} else {
			for (i = 0; i < wrapindex; i++) {
				pbstr(m4wraps[i]);
				macro();
			}
		}
	}

	if (active != stdout)
		active = stdout;	/* reset output just in case */
	for (n = 1; n < maxout; n++)	/* default wrap-up: undivert */
		if (outfile[n] != NULL)
			getdiv(n);
					/* remove bitbucket if used  */
	if (outfile[0] != NULL) {
		(void) fclose(outfile[0]);
	}

	return exit_code;
}
Ejemplo n.º 20
0
void eval(BOOLEAN do_gc)
{
  static unsigned int count = 0;

  OBJECT_PTR exp = car(reg_next_expression);

  OBJECT_PTR opcode = car(exp);

  pin_globals();

  if(do_gc)
  {
    count++;

    if(count == GC_FREQUENCY)
    {
      gc(false, true);
      count = 0;
    }
  }

  if(opcode == APPLY && profiling_in_progress)
  {
    last_operator = reg_accumulator;

    if(prev_operator != NIL)
    {
      OBJECT_PTR operator_to_be_used;

      hashtable_entry_t *e;

      unsigned int count;
      unsigned int mem_alloc;
      double elapsed_wall_time;
      double elapsed_cpu_time;

      double temp1 = get_wall_time();
      clock_t temp2 = clock();
      unsigned int temp3 = memory_allocated();

      profiling_datum_t *pd = (profiling_datum_t *)malloc(sizeof(profiling_datum_t));

      if(IS_SYMBOL_OBJECT(prev_operator))
         operator_to_be_used = prev_operator;
      else
      {
        OBJECT_PTR res = get_symbol_from_value(prev_operator, reg_current_env);
        if(car(res) != NIL)
          operator_to_be_used = cdr(res);
        else
          operator_to_be_used = cons(LAMBDA,
                                     cons(get_params_object(prev_operator),
                                          cons(car(get_source_object(prev_operator)), NIL)));
      }

      e = hashtable_get(profiling_tab, (void *)operator_to_be_used);

      if(e)
      {
        profiling_datum_t *pd = (profiling_datum_t *)e->value;

        count = pd->count + 1;

        elapsed_wall_time = pd->elapsed_wall_time + temp1 - wall_time_var;
        elapsed_cpu_time = pd->elapsed_cpu_time + (temp2 - cpu_time_var) * 1.0 / CLOCKS_PER_SEC;
      
        mem_alloc = pd->mem_allocated + temp3 - mem_alloc_var;

        hashtable_remove(profiling_tab, (void *)operator_to_be_used);
        free(pd);
      }
      else
      {
        count = 1;
        elapsed_wall_time = temp1 - wall_time_var;
        elapsed_cpu_time = (temp2 - cpu_time_var) * 1.0 / CLOCKS_PER_SEC;
        mem_alloc = temp3 - mem_alloc_var;
      }

      pd->count = count;
      pd->elapsed_wall_time = elapsed_wall_time;
      pd->elapsed_cpu_time = elapsed_cpu_time;
      pd->mem_allocated = mem_alloc;

      hashtable_put(profiling_tab, (void *)operator_to_be_used, (void *)pd);
    }

    wall_time_var = get_wall_time();
    cpu_time_var = clock();
    mem_alloc_var = memory_allocated();

    prev_operator = reg_accumulator;
  }

  if(opcode == HALT)
  {
    halt_op();
  }
  else if(opcode == REFER)
  {
    if(refer(CADR(exp)))
       return;
    reg_next_expression = CADDR(exp);
  }
  else if(opcode == CONSTANT)
  {
    if(constant(CADR(exp)))
      return;
    reg_next_expression = CADDR(exp);
  }
  else if(opcode == CLOSE)
  {
    if(closure(exp))
      return;
    reg_next_expression = fifth(exp);
  }
  else if(opcode == MACRO)
  {
    if(macro(exp))
      return;
    reg_next_expression = CADDDDR(exp);
  }
  else if(opcode == TEST)
  {
    if(reg_accumulator != NIL)
      reg_next_expression = CADR(exp);
    else
      reg_next_expression = CADDR(exp);
  }
  //Not using this WHILE; reverting 
  //to macro definition, as this
  //version doesn't handle (BREAK)
  else if(opcode == WHILE)
  {
    OBJECT_PTR cond = CADR(exp);
    OBJECT_PTR body  = CADDR(exp);

    OBJECT_PTR ret = NIL;

    while(1)
    {
      OBJECT_PTR temp = reg_current_stack;

      reg_next_expression = cond;

      while(car(reg_next_expression) != NIL)
      {
        eval(false);
        if(in_error)
          return;
      }

      if(reg_accumulator == NIL)
        break;

      reg_next_expression = body;

      while(car(reg_next_expression) != NIL)
      {
        eval(false);
        if(in_error)
          return;
      }

      //to handle premature exits
      //via RETURN-FROM
      if(reg_current_stack != temp)
        return;

      ret = reg_accumulator;
    }

    reg_accumulator = ret;
    reg_next_expression = CADDDR(exp);
  }
  else if(opcode == ASSIGN)
  {
    if(assign(CADR(exp)))
      return;
    reg_next_expression = CADDR(exp);
  }
  else if(opcode == DEFINE)
  {
    if(define(CADR(exp)))
      return;
    reg_next_expression = CADDR(exp);
  }
  else if(opcode == CONTI)
  {
    if(conti())
      return;
    reg_next_expression = CADR(exp);
  }
  else if(opcode == NUATE) //this never gets called
  {
    reg_current_stack = CADR(exp);
    reg_accumulator = CADDR(exp);
    reg_current_value_rib = NIL;
    reg_next_expression =  cons(CONS_RETURN_NIL, cdr(reg_next_expression));
  }
  else if(opcode == FRAME)
  {
    if(frame(exp))
      return;
    reg_next_expression = CADDR(exp);
  }
  else if(opcode == ARGUMENT)
  {
    if(argument())
      return;
    reg_next_expression = CADR(exp);
  }
  else if(opcode == APPLY)
  {
    apply_compiled();
  }
  else if(opcode == RETURN)
  {
    return_op();
  }
}
Ejemplo n.º 21
0
void dParserCompiler::GenerateParserCode (
	const dString& className, 
	const dString& scannerClassName, 
	const char* const outputFileName, 
	const dTree<dTokenInfo, dCRCTYPE>& symbolList, 
	dTree<dState*, dCRCTYPE>& stateList, 
	const dString& userCode, 
	const dString& endUserCode,
	int lastTerminalTokenEnum)
{
	dString templateHeader ("");
	LoadTemplateFile("dParserTemplate _cpp.txt", templateHeader);

	int position = templateHeader.Find ("$(userCode)");
	templateHeader.Replace(position, 11, userCode);

	ReplaceAllMacros (templateHeader, className, "$(className)");
	ReplaceAllMacros (templateHeader, scannerClassName, "$(scannerClass)");


	char text[256];
	sprintf (text, "%d", lastTerminalTokenEnum);
	ReplaceMacro (templateHeader, text, "&(lastTerminalToken)");

	dTree<dState*, dCRCTYPE> sortedStates;
	dTree<dState*, dCRCTYPE>::Iterator stateIter (stateList);
	for (stateIter.Begin(); stateIter; stateIter ++) {
		dState* const state = stateIter.GetNode()->GetInfo();
		sortedStates.Insert(state, state->m_number);
	}

	dTree<int, dString> actionFilter;

	dString emptySematicAction ("");
	dString stateActionsStart ("");
	dString stateActionsCount ("");
	dString nextActionsStateList ("");
	dString sematicActions ("");
	int entriesCount = 0;

	int newLineCount = 0;
	int starAndCountIndex = 0;
	dTree<dState*, dCRCTYPE>::Iterator sortStateIter (sortedStates);


	const char* const caseTabs0 = "\t\t\t\t\t\t";
	//const char* const caseTabs1 = "\t\t\t\t\t\t\t";
	for (sortStateIter.Begin(); sortStateIter; sortStateIter ++) {
		dState* const state = sortStateIter.GetNode()->GetInfo();

		int count = 0;
		dTree<dActionEntry, int> actionSort;
		dTree<dAction, dCRCTYPE>::Iterator actionIter (state->m_actions);
		for (actionIter.Begin(); actionIter; actionIter++) {
			count ++;

			dAction& action = actionIter.GetNode()->GetInfo();
			if (action.m_type == dSHIFT) {
				dCRCTYPE actionSymbol = actionIter.GetKey();
				dAssert (symbolList.Find(actionSymbol));

				dActionEntry entry;
				entry.m_stateType = char (action.m_type);
				entry.m_errorRule = state->m_hasErroItem ? 1 : 0;
				entry.m_ruleIndex = 0;
				entry.m_ruleSymbols = 0;
				entry.m_nextState = short (action.m_nextState);
				entry.m_token = short (symbolList.Find(actionSymbol)->GetInfo().m_tokenId);

				actionSort.Insert (entry, entry.m_token);

			} else if (action.m_type == dREDUCE) {

				dCRCTYPE actionSymbol = actionIter.GetKey();
				dAssert (symbolList.Find(actionSymbol));

				dRuleInfo& reduceRule = action.m_reduceRuleNode->GetInfo();
				dAssert (symbolList.Find(reduceRule.m_nameCRC));
				dAssert (symbolList.Find(reduceRule.m_nameCRC)->GetInfo().m_tokenId >= 256);

				dActionEntry entry;
				entry.m_stateType = char (action.m_type);
				entry.m_errorRule = 0; //state->m_hasErroItem ? 1 : 0;
				entry.m_ruleIndex = short (reduceRule.m_ruleNumber);
				entry.m_ruleSymbols = short (reduceRule.GetCount());
				entry.m_nextState = short (symbolList.Find(reduceRule.m_nameCRC)->GetInfo().m_tokenId - lastTerminalTokenEnum);
				entry.m_token = short (symbolList.Find(actionSymbol)->GetInfo().m_tokenId);
				actionSort.Insert (entry, entry.m_token);

				if (!reduceRule.m_ruleReduced && (reduceRule.m_semanticActionCode != emptySematicAction)) {
					// issue a sematic action code;

					reduceRule.m_ruleReduced = true;
					char text[128];
					dString userSematicAction (reduceRule.m_semanticActionCode);
					int symbolsCount = int (entry.m_ruleSymbols);
					for (int i = 0; i < symbolsCount; i ++) {

						sprintf (text, "%d", symbolsCount - i);
						dString macro ("$");
						macro += text;

						sprintf (text, "%d", symbolsCount - i - 1);
						dString macroVariable ("parameter[");
						macroVariable += text;
						macroVariable += "].m_value";
						ReplaceAllMacros (userSematicAction, macroVariable, macro);
					}
					ReplaceAllMacros (userSematicAction, "entry.m_value", "$$");

					sprintf (text, "%d:", reduceRule.m_ruleNumber);
					sematicActions += caseTabs0;
					sematicActions += "case "; 
					sematicActions += text; 
					//sematicActions += "// rule ";
					sematicActions += "// ";
					sematicActions += reduceRule.m_name;
					sematicActions += " : ";
					for (dRuleInfo::dListNode* node = reduceRule.GetFirst(); node; node = node->GetNext()) {
						sematicActions+= node->GetInfo().m_name;
						sematicActions += " ";
					}
					sematicActions += "\n";
					sematicActions += userSematicAction;
					sematicActions += "\nbreak;\n\n";
				}

			} else {
				dAssert (action.m_type == dACCEPT);

				dActionEntry entry;
				entry.m_stateType = char (action.m_type);
				entry.m_errorRule = 0; //state->m_hasErroItem ? 1 : 0;
				entry.m_ruleIndex = 0;
				entry.m_ruleSymbols = 0;
				entry.m_nextState = 0;
				entry.m_token = DACCEPTING_TOKEN;
				actionSort.Insert (entry, entry.m_token);
			}
		}

		int actionIndex = entriesCount;
		dString stateActions ("");
		dTree<dActionEntry, int>::Iterator iter (actionSort);
		for (iter.Begin(); iter; iter ++) {
			const dActionEntry& entry = iter.GetNode()->GetInfo();
			sprintf (text, "%d, %d, %d, %d, %d, %d, ", entry.m_token, entry.m_errorRule, entry.m_stateType, entry.m_nextState, entry.m_ruleSymbols, entry.m_ruleIndex);
			stateActions += text; 
			entriesCount ++;
		}

		dTree<int, dString>::dTreeNode* const stateActionNode = actionFilter.Find(stateActions);
		if (stateActionNode) {
			entriesCount = actionIndex;
			actionIndex =  stateActionNode->GetInfo();
		} else {
			actionFilter.Insert(actionIndex, stateActions);

			for (iter.Begin(); iter; iter ++) {
				if (newLineCount % 4 == 0) {
					nextActionsStateList += "\n\t\t\t";
				}
				newLineCount ++;
				const dActionEntry& entry = iter.GetNode()->GetInfo();
				sprintf (text, "dActionEntry (%d, %d, %d, %d, %d, %d), ", entry.m_token, entry.m_errorRule, entry.m_stateType, entry.m_nextState, entry.m_ruleSymbols, entry.m_ruleIndex);
				nextActionsStateList += text; 
			}
		}

		if ((starAndCountIndex % 24) == 0) {
			stateActionsStart += "\n\t\t\t";
			stateActionsCount += "\n\t\t\t";
		}
		starAndCountIndex ++;

		sprintf (text, "%d, ", actionIndex);
		stateActionsStart += text;

		sprintf (text, "%d, ", count);
		stateActionsCount += text;
	}
	nextActionsStateList.Replace(nextActionsStateList.Size()-2, 2, "");
	stateActionsCount.Replace(stateActionsCount.Size()-2, 2, "");
	stateActionsStart.Replace(stateActionsStart.Size()-2, 2, "");

	ReplaceMacro (templateHeader, stateActionsCount, "$(actionsCount)");
	ReplaceMacro (templateHeader, stateActionsStart, "$(actionsStart)");
	ReplaceMacro (templateHeader, nextActionsStateList, "$(actionTable)");

	ReplaceMacro (templateHeader, sematicActions, "$(semanticActionsCode)");


	dString stateGotoStart ("");
	dString stateGotoCount ("");
	dString nextGotoStateList ("");
	entriesCount = 0;
	int newLine = 0;
	int gotoStateCount = 0;
	for (sortStateIter.Begin(); sortStateIter; sortStateIter ++) {

		char text[256];
		dState* const state = sortStateIter.GetNode()->GetInfo();

		int currentEntryuCount = entriesCount;

		int count = 0;
		dTree<dState*, dCRCTYPE>::Iterator gotoIter (state->m_goto); 
		dTree<dTree<dState*, dCRCTYPE>::dTreeNode*, int> sortGotoActions;
		for (gotoIter.Begin(); gotoIter; gotoIter++) {
			int id = symbolList.Find(gotoIter.GetKey())->GetInfo().m_tokenId;
			sortGotoActions.Insert(gotoIter.GetNode(), id);
		}

		dTree<dTree<dState*, dCRCTYPE>::dTreeNode*, int>::Iterator iter1 (sortGotoActions);
		for (iter1.Begin(); iter1; iter1++) {
			count ++;
			if ((newLine % 5) == 0) {
				nextGotoStateList += "\n\t\t\t";
			}
			newLine ++;

			dTree<dState*, dCRCTYPE>::dTreeNode* const node = iter1.GetNode()->GetInfo();
			dState* const targetState = node->GetInfo();

			dGotoEntry entry;
			entry.m_nextState = short (targetState->m_number);
			entry.m_token = short(iter1.GetKey());

			sprintf (text, "dGotoEntry (%d, %d), ", entry.m_token, entry.m_nextState);
			nextGotoStateList += text;
			entriesCount ++;
		}

		if ((gotoStateCount % 24) == 0) {
			stateGotoStart += "\n\t\t\t";
			stateGotoCount += "\n\t\t\t";
		}
		gotoStateCount ++;

		sprintf (text, "%d, ", currentEntryuCount);
		stateGotoStart += text;

		sprintf (text, "%d, ", count);
		stateGotoCount += text;
	}

	nextGotoStateList.Replace(nextGotoStateList.Size()-2, 2, "");
	stateGotoCount.Replace(stateGotoCount.Size()-2, 2, "");
	stateGotoStart.Replace(stateGotoStart.Size()-2, 2, "");

	ReplaceMacro (templateHeader, stateGotoCount, "$(gotoCount)");
	ReplaceMacro (templateHeader, stateGotoStart, "$(gotoStart)");
	ReplaceMacro (templateHeader, nextGotoStateList, "$(gotoTable)");

	templateHeader += endUserCode;
	SaveFile(outputFileName, ".cpp", templateHeader);
}
Ejemplo n.º 22
0
int execute(TREPTR argt, int execflg, int *pf1, int *pf2)
{
	/* `stakbot' is preserved by this routine */
	register TREPTR t;
	STKPTR sav = savstak();

	sigchk();

	if ((t = argt) && execbrk == 0) {
		register int treeflgs;
		int oldexit, type;
		register char **com;

		treeflgs = t->tretyp;
		type = treeflgs & COMMSK;
		oldexit = exitval;
		exitval = 0;

		switch (type) {

		case TCOM:
			{
				STRING a1;
				int argn, internal;
				ARGPTR schain = gchain;
				IOPTR io = t->treio;
				gchain = 0;
				argn = getarg((void *)t);/*FIXME*/
				com = scan(argn);
				a1 = com[1];
				gchain = schain;

				if ((internal = syslook(com[0], commands)) || argn == 0)
					setlist(((COMPTR) t)->comset, 0);

				if (argn && (flags & noexec) == 0) {	/* print command if execpr */
					if (flags & execpr) {
						argn = 0;
						prs(execpmsg);
						while (com[argn] != ENDARGS) {
							prs(com[argn++]);
							blank();
						}
						newline();
					}

					switch (internal) {

					case SYSDOT:
						if (a1) {
							register int f;

							if ((f = pathopen(getpath(a1), a1)) < 0)
								failed(a1, notfound);
							else
								execexp(0, f);
						}
						break;

					case SYSTIMES:
					{
						struct tms t;
						times(&t);
						prt(t.tms_cutime);
						blank();
						prt(t.tms_cstime);
						newline();
					}
					break;

					case SYSEXIT:
						exitsh(a1 ? stoi(a1) : oldexit);

					case SYSNULL:
						io = 0;
						break;

					case SYSCONT:
						execbrk = -loopcnt;
						break;

					case SYSBREAK:
						if ((execbrk = loopcnt) && a1)
							breakcnt = stoi(a1);
						break;

					case SYSTRAP:
						if (a1) {
							BOOL clear;
							if ((clear = digit(*a1)) == 0)
								++com;
							while (*++com) {
								int i;
								if ((i = stoi(*com)) >= MAXTRAP || i < MINTRAP)
									failed(*com, badtrap);
								else if (clear)
									clrsig(i);
								else {
									replace(&trapcom[i], a1);
									if (*a1)
										getsig(i);
									else
										ignsig(i);
								}
							}
						} else {	/* print out current traps */
							int i;

							for (i = 0; i < MAXTRAP; i++) {
								if (trapcom[i]) {
									prn(i);
									prs(colon);
									prs(trapcom[i]);
									newline();
								}
							}
						}
						break;

					case SYSEXEC:
						com++;
						initio(io);
						ioset = 0;
						io = 0;
						if (a1 == 0)
							break;

					case SYSLOGIN:
						flags |= forked;
						oldsigs();
						execa((const char **)com);
						done();

					case SYSCD:
						if (flags & rshflg)
							failed(com[0], restricted);
						else if ((a1 == 0 && (a1 = (char *)homenod.namval) == 0) || chdir(a1) < 0) /* FIXME */
							failed(a1, baddir);
						break;

					case SYSSHFT:
						if (dolc < 1)
							error(badshift);
						else {
							dolv++;
							dolc--;
						}
						assnum(&dolladr, dolc);
						break;

					case SYSWAIT:
						await(-1);
						break;

					case SYSREAD:
						exitval = readvar(&com[1]);
						break;

/*
				case SYSTST:
					exitval=testcmd(com);
					break;
*/

					case SYSSET:
						if (a1) {
							int argc;
							argc = options(argn, (const char **)com);
							if (argc > 1)
								setargs((const char **)com + argn - argc);
						} else if (((COMPTR) t)->comset == 0)
						        /* Scan name chain and print */
							namscan(printnam);
						break;

					case SYSRDONLY:
						exitval = N_RDONLY;
					case SYSXPORT:
						if (exitval == 0)
							exitval = N_EXPORT;;

						if (a1) {
							while (*++com)
								attrib(lookup(*com), exitval);
						} else {
							namscan(printflg);
						}
						exitval = 0;
						break;

					case SYSEVAL:
						if (a1)
							execexp(a1, (UFD)&com[2]);	/* FIXME */
						break;

					case SYSUMASK:
						if (a1) {
							int c, i;
							i = 0;
							while ((c = *a1++) >= '0' && c <= '7')
								i = (i << 3) + c - '0';
							umask(i);
						} else {
							int i, j;
							umask(i = umask(0));
							prc('0');
							for (j = 6; j >= 0; j -= 3)
								prc(((i >> j) & 07) + '0');
							newline();
						}
						break;

					default:
						internal = builtin(argn, com);

					}

					if (internal) {
						if (io)
							error(illegal);
						chktrap();
						break;
					}
				} else if (t->treio == 0)
					break;
			}

		case TFORK:
			if (execflg && (treeflgs & (FAMP | FPOU)) == 0)
				parent = 0;
			else {
				while ((parent = fork()) == -1) {
					sigchk();
					alarm(10);
					pause();
				}
			}

			if (parent) {	/* This is the parent branch of fork;    */
				/* it may or may not wait for the child. */
				if (treeflgs & FPRS && flags & ttyflg) {
					prn(parent);
					newline();
				}
				if (treeflgs & FPCL)
					closepipe(pf1);
				if ((treeflgs & (FAMP | FPOU)) == 0)
					await(parent);
				else if ((treeflgs & FAMP) == 0)
					post(parent);
				else
					assnum(&pcsadr, parent);

				chktrap();
				break;
			} else {	/* this is the forked branch (child) of execute */
				flags |= forked;
				iotemp = 0;
				postclr();
				settmp();

				/* Turn off INTR and QUIT if `FINT'  */
				/* Reset ramaining signals to parent */
				/* except for those `lost' by trap   */
				oldsigs();
				if (treeflgs & FINT) {
					signal(INTR, SIG_IGN);
					signal(QUIT, SIG_IGN);
				}

				/* pipe in or out */
				if (treeflgs & FPIN) {
					sh_rename(pf1[INPIPE], 0);
					close(pf1[OTPIPE]);
				}
				if (treeflgs & FPOU) {
					sh_rename(pf2[OTPIPE], 1);
					close(pf2[INPIPE]);
				}

				/* default std input for & */
				if (treeflgs & FINT && ioset == 0)
					sh_rename(chkopen(devnull), 0);

				/* io redirection */
				initio(t->treio);
				if (type != TCOM)
					execute(((FORKPTR) t)->forktre, 1, NULL, NULL);
				else if (com[0] != ENDARGS) {
					setlist(((COMPTR) t)->comset, N_EXPORT);
					execa((const char **)com);
				}
				done();
			}

		case TPAR:
			sh_rename(dup(2), output);
			execute(((PARPTR) t)->partre, execflg, NULL, NULL);
			done();

		case TFIL:
		{
			int pv[2];
			chkpipe(pv);
			if (execute(((LSTPTR) t)->lstlef, 0, pf1, pv) == 0)
				execute(((LSTPTR) t)->lstrit, execflg, pv, pf2);
			else
				closepipe(pv);
			break;
                }
		case TLST:
			execute(((LSTPTR) t)->lstlef, 0, NULL, NULL);
			execute(((LSTPTR) t)->lstrit, execflg, NULL, NULL);
			break;

		case TAND:
			if (execute(((LSTPTR) t)->lstlef, 0, NULL, NULL) == 0)
				execute(((LSTPTR) t)->lstrit, execflg, NULL, NULL);
			break;

		case TORF:
			if (execute(((LSTPTR) t)->lstlef, 0, NULL, NULL) != 0)
				execute(((LSTPTR) t)->lstrit, execflg, NULL, NULL);
			break;

		case TFOR:
		{
			NAMPTR n = lookup(((FORPTR) t)->fornam);
			char **args;
			DOLPTR argsav = 0;

			if (((FORPTR) t)->forlst == 0) {
				args = (char **)dolv + 1;
				argsav = useargs();
			} else {
				ARGPTR schain = gchain;
				gchain = 0;
				trim((args = scan(getarg(((FORPTR) t)->forlst)))[0]);
				gchain = schain;
			}
			loopcnt++;
			while (*args != ENDARGS && execbrk == 0) {
				assign(n, *args++);
				execute(((FORPTR) t)->fortre, 0, NULL, NULL);
				if (execbrk < 0) {
					execbrk = 0;
				}
			}
			if (breakcnt)
				breakcnt--;
			execbrk = breakcnt;
			loopcnt--;
			argfor = freeargs(argsav);
        		break;
		}

		case TWH:
		case TUN:
		{
			int i = 0;

			loopcnt++;
			while (execbrk == 0 && (execute(((WHPTR) t)->whtre, 0, NULL, NULL) == 0) == (type == TWH)) {
				i = execute(((WHPTR) t)->dotre, 0, NULL, NULL);
				if (execbrk < 0)
					execbrk = 0;
			}
			if (breakcnt)
				breakcnt--;

			execbrk = breakcnt;
			loopcnt--;
			exitval = i;
			break;
		}

		case TIF:
			if (execute(((IFPTR) t)->iftre, 0, NULL, NULL) == 0)
				execute(((IFPTR) t)->thtre, execflg, NULL, NULL);
			else
				execute(((IFPTR) t)->eltre, execflg, NULL, NULL);
			break;

		case TSW:
		{
			register char *r = mactrim(((SWPTR) t)->swarg);
			t = (TREPTR) ((SWPTR) t)->swlst;
			while (t) {
				ARGPTR rex = ((REGPTR) t)->regptr;
				while (rex) {
					register char *s;
					if (gmatch(r, s = macro(rex->argval)) || (trim(s), eq(r, s))) {
						execute(((REGPTR)t)->regcom, 0, NULL, NULL);
						t = 0;
						break;
					} else
						rex = ((ARGPTR)rex)->argnxt;
				}
				if (t)
					t = (TREPTR) ((REGPTR) t)->regnxt;
			}
		}
		break;

		}
		exitset();
	}
Ejemplo n.º 23
0
void WizardsPlugin::CreateClass(const NewClassInfo &info)
{
    // Start by finding the best choice for tabs/spaces.
    // Use the preference for the target VirtualDir, not the active project, in case the user perversely adds to an inactive one.
    OptionsConfigPtr options = EditorConfigST::Get()->GetOptions();	// Globals first
    wxString TargetProj = info.virtualDirectory.BeforeFirst(wxT(':'));
    if (!TargetProj.empty()) {
        LocalWorkspaceST::Get()->GetOptions(options, TargetProj);	// Then override with any local ones
    }

    wxString separator(wxT("\t"));
    if (!options->GetIndentUsesTabs()) {
        separator = wxString(wxT(' '), wxMax(1, options->GetTabWidth()));
    }

    wxString macro(info.blockGuard);
    if( macro.IsEmpty() ) {
        // use the name instead
        macro = info.name;
        macro.MakeUpper();
        macro << (info.hppHeader ? wxT("_HPP") : wxT("_H"));
    }

    wxString headerExt = (info.hppHeader ? wxT(".hpp") : wxT(".h"));

    wxString srcFile;
    srcFile << info.path << wxFileName::GetPathSeparator() << info.fileName << wxT(".cpp");

    wxString hdrFile;
    hdrFile << info.path << wxFileName::GetPathSeparator() << info.fileName << headerExt;

    //create cpp + h file
    wxString cpp;
    wxString header;

    //----------------------------------------------------
    // header file
    //----------------------------------------------------
    header << wxT("#ifndef ") << macro << wxT("\n");
    header << wxT("#define ") << macro << wxT("\n");
    header << wxT("\n");

    wxString closeMethod;
    if (info.isInline)
        closeMethod << wxT('\n') << separator << wxT("{\n") << separator << wxT("}\n");
    else
        closeMethod = wxT(";\n");

    // Add include for base classes
    if (info.parents.empty() == false) {
        for (size_t i=0; i< info.parents.size(); i++) {

            ClassParentInfo pi = info.parents.at(i);

            // Include the header name only (no paths)
            wxFileName includeFileName(pi.fileName);
            header << wxT("#include \"") << includeFileName.GetFullName() << wxT("\" // Base class: ") << pi.name << wxT("\n");
        }
        header << wxT("\n");
    }

    // Open namespace
    if (!info.namespacesList.IsEmpty()) {
        WriteNamespacesDeclaration (info.namespacesList, header);
    }

    header << wxT("class ") << info.name;

    if (info.parents.empty() == false) {
        header << wxT(" : ");
        for (size_t i=0; i< info.parents.size(); i++) {
            ClassParentInfo pi = info.parents.at(i);
            header << pi.access << wxT(" ") << pi.name << wxT(", ");
        }
        header = header.BeforeLast(wxT(','));
    }
    header << wxT("\n{\n");

    if (info.isSingleton) {
        header << separator << wxT("static ") << info.name << wxT("* ms_instance;\n\n");
    }

    if (info.isAssingable == false) {
        //declare copy constructor & assingment operator as private
        header << wxT("private:\n");
        header << separator << info.name << wxT("(const ") << info.name << wxT("& rhs)") << closeMethod;
        header << separator << info.name << wxT("& operator=(const ") << info.name << wxT("& rhs)") << closeMethod;
        header << wxT("\n");
    }

    if (info.isSingleton) {
        header << wxT("public:\n");
        header << separator << wxT("static ") << info.name << wxT("* Instance();\n");
        header << separator << wxT("static void Release();\n\n");

        header << wxT("private:\n");
        header << separator << info.name << wxT("();\n");

        if (info.isVirtualDtor) {
            header << separator << wxT("virtual ~") << info.name << wxT("();\n\n");
        } else {
            header << separator << wxT('~') << info.name << wxT("();\n\n");
        }
    } else {
        header << wxT("public:\n");
        header << separator << info.name << wxT("()") << closeMethod;
        if (info.isVirtualDtor) {
            header << separator << wxT("virtual ~") << info.name << wxT("()") << closeMethod << wxT("\n");
        } else {
            header << separator << wxT('~') << info.name << wxT("()") << closeMethod << wxT("\n");
        }

    }

    //add virtual function declaration
    wxString v_decl = DoGetVirtualFuncDecl(info, separator);
    if (v_decl.IsEmpty() == false) {
        header << wxT("public:\n");
        header << v_decl;
    }

    header << wxT("};\n\n");

    // Close namespaces
    for (unsigned int i = 0; i < info.namespacesList.Count(); i++) {
        header << wxT("}\n\n");
    }

    header << wxT("#endif // ") << macro << wxT("\n");

    wxFFile file;

    file.Open(hdrFile, wxT("w+b"));
    file.Write(header);
    file.Close();

    //if we have a selected virtual folder, add the files to it
    wxArrayString paths;
    paths.Add(hdrFile);

    //----------------------------------------------------
    // source file
    //----------------------------------------------------
    if (!info.isInline) {
        cpp << wxT("#include \"") << info.fileName << headerExt << wxT("\"\n\n");

        // Open namespace
        if (!info.namespacesList.IsEmpty()) {
            WriteNamespacesDeclaration (info.namespacesList, cpp);
        }

        if (info.isSingleton) {
            cpp << info.name << wxT("* ") << info.name << wxT("::ms_instance = 0;\n\n");
        }
        //ctor/dtor
        cpp << info.name << wxT("::") << info.name << wxT("()\n");
        cpp << wxT("{\n}\n\n");
        cpp << info.name << wxT("::~") << info.name << wxT("()\n");
        cpp << wxT("{\n}\n\n");
        if (info.isSingleton) {
            cpp << info.name << wxT("* ") << info.name << wxT("::Instance()\n");
            cpp << wxT("{\n");
            cpp << separator << wxT("if (ms_instance == 0) {\n");
            cpp << separator << separator << wxT("ms_instance = new ") << info.name << wxT("();\n");
            cpp << separator << wxT("}\n");
            cpp << separator << wxT("return ms_instance;\n");
            cpp << wxT("}\n\n");

            cpp << wxT("void ") << info.name << wxT("::Release()\n");
            cpp << wxT("{\n");
            cpp << separator << wxT("if (ms_instance) {\n");
            cpp << separator << separator << wxT("delete ms_instance;\n");
            cpp << separator << wxT("}\n");
            cpp << separator << wxT("ms_instance = 0;\n");
            cpp << wxT("}\n\n");
        }

        cpp << DoGetVirtualFuncImpl(info);

        // Close namespaces
        if (info.namespacesList.Count()) {
            cpp << wxT('\n');	// Thow in an initial \n to separate the first namespace '}' from the previous function's one
        }

        for (unsigned int i = 0; i < info.namespacesList.Count(); i++) {
            cpp << wxT("}\n\n");
        }

        file.Open(srcFile, wxT("w+b"));
        file.Write(cpp);
        file.Close();

        paths.Add(srcFile);
    }

    // We have a .cpp and an .h file, and there may well be a :src and an :include folder available
    // So try to place the files appropriately. If that fails, dump both in the selected folder
    bool smartAddFiles = EditorConfigST::Get()->GetOptions()->GetOptions() & OptionsConfig::Opt_SmartAddFiles;
    if (!smartAddFiles || ! m_mgr->AddFilesToVirtualFolderIntelligently(info.virtualDirectory, paths) )
        m_mgr->AddFilesToVirtualFolder(info.virtualDirectory, paths);

    // Open the newly created classes in codelite
    for(size_t i=0; i<paths.GetCount(); i++) {
        m_mgr->OpenFile(paths.Item(i));
    }

    // Notify codelite to parse the files
    wxCommandEvent parseEvent(wxEVT_COMMAND_MENU_SELECTED, XRCID("retag_workspace"));
    EventNotifier::Get()->TopFrame()->GetEventHandler()->AddPendingEvent(parseEvent);
}
Ejemplo n.º 24
0
#ifdef USE_PRAGMA_IDENT_HDR
#pragma ident "@(#)opcodes.hpp	1.25 03/12/23 16:42:46 JVM"
#endif
/*
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL.  Use is subject to license terms.
 */

// Build a big enum of class names to give them dense integer indices
#define macro(x) Op_##x,
enum Opcodes {
  Op_Node = 0,
  macro(Set)                    // Instruction selection match rule
  macro(RegI)                   // Machine integer register
  macro(RegP)                   // Machine pointer register
  macro(RegF)                   // Machine float   register
  macro(RegD)                   // Machine double  register
  macro(RegL)                   // Machine long    register
  macro(RegFlags)               // Machine flags   register
  _last_machine_leaf,           // Split between regular opcodes and machine
#include "classes.hpp"
  _last_opcode
};
#undef macro

// Table of names, indexed by Opcode
extern const char *NodeClassNames[];
Ejemplo n.º 25
0
edit()
{
	register char		*p;
	LOCATION		t_loc,
				loc;
	FILE			*fp;
	char			errbuf[ER_MAX_LEN + 1];
	char			input[MAX_LOC + 1];
	char			*editfile;
	char			*ingedit;
	i4			rflag;
	STATUS			status;
	i4			c;
#ifdef CMS
	i4			Notempty = 1;
#endif /* CMS */

	GLOBALREF	char	*IIMOildInitLnDraw;

	FUNC_EXTERN 	char		*getfilenm();
	FUNC_EXTERN 	char		*macro();


	if (!Newline)
	{
		q_putc(Qryiop, '\n');
		Newline = TRUE;
	}

	Autoclear	= 0;
	editfile	= getfilenm();
	rflag		= 0;

	if (*editfile == '\0')
	{
		rflag	 = 1;
		input[0] = EOS;


		if ((status = NMloc( TEMP, PATH, (char *)NULL, &t_loc)) ||
		    (status = LOuniq( ERx( "query" ), ERx( "edt" ), &t_loc)))
		{
			STcopy( ERx( "queryXXX" ), input );
		}
		else
		{
			LOcopy( &t_loc, input, &loc );
		}

		status = SIfopen( &loc, ERx( "w" ), (i4)SI_TXT,
				  (i4)SI_MAX_TXT_REC, &fp );
	}
	else
	{
		/* use the path and file name the user gave you */

		STcopy(editfile, input);

		if (!(status = LOfroms(PATH & FILENAME, input, &loc)))
			status = SIfopen( &loc, ERx("w"), (i4)SI_TXT,
					  (i4)SI_MAX_TXT_REC, &fp );
	}

	if (status)
	{
		if (status == FAIL)
			errbuf[0] = '\0';
		else
			ERreport(status, errbuf);

		putprintf(ERget(F_MO000C_Cant_create_qry_file),
				input, errbuf);

		cgprompt();
		return(0);
	}

	if (q_ropen(Qryiop, 'r') == (struct qbuf *)NULL)
		/* edit: q_ropen 1 */
		ipanic(E_MO0044_1500400);

	while ((c = (i4)q_getc(Qryiop)) > 0)
		SIputc((char)c, fp);

	SIclose(fp);

	if (Nodayfile >= 0)
	{
		putprintf(ERget(F_MO000D_editor_prompt));
		SIflush(stdout);
	}

	/*
	**	macro returns NULL if undefined, UTedit uses
	**		default editor if passed NULL.
	*/

	/* Bug 4875	-	Use editor defined by environment variable
		ING_EDIT. If that is not set then use the macro(editor). 
	*/

	NMgtAt((ERx("ING_EDIT")), &ingedit);
	if ( ingedit != NULL && *ingedit != EOS )
		p = ingedit;
	else

		p = macro(ERx("{editor}"));

	if (status = UTedit(p, &loc))
	{
		ERreport(status, errbuf);
		putprintf(ERget(F_MO000E_Can_t_start_up_editor), errbuf);

		cgprompt();
		return(0);
	}

	if (!rflag)
	{
		if (q_ropen(Qryiop, 'a') == (struct qbuf *)NULL)
			/* edit: q_ropen 2 */
			ipanic(E_MO0045_1500401);
	}
	else
	{
		if (q_ropen(Qryiop, 'w') == (struct qbuf *)NULL)
			/* edit: q_ropen 3 */
			ipanic(E_MO0046_1500402);

		if (status = SIfopen( &loc, ERx("r"), (i4)SI_TXT,
				      (i4)SI_MAX_TXT_REC, &fp ))
#ifdef CMS
		{
			Notempty = 0;
		}
#else
		{
			ERreport(status, errbuf);
			/* can't reopen editfile %s: %s\n */
			ipanic(E_MO0047_1500403,
				editfile, errbuf);
		}
#endif /* CMS */

#ifdef CMS
		if (Notempty)
		{
#endif /* CMS */
		Notnull = 0;

		while ((c = SIgetc(fp)) != EOF)
		{
			if (status)
			{
				ERreport(status, errbuf);
				/* Error reading edit file: %s\n */
				ipanic(E_MO0048_1500404, errbuf);
			}

			Notnull = 1;

			q_putc(Qryiop, (char)c);
		}

		SIclose(fp);


		if (status = LOpurge(&loc, 0))
		{
			ERreport(status, errbuf);
			putprintf(ERget(F_MO000F_Cant_delete_file), editfile, errbuf);
		}
#ifdef CMS
		} /* endif Notempty */
#endif /* CMS */
	}

#ifndef FT3270
	/* Re-Initialize IT line drawing */
	{
	    if (Outisterm && IIMOildInitLnDraw != NULL)
		SIprintf(ERx("%s"), IIMOildInitLnDraw);
	}
#endif

	cgprompt();

	return(0);
}
Ejemplo n.º 26
0
void makeTPlots(const Char_t *tag = ""){//"dEdx") {
  TString FileN(gDirectory->GetName());
  gInterpreter->ProcessLine(".L Chain.C");
  TChain *theChain = Chain();
  TString macro(".L ");
  const Char_t *T = gSystem->Which(gROOT->GetMacroPath(),"T.C");
  macro += T; delete [] T;
  macro += "+";
  gInterpreter->ProcessLine(macro);
  //  gInterpreter->ProcessLine(".L T.C+");
  TT t(theChain);
#if 1
  TString Out = gSystem->DirName(FileN); cout << Out;
  TString Dir = gSystem->DirName(Out);
  //  Out.ReplaceAll(Dir,"");
  if (Out.BeginsWith("/")) Out = Out.Data()+1;
#else
  TString Out = gSystem->BaseName(FileN);
  Out.ReplaceAll(".root","");
#endif
  Out.ReplaceAll("/","_");
  //   if (FileN.Contains("6073006_raw") Out += "R06";
  //   if (FileN.Contains("6073023_raw") Out += "R23";
  Out += "Plots"; Out += tag; 
  TString Tag(tag);
  if (Tag.Contains("G14G",TString::kIgnoreCase) || 
      Tag.Contains("G24G",TString::kIgnoreCase) || 
      Tag.Contains("G34G",TString::kIgnoreCase) ||
      Tag.Contains("G44G",TString::kIgnoreCase)) {
    t.SetuMinMax(2.5, 2.9);
    Out += "_u_2.5-2.9";
    //    Out += "_u_2.5-2.9_v_0-2.8";
    //    t.SetvMinMax(0.0, 2.8);
  }
  if (Tag.Contains("G15G",TString::kIgnoreCase)) {
    t.SetuMinMax(2.0, 2.5);
    Out += "_u_2.0-2.5";
    //    Out += "_u_2.5-2.9_v_0-2.8";
    //    t.SetvMinMax(0.0, 2.8);
  }
  if (Tag.Contains("G21G",TString::kIgnoreCase)) {
    t.SetVertexZCut(2.0); // cm from z = 0
  }
  if (Tag.Contains("G22G",TString::kIgnoreCase)) {
    t.SetDipCut(0.9); // pT < DipCut*p 
  }
  if (Tag.Contains("NoW",TString::kIgnoreCase)) {
    t.SetNoWafers(); 
  }
  if (Tag.Contains("BL",TString::kIgnoreCase)) {
    t.SetLaddersInGlobal(kTRUE); 
  }
  if (Tag.Contains("ssd",TString::kIgnoreCase)) {
    t.SetSsd(kTRUE); 
  }
  if (Tag.Contains("svt",TString::kIgnoreCase)) {
    t.SetSvt(kTRUE); 
  }
  if (Tag.Contains("east",TString::kIgnoreCase)) {
    if (Tag.Contains("fareast",TString::kIgnoreCase))    t.SetEastWest(3);
    else                                                 t.SetEastWest(1);
  } else {
    if (Tag.Contains("west",TString::kIgnoreCase)) {
      if (Tag.Contains("farwest",TString::kIgnoreCase)) t.SetEastWest(4);
      else                                              t.SetEastWest(2);
    }
  }
  if (Tag.Contains("global",TString::kIgnoreCase)) {
    t.UseGlobal();
  }
  if (Tag.Contains("local",TString::kIgnoreCase)) {
    t.UseLocal();
  }  
  if (Tag.Contains("dEdx",TString::kIgnoreCase)) {
    t.SetdEdxCut(4.e-6,40.);
  }  
  //  t.SetRCut(1.0);
  t.SetRCut(0.5);
  t.SetMinNoFitPoints(25);
  Out += "NFP25";
  Out += Form("rCut%3.1fcm",t.GetRCut());
  Out += ".root";
  cout << " ===> " << Out << endl;
  t.SetOutFileName(Out);
  t.Loop(0);
}
int main()
{FILE *fp,*fpn,*fpo;
fpa=fopen("ALA.dil","wb+");
fclose(fpa);
fpa=fopen("ALA2.dil","wb+");
fclose(fpa);
char stu[15];//For storing the operand so that endl value is not passed along with it
int i;
  fpo=fopen("Output.txt","w+");
  fclose(fpo);
fpm=fopen("MDT.dil","wb+");
fclose(fpm);//For initialising the needed files
int flag=0;
fp=fopen("Input.txt","r");
while(!feof(fp))
{
            fscanf(fp,"%s",label);
fscanf(fp,"%s",op);
fscanf(fp,"%s",operand);

if(flag==1)
macro();//If a macro definetion is found pass-1 is called

if(strcmp(op,"MACRO")==0)
flag=1; //Macro definetion found, flag is set so that from next step on, it can be stored in MDT


  if(strcmp(op,"MEND")==0)
  {
                            flag=0;s=0;
                         fseek(fpm,0,SEEK_END);   //For appending in the last, can be prevented if "a" attribute is used during the opening of file
  fwrite(&m,sizeof(m),1,fpm);
  fclose(fpm);
            }
            }

            rewind(fp);
             fpn=fopen("Input2.txt","w+");//creating the macro definetions free input for pass-2
             flag=0;
             i=0;
        while(!feof(fp))
{
            fscanf(fp,"%s",label);
fscanf(fp,"%s",op);
fscanf(fp,"%s",operand);

if(flag==1)
{if(strcmp(op,"MACRO")!=0)//If after MEND, MACRO is not found, that is the end of macro definetions
flag=2;
else
flag=0;}

if(flag==2)//After all the definetions ended we can set the flag to 2, and copy the remaining contents into new file
{fprintf(fpn,"%s\t%s\t%s\n",label,op,operand);
i++;
}

if(strcmp(op,"MEND")==0)
flag=1;//Checking whether MEND occurs
}

fclose(fpn);
fclose(fp);

          printf("Pass-1 is over\nThe definetions stored in MDT are:\n");
            fpm=fopen("MDT.dil","r");
            while(fread(&m,sizeof(m),1,fpm)==1)
            printf("%s\t\t\t\t\t\t%s",m.name,m.def);
            fclose(fpm);
            fpn=fopen("Input2.txt","r");


            ct=0;
             while(!feof(fpn))
             {


                   fscanf(fpn,"%s",label);
fscanf(fpn,"%s",op);
fscanf(fpn,"%s",operand);

                             pass2();
                           i--;
                           if(i==0)//To prevent the extra space of endl
                           break;

                             }
                              printf("The arguements stored in ALA are:\n");
            fpm=fopen("ALA2.dil","r");
            while(fread(&a1,sizeof(a1),1,fpm)==1)
            printf("%s\t%s\n",a1.hash,a1.arg);
            fclose(fpm);
                             printf("Pass-2 is over\n");
            getche();//To wait, so that screen is not closed abruptly


            }
#include "generate_interface_impl.hpp"

namespace xios
{

#define macro(T) \
  template void CInterface::AttributeCInterface<T>(ostream& oss,const string& className,const string& name) ; \
  template void CInterface::AttributeFortran2003Interface<T>(ostream& oss,const string& className,const string& name) ; \
  template void CInterface::AttributeFortranInterfaceDeclaration<T>(ostream& oss,const string& className,const string& name) ; \
  template void CInterface::AttributeFortranInterfaceGetDeclaration<T>(ostream& oss,const string& className,const string& name) ; \
  template void CInterface::AttributeFortranInterfaceBody<T>(ostream& oss,const string& className,const string& name) ; \
  template void CInterface::AttributeFortranInterfaceGetBody<T>(ostream& oss,const string& className,const string& name) ; \
  template string CInterface::getStrFortranType<T>(void) ; \
  template string CInterface::getStrFortranKind<T>(void) ; \
  template string CInterface::getStrFortranKindC<T>(void) ; \
  template bool CInterface::matchingTypeCFortran<T>(void) ; 
  
  macro(bool)
  macro(int)
  macro(double)
  macro(CDate)
  macro(CDuration)
}