equation* equation_factory::vector_equation(std::string eq){
	for (size_t i = 0; i < eq.size(); ++i) {//basically, if it's not an equation, don't bother parsing. It's not going to end well.
		if (eq.at(i) == '\\' || eq.at(i) == ':') return NULL;
	}

	std::vector<std::string> eqrs;
	std::istringstream ss(eq);
	std::string token;
	while(std::getline(ss, token, ',')){
		eqrs.push_back(token);
	}
	std::vector<std::string> all_real;
	std::string white_space(" ");
	for(unsigned int i = 0; i < eqrs.size(); ++i){
		std::string k = replacer(eqrs[i], std::string("<"), white_space);
		std::string f = replacer(k, std::string(">"), white_space);
		all_real.push_back(f);
	}
	
	equation* ret = new equation();
	ret->isVector = true;
	ret->xyz = new equation*[3];
	ret->xyz[0] = scalar_equation(all_real[0]);
	ret->xyz[1] = scalar_equation(all_real[1]);
	ret->xyz[2] = scalar_equation(all_real[2]);
	ret->self = eq;
	
	return ret;
	
}
Example #2
0
void t_army_mover::report_stealth()
{
	if (m_stealth_experience.empty())
		return;

	if (m_army->is_human())
	{
		t_counted_ptr<t_basic_dialog>	dialog;
		int								i;
		std::string						text;
		t_hero_keyword_replacer			replacer;

		dialog = new t_basic_dialog;

		for (i = 0; i < m_stealth_experience.size(); ++i)
		{
			dialog->add_experience( m_stealth_experience[i].experience, 
									m_stealth_experience[i].hero );
			replacer.add_hero( m_stealth_experience[i].hero );
		}
		if (m_stealth_experience.size() == 1)
			text = replacer( k_text_stealth_use_singular );
		else
			text = replacer( k_text_stealth_use_plural );
		dialog->set_text( text );
		dialog->add_ok_button();
		dialog->open();
		dialog->run_modal();
	}
	m_army->check_hero_levels();
	m_stealth_experience.clear();
}
static std::string format_hero_list( t_creature_array const& army, std::string const& singular,
									 std::string const& plural )
{
	int						count = 0;
	t_hero_keyword_replacer replacer;
	int						i;
	t_hero const*			hero;

	for (i = 0; i < t_creature_array::k_size; ++i)
	{
		hero = army[i].get_hero();

		if (hero == 0)
			continue;
		++count;
		replacer.add_hero( hero );
	}
	
	if (count == 0)
		return replace_keywords( singular, "%hero_name", k_the_army );

	if (count == 1)
		return replacer( singular );
	return replacer( plural );
}
Example #4
0
TEST(SymbolTable, recursiveReplace) {
  CompileErrorList errors;
  SymbolGraph graph;
  graph.addNode(Symbol(ZP("A"), ZP("(B C D 0)")));
  graph.addNode(Symbol(ZP("B"), ZP("(C C 1)")));
  graph.addNode(Symbol(ZP("C"), ZP("(D D D 2)")));
  graph.addNode(Symbol(ZP("D"), ZP("(E 3)")));
  graph.addNode(Symbol(ZP("E"), ZP("(X 4)")));
  graph.addNode(Symbol(ZP("F"), ZP("(A B C D E X 5)")));
  auto eval = graph.evaluate();
  ASSERT_TRUE(eval.valid());
  SymbolReplacer replacer(eval);
  auto result = replacer.replace(ZP("F ABCDEFG HIJKLMNOP A B F"), errors);
  ASSERT_EQ(result.string(),
            "((((((X 4) 3) ((X 4) 3) ((X 4) 3) 2) (((X 4) 3) ((X 4) 3) ((X 4) "
            "3) 2) 1) (((X 4) 3) ((X 4) 3) ((X 4) 3) 2) ((X 4) 3) 0) ((((X 4) "
            "3) ((X 4) 3) ((X 4) 3) 2) (((X 4) 3) ((X 4) 3) ((X 4) 3) 2) 1) "
            "(((X 4) 3) ((X 4) 3) ((X 4) 3) 2) ((X 4) 3) (X 4) X 5) ABCDEFG "
            "HIJKLMNOP (((((X 4) 3) ((X 4) 3) ((X 4) 3) 2) (((X 4) 3) ((X 4) "
            "3) ((X 4) 3) 2) 1) (((X 4) 3) ((X 4) 3) ((X 4) 3) 2) ((X 4) 3) 0) "
            "((((X 4) 3) ((X 4) 3) ((X 4) 3) 2) (((X 4) 3) ((X 4) 3) ((X 4) 3) "
            "2) 1) ((((((X 4) 3) ((X 4) 3) ((X 4) 3) 2) (((X 4) 3) ((X 4) 3) "
            "((X 4) 3) 2) 1) (((X 4) 3) ((X 4) 3) ((X 4) 3) 2) ((X 4) 3) 0) "
            "((((X 4) 3) ((X 4) 3) ((X 4) 3) 2) (((X 4) 3) ((X 4) 3) ((X 4) 3) "
            "2) 1) (((X 4) 3) ((X 4) 3) ((X 4) 3) 2) ((X 4) 3) (X 4) X 5)");
}
Example #5
0
void FixupMap::replaceShader(const std::string& oldShader, const std::string& newShader)
{
	// Instantiate a walker
	ShaderReplacer replacer(oldShader, newShader);
	GlobalSceneGraph().root()->traverse(replacer);

	_result.replacedShaders += replacer.getReplaceCount();
}
void FixAbbreviationsInElement(string& result)
{
    for (int pat=0; set_abbreviation_list[pat].first[0]!='\0'; ++pat) {
        CRegexpUtil replacer( result );
        //int num_replacements = 
        replacer.Replace( set_abbreviation_list[pat].first, set_abbreviation_list[pat].second, 
            CRegexp::fCompile_ignore_case, CRegexp::fMatch_default, 0);
        replacer.GetResult().swap( result );
    }
}
Example #7
0
void FixupMap::replaceSpawnarg(const std::string& oldVal, const std::string& newVal)
{
	SpawnargReplacer replacer(oldVal, newVal);
	GlobalSceneGraph().root()->traverse(replacer);

	replacer.processEntities();

	_result.replacedModels += replacer.getModelCount();
	_result.replacedEntities += replacer.getEclassCount();
	_result.replacedMisc += replacer.getOtherCount();
}
void FixOrgNames(objects::CSeq_entry_Handle seh, string& result)
{
    vector<string> taxnames;
    FindOrgNames(seh,taxnames);
    for(vector<string>::const_iterator name=taxnames.begin(); name!=taxnames.end(); ++name) {
        CRegexpUtil replacer( result );
        //int num_replacements = 
        replacer.Replace( "\\b"+*name+"\\b", *name, CRegexp::fCompile_ignore_case, CRegexp::fMatch_default, 0);
        replacer.GetResult().swap( result );
    }
}
Example #9
0
void string_replace(StringType &dst, const StringType &src, const StringType &old_str, const StringType &new_str)
{

  if (old_str.size() == 0 || old_str.size() > src.size()) {
    /* Just copy -- there's nothing to replace */
    dst = src;
  }
  else if (old_str.size() == new_str.size()) {
    /* Special case when old_str and new_str are same length,
       we copy src to dst and the replace in-place. */
    dst = src;

    if (old_str.size() == 1) {
      /* Special case when old_str and new_str are both 1 character */
      char old_chr = old_str.begin()[0];
      char new_chr = new_str.begin()[0];
      for (auto p = dst.begin(); p != dst.end(); ++p) {
        if (*p == old_chr) {
          *p = new_chr;
        }
      }
    }
    else {
      detail::string_inplace_replacer<StringType> replacer(dst, new_str);
      detail::string_search(src, old_str, replacer);
    }
  }
  else {
    /* Most general case, where old_str and new_str are different
       lengths.  Count matches to determine resulting string length,
       then interleave to make the result. */
    intptr_t count = string_count(src, old_str);
    size_t delta = ((intptr_t)new_str.size() - (intptr_t)old_str.size()) * count;

    dst.resize((intptr_t)src.size() + delta);

    detail::string_copy_replacer<StringType> replacer(dst, src, old_str, new_str);
    detail::string_search(src, old_str, replacer);
    replacer.finish();
  }
}
Example #10
0
TEST(SymbolTable, replaceSimple) {
  CompileErrorList errors;
  SymbolGraph graph;
  graph.addNode(Symbol(ZP("A"), ZP("B")));
  graph.addNode(Symbol(ZP("B"), ZP("C")));
  graph.addNode(Symbol(ZP("C"), ZP("D")));
  graph.addNode(Symbol(ZP("E"), ZP("C")));
  auto eval = graph.evaluate();
  ASSERT_TRUE(eval.valid());
  SymbolReplacer replacer(eval);
  auto result =
      replacer.replace(ZP("A+B+C+c=E-D+X-ABCDEFG-124*12B32#E"), errors);
  ASSERT_EQ(result.string(), "D+D+D+c=D-D+X-ABCDEFG-124*12B32#D");
}
Example #11
0
void read_data(uint32 datum_count) {
  uint32 data[datum_count];
  data_package pack = {datum_count, data};

  for (uint32 cur = 0; cur < datum_count; cur++) {
    uint32 datum;
    cgc_read(&datum, sizeof(datum));
    data[cur] = datum;
  }

  while(1) {
    transmit_all(STDOUT, "CHRT", 4);
    transmit_all(STDOUT, (char*)(&datum_count), 4);

    uint32 choice;
    cgc_read(&choice, sizeof(choice));
    
    switch(choice) {
    case 1:
      sparks(pack);
      break;
    case 3:
      bars(pack);
      break;
    case 4:
      echo();
      break;
    case 5:
      seed();
      break;
    case 6:
      noise();
      break;
    case 7:
      replacer(pack);
      break;
    default:
      _terminate(0);
    }
  }
}
Example #12
0
void t_magic_university::right_click( t_mouse_event const& event,
                                      t_adventure_frame* adventure_frame )
{
    t_skill_mastery information = get_information_level();
    int				player_number = get_map()->get_player_number();

    if (information >= k_mastery_basic)
        m_visited[player_number] = true;
    if (!m_visited[player_number])
    {
        t_stationary_adventure_object::right_click( event, adventure_frame );
        return;
    }
    std::string				help_text = get_text( "help_skills" );
    t_hero_keyword_replacer replacer;
    int						i;

    for (i = 0; i < m_skills.size(); ++i)
        replacer.add_skill( t_skill( m_skills[i], k_mastery_basic ) );

    show_popup_text( replacer( help_text ), event.screen_point );
}
Example #13
0
 void MTD_FLASHMEM HTTPTemplateResponse::processFileRequest()
 {
     char const* mimetype;
     void const* data;
     uint16_t dataLength;
     if (m_filename && FlashFileSystem::find(m_filename, &mimetype, &data, &dataLength))
     {
         // found
         setStatus(STR_200_OK);
         addHeader(STR_Content_Type, FSTR("text/html"));
         
         // replace parameters
         ParameterReplacer replacer((char const*)data, (char const*)data + dataLength, &m_params);
         
         // is this a specialized file (contains {%..%} blocks)?
         if (replacer.getBlocks()->getItemsCount() > 0 && replacer.getTemplateFilename() != NULL)
         {
             // this is a specialized file, add blocks as parameters
             addParams(replacer.getBlocks());
             // load template file
             if (FlashFileSystem::find(replacer.getTemplateFilename(), &mimetype, &data, &dataLength))
             {
                 // replace parameters and blocks of template file
                 ParameterReplacer templateReplacer((char const*)data, (char const*)data + dataLength, &m_params);
                 // flush resulting content
                 addContent(templateReplacer.getResult());
                 return;
             }
         }
         else
         {
             // just flush this file (contains only {{...}} blocks)
             addContent(replacer.getResult());
             return;
         }
     }
     // not found
     setStatus(STR_404_Not_Fount);
 }
Example #14
0
    void PureClientContext::m_handleReplaceTree(Json::Value const &nodes) {
        m_gotTree = true;
        OSVR_DEV_VERBOSE("Got updated path tree, processing");
        // reset path tree
        m_pathTree.reset();
        // wipe out handlers in the interface tree
        m_interfaces.clearHandlers();

        // populate path tree from message
        common::jsonToPathTree(m_pathTree, nodes);

        // replace the @localhost with the correct host name
        // in case we are a remote client, otherwise the connection
        // would fail

        LocalhostReplacer replacer(m_host);
        util::traverseWith(m_pathTree.getRoot(),
                           [&replacer](osvr::common::PathNode &node) {
                               common::applyPathNodeVisitor(replacer, node);
                           });

        // re-connect handlers.
        m_connectNeededCallbacks();
    }
Example #15
0
MStatus atomImport::reader(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;

	MString fileName = file.fullName();
#if defined (OSMac_)	
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ifstream animFile(fname);
#else
	ifstream animFile(fileName.asChar());
#endif
	// 	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//

	if(animFile.good()==false)
		return status;
	MString pasteFlags;
	MString	prefix;
	MString	suffix;
	MString	search;
	MString	replace;
	MString	mapFile;
	bool replaceLayers = false;
	MString	exportEditsFile;	
	bool includeChildren = false;
	atomNodeNameReplacer::ReplaceType type = atomNodeNameReplacer::eHierarchy;
	MString templateName;
	MString viewName;
	bool useTemplate = false;

	if (options.length() > 0) {
		//	Set up the flags for the paste command.
		//
		const MString flagSrcTime("srcTime");
		const MString flagDstTime("dstTime");
		const MString flagOldDstTime("time");
		const MString flagCopies("copies");
		const MString flagOption("option");
		const MString flagConnect("connect");
		const MString flagMatch("match");
		const MString flagSearch("search");
		const MString flagReplace("replace");
		const MString flagPrefix("prefix");
		const MString flagSuffix("suffix");
		const MString flagMapFile("mapFile");
		const MString flagHierarchy("hierarchy");
		const MString flagString("string");
		const MString flagSelected("selected");
		const MString flagTemplate("template");
		const MString flagView("view");
		const MString optionChildrenToo("childrenToo");
		const MString optionTemplate("template");
		const MString flagExportEdits("exportEdits");
		MString copyValue;
		MString flagValue;
		MString connectValue;
		MString match;
		MString srcTimeValue;
		MString dstTimeValue;

		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {

			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagCopies && theOption.length() > 1) {
				copyValue = theOption[1];;
			} else if (theOption[0] == flagOption && theOption.length() > 1) {
				flagValue = theOption[1];
			} else if (theOption[0] == flagConnect && theOption.length() > 1) {
				if (theOption[1].asInt() != 0) {
					connectValue += theOption[1];
				}
			} 
			else if( theOption[0] == flagTemplate && theOption.length() > 1)
			{
				templateName = theOption[1];
			}
			else if( theOption[0] == flagView && theOption.length() > 1)
			{
				viewName = theOption[1];
			}
			else if (theOption[0] == flagSrcTime && theOption.length() > 1) {
				srcTimeValue += theOption[1];
			}
			else if ((theOption[0] == flagDstTime || theOption[0] == flagOldDstTime )&& theOption.length() > 1) {
				dstTimeValue += theOption[1];
			}
			else if (theOption[0] == flagMatch && theOption.length() > 1) {
				match =  theOption[1];
			} 
			else if (theOption[0] == flagSearch && theOption.length() > 1) {
				search =  theOption[1];
			} 
			else if (theOption[0] == flagReplace && theOption.length() > 1) {
				replace =  theOption[1];
			} 
			else if (theOption[0] == flagPrefix && theOption.length() > 1) {
				prefix =  theOption[1];
			} 
			else if (theOption[0] == flagSuffix && theOption.length() > 1) {
				suffix =  theOption[1];
			} 
			else if (theOption[0] == flagMapFile && theOption.length() > 1) {
				mapFile =  theOption[1];
			}
			else if (theOption[0] == flagSelected && theOption.length() > 1) {
				includeChildren =   (theOption[1] == optionChildrenToo) ? true : false;
				if(theOption[1] == optionTemplate)
					useTemplate = true;
			}
			else if (theOption[0] == flagExportEdits && theOption.length() > 1) {
				exportEditsFile =  theOption[1];
			}
		}
	
		if (copyValue.length() > 0) {
			pasteFlags += " -copies ";
			pasteFlags += copyValue;
			pasteFlags += " ";
		} 
		if (flagValue.length() > 0) {
			pasteFlags += " -option \"";
			pasteFlags += flagValue;
			pasteFlags += "\" ";
			if(flagValue == MString("replace"))
				replaceLayers = true;
		} 
		if (connectValue.length() > 0) {
			pasteFlags += " -connect ";
			pasteFlags += connectValue;
			pasteFlags += " ";
		} 
		if (dstTimeValue.length() > 0) {
			bool useQuotes = !dstTimeValue.isDouble();
			pasteFlags += " -time ";
			if (useQuotes) pasteFlags += "\"";
			pasteFlags +=  dstTimeValue;
			if (useQuotes) pasteFlags += "\"";
			pasteFlags += " ";
		} 		
		if (srcTimeValue.length() > 0) 
		{
			MTime lClipStartTime;
			MTime lClipEndTime;
			MStringArray lTimes;

			if ( MStatus::kSuccess == srcTimeValue.split( L':', lTimes ) )
			{
				if ( lTimes.length() > 0 )
				{
					double lImportStartFrame = lTimes[0].asDouble();
					double lImportEndFrame   = lImportStartFrame;
					
					if ( lTimes.length() > 1 )
					{
						lImportEndFrame = lTimes[1].asDouble();
					}
					fReader.setImportFrameRange( lImportStartFrame, lImportEndFrame );
				}
				else
				{
					fReader.clearImportFrameRange();
				}
			}
		} 
        else
        {
            fReader.clearImportFrameRange();
        }
		if(match.length() >0)
		{
			if(match == flagHierarchy)
				type = atomNodeNameReplacer::eHierarchy;
			else if(match == flagString)
				type = atomNodeNameReplacer::eSearchReplace;
			else if(match == flagMapFile)
				type = atomNodeNameReplacer::eMapFile;
		} //not set, then we leave what we had

		
	}

	//	If the selection list is empty, there is nothing to import.
	//
	MSelectionList sList;
	std::vector<unsigned int> depths;
	atomTemplateReader templateReader;
	if(useTemplate == true)
	{
		templateReader.setTemplate(templateName,viewName);
		includeChildren = false;
		templateReader.selectNodes(); //make the selection set be us.
	}
	SelectionGetter::getSelectedObjects(includeChildren,sList,depths);
	if (sList.isEmpty()) {
		MString msg = MStringResource::getString(kNothingSelected, status);
		MGlobal::displayError(msg);
		return (MS::kFailure);
	}


	atomNodeNameReplacer replacer(type,sList,depths,prefix,suffix,search,replace,mapFile);
	if (mode == kImportAccessMode) {
		status = importAnim(sList,animFile,pasteFlags,replacer,exportEditsFile,templateReader,replaceLayers);
	}

	animFile.close();
	return status;
}
Example #16
0
// -----------------------------------------------------
// determine if AI should retreat
// -----------------------------------------------------
bool ai_check_retreat( t_battlefield& battlefield )
{
	bool side = battlefield.get_acting_side();

	if (battlefield.get_retreat_checked( side ))
		return false;
	if (!should_retreat( battlefield, side ))
		return false;
	battlefield.set_retreat_checked( side );

	t_player*			player = battlefield.get_player( side );
	t_combat_window*	combat_window = battlefield.get_combat_window();

	if (!player->is_computer())
		return suggest_retreat( battlefield, side );

	if (battlefield.can_surrender( side ))
	{
		int			cost = battlefield.calculate_surrender_cost( side );
		std::string	cost_text = format_string( "%i", cost );
		std::string	text;
		bool		enemy_towns;
		bool		blocked_towns;
		t_town*		town = combat_window->find_nearest_town( side, enemy_towns, blocked_towns );
		t_hero const*	enemy_hero;
		t_hero const*	hero;
		t_skill			skill;
		t_skill			enemy_skill;
		t_hero_keyword_replacer replacer;

		hero = get_charm( battlefield, side, skill );
		enemy_hero = get_charm( battlefield, !side, enemy_skill );
		replacer.add_keyword( "%surrender_cost", cost_text );
		replacer.add_keyword( "%town_name", town->get_name() );

		if (enemy_skill.level < skill.level)
		{
			replacer.add_hero( hero );
			replacer.add_skill( skill );
			text = replacer( k_text_force_surrender );
			ok_dialog( text );
			battlefield.surrender();
			return true;
		}

		text = replacer( k_text_request_surrender );
		if (yes_no_dialog( text, true ))
		{
			battlefield.surrender();
			return true;
		}
	}

	if (!battlefield.can_retreat( side ))
		return false;
	if (side)
		combat_window->force_combat_termination(k_result_defender_retreated);
	else
		combat_window->force_combat_termination(k_result_attacker_retreated);
	return true;
}
Example #17
0
bool processFile(const QString &firstFile, const QString &secondFile)
{

    QFile inputFile(firstFile);
    qDebug() << "The initial file size is: " + QString::number(inputFile.size());
    if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Error: cannot open input file.";
        return false;
    }
    QTextStream inputStream(&inputFile);
    QDomDocument inputSvg;
    QString svgText = prepareSvg(inputStream.readAll());
    inputSvg.setContent(svgText);

    if (inputSvg.elementsByTagName("svg").count() == 0) {
        qDebug() << firstFile;
        qDebug() << "Error: it's a not well-formed SVG file.";
        return false;
    }

    Replacer replacer(inputSvg);
    Remover remover(inputSvg);

    replacer.calcElemAttrCount("initial");

    if (!Keys::get().flag(Key::KeepDefaultAttributes))
        remover.cleanSvgElementAttribute();

    // mandatory fixes used to simplify subsequent functions
    replacer.convertUnits();
    replacer.fixWrongAttr();
    replacer.convertCDATAStyle();
    replacer.prepareDefs();
    replacer.joinStyleAttr();

    if (!Keys::get().flag(Key::NoViewbox))
        replacer.convertSizeToViewbox();
    if (!Keys::get().flag(Key::KeepDuplicatedDefs))
        remover.removeDuplicatedDefs();
    if (!Keys::get().flag(Key::KeepSinglyGradients))
        replacer.mergeGradients();
    remover.removeElements();
    remover.removeAttributes();
    if (!Keys::get().flag(Key::KeepUnusedDefs))
        remover.removeUnusedDefs();
    if (!Keys::get().flag(Key::KeepUnreferencedIds))
        remover.removeUnreferencedIds();
    if (!Keys::get().flag(Key::KeepUnusedXLinks))
        remover.removeUnusedXLinks();
    if (!Keys::get().flag(Key::KeepDefaultAttributes))
        remover.processStyleAttr();
    if (!Keys::get().flag(Key::KeepUnsortedDefs))
        replacer.sortDefs();
    if (!Keys::get().flag(Key::KeepBasicShapes))
        replacer.convertBasicShapes();
    if (!Keys::get().flag(Key::KeepGroups))
        remover.removeGroups();
    if (!Keys::get().flag(Key::KeepAbsolutePaths))
        replacer.processPaths();
    if (!Keys::get().flag(Key::SkipElemByStyleGroup))
        replacer.groupElementsByStyles();
    if (!Keys::get().flag(Key::SkipRoundingNumbers))
        replacer.roundDefs();
    replacer.splitStyleAttr();
    replacer.finalFixes();

    QFile outFile(secondFile);
    if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "Error: could not open out file for write.";
        return false;
    }
    // TODO: check is out file smaller than original
    QTextStream out(&outFile);
    // remove unneeded new lines in text elements, created by default xml format,
    // but wrong in svg
    QString outStr = inputSvg.toString(Keys::get().intNumber(Key::Indent));
    if (!Keys::get().flag(Key::KeepProlog))
        outStr.remove(QRegExp("<\\!DOCTYPE.*\\.dtd('|\")>(\n|)"));
    outStr.replace(">\n<tspan", "><tspan");
    out << outStr;
    outFile.close();

    qDebug() << "The final file size is: " + QString::number(outFile.size());
    replacer.calcElemAttrCount("final");
    return true;
}
FinalRepresentation
IntermediateRepresentator::transform(const TransformationParameters& parameters,
                                     const CompileErrorList& parsingErrors,
                                     MemoryAccess& memoryAccess) {
  auto errors = parsingErrors;
  if (_currentOutput) {
    errors.pushError(_currentOutput->positionInterval(),
                     "Macro not closed. Missing a macro end directive?");
  }

  PrecompileImmutableArguments precompileArguments(parameters.architecture(),
                                                   parameters.generator());

  SymbolGraph graph;
  MacroDirectiveTable macroTable;
  for (const auto& command : _commandList) {
    command->precompile(precompileArguments, errors, graph, macroTable);
  }

  IntermediateMacroInstruction::replaceWithMacros(
      _commandList.begin(), _commandList.end(), macroTable, errors);

  auto macroList = generateMacroInformation();
  auto preliminaryEvaluation = graph.evaluate();

  if (!evaluateGraph(preliminaryEvaluation, errors)) {
    return FinalRepresentation({}, errors, macroList);
  }

  SymbolReplacer preliminaryReplacer(preliminaryEvaluation);

  MemoryAllocator allocator(parameters.allocator());
  SectionTracker tracker;

  auto allowedSize = memoryAccess.getMemorySize().get();
  IntermediateOperationPointer firstMemoryExceedingOperation(nullptr);

  AllocateMemoryImmutableArguments allocateMemoryArguments(precompileArguments,
                                                           preliminaryReplacer);

  for (const auto& command : _commandList) {
    command->allocateMemory(
        allocateMemoryArguments, errors, allocator, tracker);
    if (allocator.estimateSize() > allowedSize &&
        !firstMemoryExceedingOperation) {
      firstMemoryExceedingOperation = command;
    }
  }

  auto allocatedSize = allocator.calculatePositions();

  EnhanceSymbolTableImmutableArguments symbolTableArguments(
      allocateMemoryArguments, allocator);
  for (const auto& command : _commandList) {
    command->enhanceSymbolTable(symbolTableArguments, errors, graph);
  }

  auto graphEvaluation = graph.evaluate();
  auto graphValid = evaluateGraph(graphEvaluation, errors);
  auto memoryValid = checkMemorySize(
      allocatedSize, allowedSize, firstMemoryExceedingOperation, errors);
  if (!(graphValid && memoryValid)) {
    return FinalRepresentation({}, errors, macroList);
  }

  SymbolReplacer replacer(graphEvaluation);
  ExecuteImmutableArguments executeArguments(symbolTableArguments, replacer);
  FinalCommandVector commandOutput;
  for (const auto& command : _commandList) {
    command->execute(executeArguments, errors, commandOutput, memoryAccess);
  }

  return FinalRepresentation(commandOutput, errors, macroList);
}