コード例 #1
0
ファイル: nxssetreader.cpp プロジェクト: rforge/phylobase
/**
|	returns the number of indices added.
*/
unsigned NxsSetReader::InterpretTokenAsIndices(NxsToken &token, 
  const NxsLabelToIndicesMapper & mapper, 
  const char * setType, 
  const char * cmdName, 
  NxsUnsignedSet * destination)
	{
	try {
		const std::string t = token.GetToken();
		if (NxsString::case_insensitive_equals(t.c_str(), "ALL"))
			{
			unsigned m = mapper.GetMaxIndex();
			NxsUnsignedSet s;
			for (unsigned i = 0; i <= m; ++i)
				s.insert(i);
			destination->insert(s.begin(), s.end());
			return (unsigned)s.size();
			}
		return mapper.GetIndicesForLabel(t, destination);
		}
	catch (const NxsException & x)
		{
		NxsString errormsg = "Error in the ";
		errormsg << setType << " descriptor of a " << cmdName << " command.\n";
		errormsg += x.msg;
		throw NxsException(errormsg, token);
		}
	catch (...)
		{
		NxsString errormsg = "Expecting a ";
		errormsg << setType << " descriptor (number or label) in the " << cmdName << ".  Encountered ";
		errormsg <<  token.GetToken();
		throw NxsException(errormsg, token);
		}
	}
コード例 #2
0
void NxsTaxaAssociationBlock::Read(
    NxsToken &token) /* the token used to read from `in' */
{
    isEmpty = false;

    DemandEndSemicolon(token, "BEGIN TAXAASSOCIATION");

    for (;; )
    {
        token.GetNextToken();
        NxsBlock::NxsCommandResult res = HandleBasicBlockCommands(token);
        if (res == NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK))
        {
            return;
        }
        if (res != NxsBlock::NxsCommandResult(HANDLED_COMMAND))
        {
            if (token.Equals("TAXA"))
            {
                HandleTaxaCommand(token);
            }
            else if (token.Equals("ASSOCIATES"))
            {
                HandleAssociatesCommand(token);
            }
            else
            {
                SkipCommand(token);
            }
        }
    }
}
コード例 #3
0
ファイル: garlireader.cpp プロジェクト: rekepalli/garli
/*----------------------------------------------------------------------------------------------------------------------
|	Called when the HELP command needs to be parsed from within the GarliReader block.
*/
void GarliReader::HandleHelp(
    NxsToken &token)	/* the token used to read from `in' */
{
    // Retrieve all tokens for this command, stopping only in the event
    // of a semicolon or an unrecognized keyword
    //
    for (;;)
    {
        token.GetNextToken();

        if (token.Equals(";"))
        {
            break;
        }
        else
        {
            errormsg = "Unexpected keyword (";
            errormsg += token.GetToken();
            errormsg += ") encountered reading HELP command";
            throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
        }
    }

    message = "\nExamples of use of available commands:";
    message += "\n  help                     -> shows this message";
    message += "\n  log file=mylog.txt start -> opens log file named mylog.txt";
    message += "\n  log stop                 -> closes current log file";
    message += "\n  exe mydata.nex           -> executes nexus file mydata.nex";
    message += "\n  show                     -> reports on blocks currently stored";
    message += "\n  quit                     -> terminates application";
    message += "\n";
    PrintMessage();
}
コード例 #4
0
ファイル: nxsblock.cpp プロジェクト: beiko-lab/gengis
/*----------------------------------------------------------------------------------------------------------------------
|	Stores the next token as the this->blockid field.
*/
void NxsBlock::HandleBlockIDCommand(NxsToken & token)
	{
	token.GetNextToken();
	if (token.Equals(";"))
		GenerateUnexpectedTokenNxsException(token, "an id for the block");
	blockIDString = token.GetToken();
	DemandEndSemicolon(token, "BLOCKID");
	}
コード例 #5
0
ファイル: nxsblock.cpp プロジェクト: beiko-lab/gengis
*/void NxsBlock::DemandIsAtEquals(NxsToken &token, const char *contextString) const
	{
	if (!token.Equals("="))
		{
		errormsg = "Expecting '=' ";
		if (contextString)
			errormsg.append(contextString);
		errormsg << " but found " << token.GetToken() << " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	}
コード例 #6
0
ファイル: nxstaxablock.cpp プロジェクト: beiko-lab/gengis
/*only used it the linkAPI is enabled*/
void NxsTaxaBlockSurrogate::HandleLinkTaxaCommand(NxsToken & token)
	{
	token.GetNextToken();
	const std::map<std::string, std::string> kv = token.ProcessAsSimpleKeyValuePairs("LINK");
	std::map<std::string, std::string>::const_iterator pairIt = kv.begin();
	for (;pairIt != kv.end(); ++pairIt)
		{
		NxsTaxaBlockAPI *entryTaxa = taxa;
		int entryTaxaLinkStatus = taxaLinkStatus;
		NxsString key(pairIt->first.c_str());
		key.ToUpper();
		NxsString value(pairIt->second.c_str());
		if (key == "TAXA")
			{
			if (taxa && !taxa->GetID().EqualsCaseInsensitive(value))
				{
				if (GetTaxaLinkStatus() & NxsBlock::BLOCK_LINK_USED)
					{
					NxsString errormsg = "LINK to a Taxa block must occur before commands that use a taxa block";
					throw NxsException(errormsg, token);
					}
				SetTaxaBlockPtr(NULL, NxsBlock::BLOCK_LINK_UNINITIALIZED);
				}
			if (!taxa)
				{
				if (!nxsReader)
					{
					NxsString errormsg =  "API Error: No nxsReader during parse in NxsTaxaBlockSurrogate::HandleLinkTaxaCommand";
					throw NxsNCLAPIException(errormsg, token);
					}
				NxsTaxaBlockAPI * cb = nxsReader->GetTaxaBlockByTitle(value.c_str(), NULL);
				if (cb == NULL)
					{
					NxsString errormsg = "Unknown TAXA block (";
					errormsg += value;
					errormsg +=") referred to in the LINK command";
					taxa = entryTaxa;
					taxaLinkStatus = entryTaxaLinkStatus;
					throw NxsException(errormsg, token);
					}
				SetTaxaBlockPtr(cb, NxsBlock::BLOCK_LINK_FROM_LINK_CMD);
				}				
			}
		else
			{
			NxsString errormsg = "Skipping unknown LINK subcommand: ";
			errormsg += pairIt->first.c_str();
			nxsReader->NexusWarnToken(errormsg, NxsReader::SKIPPING_CONTENT_WARNING, token);
			errormsg.clear(); //this token pos will be off a bit.
			}
		}
	}
コード例 #7
0
ファイル: nxsblock.cpp プロジェクト: beiko-lab/gengis
/*----------------------------------------------------------------------------------------------------------------------
| throws a NxsException with the token info for `token` 
| `expected` should fill in the phrase "Expecting ${expected}, but found..."
| expected can be NULL.
|
| Sets this->errormsg
*/
void NxsBlock::GenerateUnexpectedTokenNxsException(NxsToken &token, const char *expected) const
	{
	errormsg = "Unexpected token";
	if (expected)
		{
		errormsg += ". Expecting ";
		errormsg += expected;
		errormsg += ", but found: ";
		}
	else
		{
		errormsg += ": ";
		}
	errormsg += token.GetToken();
	throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
	}
コード例 #8
0
ファイル: nxstoken.cpp プロジェクト: rforge/phylobase
NxsX_UnexpectedEOF::NxsX_UnexpectedEOF(NxsToken &token)
	:NxsException("Unexpected end-of-file", token)
	{
	std::string t = token.GetBlockName();
	NxsString::to_upper(t);
	if (!t.empty())
		msg << " while reading " << t << " block.";
	}
コード例 #9
0
ファイル: nxsunalignedblock.cpp プロジェクト: cdesjardins/ncl
/*!
	Called from HandleMatrix function to read in the next state. Returns true if next token encountered is a comma,
	false otherwise. A comma signals the end of data for the current taxon in an UNALIGNED block.
*/
bool NxsUnalignedBlock::HandleNextState(
  NxsToken & token,			/* is the token used to read from `in' */
  unsigned taxNum,				/* is the row in range [0..ntax) (used for error reporting only) */
  unsigned charNum,				/* is the column (used for error reporting only) */
  NxsDiscreteStateRow & row, const NxsString &nameStr)	/* is the container for storing new state */
	{
	token.SetLabileFlagBit(NxsToken::parentheticalToken);
	token.SetLabileFlagBit(NxsToken::curlyBracketedToken);
	token.SetLabileFlagBit(NxsToken::singleCharacterToken);

	token.GetNextToken();

	if (token.Equals(",") || token.Equals(";"))
		return false;
	const NxsString stateAsNexus = token.GetToken();
	const NxsDiscreteStateCell stateCode = mapper.EncodeNexusStateString(stateAsNexus, token, taxNum, charNum, NULL, nameStr);
	if (charNum < row.size())
		row[charNum] = stateCode;
	else
		{
		while (charNum < row.size())
			row.push_back(NXS_INVALID_STATE_CODE);
		row.push_back(stateCode);
		}
	return true;
	}
コード例 #10
0
ファイル: nxsblock.cpp プロジェクト: beiko-lab/gengis
/*----------------------------------------------------------------------------------------------------------------------
|	Stores the next token as the this->title field.
*/
void NxsBlock::HandleTitleCommand(NxsToken & token)
	{
	token.GetNextToken();
	if (token.Equals(";"))
		GenerateUnexpectedTokenNxsException(token, "a title for the block");
	if (!title.empty() && nexusReader)
		{
		errormsg = "Multiple TITLE commands were encountered the title \"";
		errormsg += title;
		errormsg += "\" will be replaced by \"";
		errormsg += token.GetToken() ;
		errormsg += '\"';
		nexusReader->NexusWarnToken(errormsg, NxsReader::OVERWRITING_CONTENT_WARNING, token);
		errormsg.clear();
		}
	title = token.GetToken();
	autoTitle = false;
	DemandEndSemicolon(token, "TITLE");
	}
コード例 #11
0
ファイル: nxsblock.cpp プロジェクト: beiko-lab/gengis
void NxsBlock::SkipCommand(NxsToken & token)
	{
	if (nexusReader)
		{
		errormsg = "Skipping command: ";
		errormsg << token.GetTokenReference();
		nexusReader->NexusWarnToken(errormsg, NxsReader::SKIPPING_CONTENT_WARNING, token);
		errormsg.clear();
		}
	if (!token.Equals(";"))
		SkippingCommand(token.GetToken());
	if (storeSkippedCommands)
		{
		ProcessedNxsCommand pnc;
		token.ProcessAsCommand(&pnc);
		skippedCommands.push_back(pnc);
		}
	else
		token.ProcessAsCommand(NULL);
	}
コード例 #12
0
ファイル: BlockParams.cpp プロジェクト: pombredanne/exa-bayes
void BlockParams::Read(NxsToken &token)
{
  DemandEndSemicolon(token, "PARAMS");
  nat idCtr = 0; 

  auto catsFound = std::unordered_set<Category>{}; 

  while(true)
    {
      token.GetNextToken();
      NxsBlock::NxsCommandResult res = HandleBasicBlockCommands(token); 

      if (res == NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK))
	return;

      if (res != NxsBlock::NxsCommandResult(HANDLED_COMMAND))
	{	  
	  auto str = token.GetToken(false); 

	  auto cat = CategoryFuns::getCategoryFromLinkLabel(str); 	  
	  parseScheme(token, cat, idCtr); 

	  if(catsFound.find(cat) != catsFound.end())
	    {
	      cerr << "parsing error: found a linking scheme for category  " <<  CategoryFuns::getShortName(cat) << " twice. Aborting." ; 
	      exitFunction(-1, true); 
	    }

	  if( cat == Category::TOPOLOGY)
	    {
	      cerr <<  "not implemented"; 
	      assert(0); 
	    }	    
	}
    }
}
コード例 #13
0
ファイル: nxsunalignedblock.cpp プロジェクト: cdesjardins/ncl
/*!
	Called when DIMENSIONS command needs to be parsed from within the UNALIGNED block. Deals with everything after the
	token DIMENSIONS up to and including the semicolon that terminates the DIMENSIONS command.
*/
void NxsUnalignedBlock::HandleDimensions(
  NxsToken & token)			/* the token used to read from `in' */
	{
	unsigned ntaxRead = 0;
	for (;;)
		{
		token.GetNextToken();
		if (token.Equals("NEWTAXA"))
			newtaxa = true;
		else if (token.Equals("NTAX"))
			{
			DemandEquals(token, "after NTAX in DIMENSIONS command");
			ntaxRead = DemandPositiveInt(token, "NTAX");
			}
		else if (token.Equals(";"))
			break;
		}
	if (newtaxa)
		{
		if (ntaxRead == 0)
			{
			errormsg = "DIMENSIONS command must have an NTAX subcommand when the NEWTAXA option is in effect.";
			throw NxsException(errormsg, token);
			}
		AssureTaxaBlock(createImpliedBlock, token, "Dimensions");
		if (!createImpliedBlock)
			{
			taxa->Reset();
			if (nexusReader)
				nexusReader->RemoveBlockFromUsedBlockList(taxa);
			}
		taxa->SetNtax(ntaxRead);
		nTaxWithData = ntaxRead;
		}
	else
		{
		AssureTaxaBlock(false, token, "Dimensions");
		const unsigned ntaxinblock = taxa->GetNTax();
		if (ntaxinblock == 0)
			{
			errormsg = "A TAXA block must be read before character data, or the DIMENSIONS command must use the NEWTAXA.";
			throw NxsException(errormsg, token);
			}
		if (ntaxinblock < ntaxRead)
			{
			errormsg = "NTAX in UNALIGNED block must be less than or equal to NTAX in TAXA block\nNote: one circumstance that can cause this error is \nforgetting to specify NTAX in DIMENSIONS command when \na TAXA block has not been provided";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		nTaxWithData = (ntaxRead == 0 ? ntaxinblock : ntaxRead);
		}
	}
コード例 #14
0
ファイル: nxstaxablock.cpp プロジェクト: beiko-lab/gengis
void NxsTaxaBlock::HandleTaxLabels(NxsToken &token)
	{
	if (dimNTax == 0) 
		{
		errormsg = "NTAX must be specified before TAXLABELS command";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	taxLabels.clear();
	labelToIndex.clear();
	for (unsigned i = 0; i < dimNTax; i++)
		{
		token.GetNextToken();
		try
			{
			NxsString t = token.GetToken();
			AddTaxonLabel(t);
			}
		catch (const NxsException & x)
			{
			throw NxsException(x.msg, token);
			}
		}
	DemandEndSemicolon(token, "TAXLABELS");
	}
コード例 #15
0
ファイル: nxsblock.cpp プロジェクト: beiko-lab/gengis
/*----------------------------------------------------------------------------------------------------------------------
|	Hook to consolidate the handling of COMMANDS that are common to all blocks (TITLE, BLOCKID, END, ENDBLOCK -- and,
|		evenually, LINK).
|	HandleXYZ() where XYZ is the command name is then called.  
|	Returns NxsCommandResult(HANDLED_COMMAND), NxsCommandResult(HANDLED_COMMAND), or NxsCommandResult(UNKNOWN_COMMAND)
|		to tell the caller whether the command was recognized.
*/
NxsBlock::NxsCommandResult NxsBlock::HandleBasicBlockCommands(NxsToken & token)
	{
	if (token.Equals("TITLE"))
		{
		HandleTitleCommand(token);
		return NxsBlock::NxsCommandResult(HANDLED_COMMAND);
		}
	if (false && token.Equals("BLOCKID")) /*now we are skipping this to put it at the end of blocks*/
		{
		HandleBlockIDCommand(token);
		return NxsBlock::NxsCommandResult(HANDLED_COMMAND);
		}
	if (token.Equals("LINK") && this->ImplementsLinkAPI())
		{
		HandleLinkCommand(token);
		return NxsBlock::NxsCommandResult(HANDLED_COMMAND);
		}
	if (token.Equals("END") || token.Equals("ENDBLOCK"))
		{
		HandleEndblock(token);
		return NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK);
		}
	return NxsBlock::NxsCommandResult(UNKNOWN_COMMAND);
	}
コード例 #16
0
ファイル: nxstaxablock.cpp プロジェクト: cran/rncl
/*! Other than the commands handled by NxsBlock::HandleBasicBlockCommands(), this
	function will deal with Dimensions and call NxsTaxaBlock::HandleTaxLabels()
	to parse the TaxLabels commands.

	All other commands will be skipped
*/
void NxsTaxaBlock::Read(
  NxsToken &token)	/* the token used to read from in */
	{
	Reset();
	isEmpty				= false;
	isUserSupplied		= true;

	DemandEndSemicolon(token, "BEGIN TAXA");

	for (;;)
		{
		token.GetNextToken();
		NxsBlock::NxsCommandResult res = HandleBasicBlockCommands(token);
		if (res == NxsBlock::NxsCommandResult(STOP_PARSING_BLOCK))
			return;
		if (res != NxsBlock::NxsCommandResult(HANDLED_COMMAND))
			{
			if (token.Equals("DIMENSIONS"))
				{
				token.GetNextToken();
				if (!token.Equals("NTAX"))
					{
					errormsg = "Expecting NTAX keyword, but found ";
					errormsg += token.GetToken();
					errormsg += " instead";
					throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
					}
				DemandEquals(token, "after NTAX");
				dimNTax = DemandPositiveInt(token, "NTAX");
				taxLabels.reserve(dimNTax);
				DemandEndSemicolon(token, "DIMENSIONS");
				}	// if (token.Equals("DIMENSIONS"))
			else if (token.Equals("TAXLABELS"))
				HandleTaxLabels(token);
			else
				SkipCommand(token);
			}
		}	// GetNextToken loop
	}
コード例 #17
0
ファイル: basiccmdline.cpp プロジェクト: fmichonneau/ncl
/*----------------------------------------------------------------------------------------------------------------------
	Called whenever a file name needs to be read from either the command line or a file. Expects next token to be "="
	followed by the token representing the file name. Call this function after, say, the keyword "file" has been read
	in the following LOG command:
>
	log file=doofus.txt start replace;
>
	Note that this function will read only the "=doofus.txt " leaving "start replace;" in the stream for reading at
	a later time.
*/
NxsString BASICCMDLINE::GetFileName(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	// Eat the equals sign
	token.GetNextToken();

	if (!token.Equals("="))
		{
		errormsg = "Expecting an equals sign, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	// Now get the filename itself
	token.GetNextToken();

	return token.GetToken();
	}
コード例 #18
0
ファイル: nxsreader.cpp プロジェクト: rforge/phylobase
bool NxsReader::ReadUntilEndblock(NxsToken &token, const std::string & )
	{
	for (;;)
		{
		token.GetNextToken();
		if (token.Equals("END") || token.Equals("ENDBLOCK")) 
			{
			token.GetNextToken();
			if (!token.Equals(";")) 
				{
				std::string errormsg = "Expecting ';' after END or ENDBLOCK command, but found ";
				errormsg += token.GetToken();
				errormsg += " instead";
				NexusError(NxsString(errormsg.c_str()), token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				return false;
				}
			return true;
			}
		}
	}
コード例 #19
0
ファイル: nxstoken.cpp プロジェクト: rforge/phylobase
/*!
	Advances the token, and returns the unsigned int that the token represents

 	Sets errormsg and raises a NxsException on failure.
	`contextString` is used in error messages:
		"Expecting ';' to terminate the ${contextString} command"
*/
void NxsToken::DemandEndSemicolon(NxsToken &token, NxsString & errormsg, const char *contextString)
	{
	token.GetNextToken();
	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' to terminate the ";
		errormsg += contextString;
		errormsg += " command, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	}
コード例 #20
0
ファイル: basiccmdline.cpp プロジェクト: fmichonneau/ncl
/*----------------------------------------------------------------------------------------------------------------------
	Called when the END or ENDBLOCK command needs to be parsed from within the BASICCMDLINE block. Basically just
	checks to make sure the next token in the data file is a semicolon.
*/
void BASICCMDLINE::HandleEndblock(
  NxsToken & token)	/* is the token used to read from `in' */
	{
	// Get the semicolon following END or ENDBLOCK token
	token.GetNextToken();

	if (!token.Equals(";"))
		{
		errormsg = "Expecting ';' to terminate the END or ENDBLOCK command, but found ";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	}
コード例 #21
0
ファイル: nxstoken.cpp プロジェクト: rforge/phylobase
/*----------------------------------------------------------------------------------------------------------------------
|	Advances the token, and returns the unsigned int that the token represents
|
| 	Sets errormsg and raises a NxsException on failure.
|	`contextString` is used in error messages:
|		"${contextString} must be a number greater than 0"
*/
unsigned NxsToken::DemandPositiveInt(NxsToken &token, NxsString & errormsg, const char *contextString)
	{
	token.GetNextToken();
	int i = atoi(token.GetToken().c_str());
	if (i <= 0)
		{
		errormsg.assign(contextString);
		errormsg += " must be a number greater than 0. Found";
		errormsg += token.GetToken();
		errormsg += " instead";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}
	return (unsigned) i;
	}
コード例 #22
0
void NxsTaxaAssociationBlock::HandleTaxaCommand(
    NxsToken &token)
{
    if (!this->nexusReader)
    {
        NxsNCLAPIException("No NxsReader when reading TaxaAssociation block.");
    }

    token.GetNextToken();
    this->firstTaxaBlock = this->ProcessTaxaBlockName(token.GetTokenReference(), token);
    token.GetNextToken();
    if (!token.Equals(","))
    {
        errormsg << "Expecting comma in the TAXA command, found \"" << token.GetTokenReference() << "\".";
        throw NxsException(errormsg, token);
    }
    token.GetNextToken();
    this->secondTaxaBlock = this->ProcessTaxaBlockName(token.GetTokenReference(), token);
    NxsToken::DemandEndSemicolon(token, this->errormsg, "TAXA");
}
コード例 #23
0
void NxsException::addPositionInfo(const NxsToken & t)
{
    pos = t.GetFilePosition();
    line = t.GetFileLine();
    col = t.GetFileColumn();
}
コード例 #24
0
/*! Called internally when the NxsReader has found the correct NxsBlock to read
    a block in a file.

    `token` will be at the block ID.
    `currBlockName` will be the block ID as a string.
    `currentBlock` will be the block reader to be used
    `sourceOfBlock` is the factory  that created the block (or 0L). If sourceOfBlock
        is not NULL then it will be alerted if the block is skipped (BlockSkipped() method)
        or there was an error in the read (BlockError() method). The factory is expected
        to delete the block instances in these cases (NxsReader will not refer to those
        instances again).



    The following steps occur:
        - the EnteringBlock hook is called (if it returns false, the block will be skipped by calling
            NxsReader::SkippingBlock
        - NxsBlock::Reset() is called on the reader block
        - NxsBlock::Read() method of the reader block is called
        - If an exception is generated, the NexusError is called.
        - If no exception is generated by Read then the block is processed:
            - if NxsReader::cullIdenticalTaxaBlocks(true) has been called before Execute and this
                is a repeated TAXA block, the block will be deleted.
            - the BlockReadHook() will store all of the implied blocks
                (by calling NxsBlock::GetImpliedBlocks()) and the block itself.
            - if one of the implied blocks is a repeated TAXA block and
                NxsReader::cullIdenticalTaxaBlocks(true) has been called, then
                the blocks NxsBlock::SwapEquivalentTaxaBlock() method will determine
                whether or not the duplicate taxa block can be deleted.
            - each stored block will generate a call to NxsReader::AddBlockToUsedBlockList()
        - ExitingBlock() is called
        - PostBlockReadingHook() is called
 */
bool NxsReader::ExecuteBlock(NxsToken &token, const NxsString &currBlockName, NxsBlock *currentBlock, NxsBlockFactory * sourceOfBlock)
{
    if (!EnteringBlock(currBlockName))
    {
        SkippingBlock(currBlockName);
        if (sourceOfBlock)
        {
            sourceOfBlock->BlockSkipped(currentBlock);
        }
        if (!ReadUntilEndblock(token, currBlockName))
        {
            token.SetBlockName(0L);
            token.SetEOFAllowed(true);
            return false;
        }
        return true;
    }
    this->RemoveBlockFromUsedBlockList(currentBlock);
    currentBlock->Reset();
    // We need to back up currentBlock, because the Read statement might trigger
    // a recursive call to Execute (if the block contains instructions to execute
    // another file, then the same NxsReader object may be used and any member fields (e.g. currentBlock)
    //	could be trashed.
    //
    bool eofFound = false;
    try
    {
        try
        {
            currentBlock->Read(token);
        }
        catch (NxsX_UnexpectedEOF &eofx)
        {
            if (!currentBlock->TolerateEOFInBlock())
            {
                throw eofx;
            }
            NxsString m;
            m << "Unexpected End of file in " << currBlockName << "block";
            currentBlock->WarnDangerousContent(m, token);
            eofFound = true;
        }
        if (destroyRepeatedTaxaBlocks && currBlockName.EqualsCaseInsensitive("TAXA"))
        {
            NxsTaxaBlockAPI * oldTB = this->GetOriginalTaxaBlock((NxsTaxaBlockAPI *) currentBlock);
            if (oldTB)
            {
                const std::string altTitle = currentBlock->GetTitle();
                this->RegisterAltTitle(oldTB, altTitle);
                if (sourceOfBlock)
                {
                    sourceOfBlock->BlockError(currentBlock);
                }
                return true;
            }
        }
        BlockReadHook(currBlockName, currentBlock, &token);
    }
    catch (NxsException &x)
    {
        NxsString m;
        if (currentBlock->errormsg.length() > 0)
        {
            m = currentBlock->errormsg;
        }
        else
        {
            m = x.msg;
        }
        currentBlock->Reset();
        if (sourceOfBlock != 0)
        {

            sourceOfBlock->BlockError(currentBlock);
        }
        else
        {

            token.SetBlockName(0L);
        }
        token.SetEOFAllowed(true);
        currentBlock = NULL;
        NexusError(m, x.pos, x.line, x.col);
        return false;
    }       // catch (NxsException x)
    ExitingBlock(currBlockName);
    PostBlockReadingHook(*currentBlock);
    return !eofFound;
}
コード例 #25
0
/*! used internally to  do most of the work of Execute() */
void NxsReader::CoreExecutionTasks(
    NxsToken  &token,           /* the token object used to grab NxsReader tokens */
    bool notifyStartStop)       /* if true, ExecuteStarting and ExecuteStopping will be called */
{
    unsigned numSigInts = NxsReader::getNumSignalIntsCaught();
    const bool checkingSignals = NxsReader::getNCLCatchesSignals();

    lastExecuteBlocksInOrder.clear();
    currBlock = NULL;

    NxsString errormsg;
    token.SetEOFAllowed(true);

    try
    {
        token.SetLabileFlagBit(NxsToken::saveCommandComments);
        token.GetNextToken();
    }
    catch (NxsException x)
    {
        NexusError(token.errormsg, 0, 0, 0);
        return;
    }

    if (token.Equals("#NEXUS"))
    {
        token.SetLabileFlagBit(NxsToken::saveCommandComments);
        token.GetNextToken();
    }
    else
    {
        errormsg = "Expecting #NEXUS to be the first token in the file, but found ";
        errormsg += token.GetToken();
        errormsg += " instead";
        /*mth changed this to a warning instead of an error	 because of the large number
            of files that violate this requirement.
         */
        NexusWarn(errormsg,  NxsReader::AMBIGUOUS_CONTENT_WARNING, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
    }

    if (notifyStartStop)
    {
        ExecuteStarting();
    }
    bool keepReading = true;
    for (; keepReading && !token.AtEOF(); )
    {
        if (checkingSignals && NxsReader::getNumSignalIntsCaught() != numSigInts)
        {
            throw NxsSignalCanceledParseException("Reading NEXUS content");
        }
        if (token.Equals("BEGIN"))
        {
            token.SetEOFAllowed(false); /*must exit the block before and EOF*/
            token.GetNextToken();
            token.SetBlockName(token.GetTokenReference().c_str());
            for (currBlock = blockList; currBlock != NULL; currBlock = currBlock->next)
            {
                if (currBlock->CanReadBlockType(token))
                {
                    break;
                }
            }
            NxsString currBlockName = token.GetToken();
            currBlockName.ToUpper();
            NxsBlockFactory * sourceOfBlock = NULL;
            if (currBlock == NULL)
            {
                try
                {
                    currBlock = CreateBlockFromFactories(currBlockName, token, &sourceOfBlock);
                }
                catch (NxsException x)
                {
                    NexusError(x.msg, x.pos, x.line, x.col);
                    token.SetBlockName(0L);
                    token.SetEOFAllowed(true);
                    return;
                }
            }
            if (currBlock == NULL)
            {
                SkippingBlock(currBlockName);
                if (!ReadUntilEndblock(token, currBlockName))
                {
                    token.SetBlockName(0L);
                    token.SetEOFAllowed(true);
                    return;
                }
            }
            else if (currBlock->IsEnabled())
            {
                keepReading = ExecuteBlock(token, currBlockName, currBlock, sourceOfBlock);
            }
            else
            {
                SkippingDisabledBlock(token.GetToken());
                if (sourceOfBlock)
                {
                    sourceOfBlock->BlockSkipped(currBlock);
                }
                if (!ReadUntilEndblock(token, currBlockName))
                {
                    token.SetBlockName(0L);
                    token.SetEOFAllowed(true);
                    return;
                }
            }
            currBlock = NULL;
            token.SetEOFAllowed(true);
            token.SetBlockName(0L);
        }       // if (token.Equals("BEGIN"))
        else if (token.Equals("&SHOWALL"))
        {
            for (NxsBlock*  showBlock = blockList; showBlock != NULL; showBlock = showBlock->next) {
                DebugReportBlock(*showBlock);
            }
        }
        else if (token.Equals("&LEAVE"))
        {
            break;
        }
        if (keepReading)
        {
            token.SetLabileFlagBit(NxsToken::saveCommandComments);
            token.GetNextToken();
        }
    }
    if (notifyStartStop)
    {
        ExecuteStopping();
    }

    currBlock = NULL;
}
コード例 #26
0
void NxsTaxaAssociationBlock::HandleAssociatesCommand(
    NxsToken &token)
{
    if (this->firstTaxaBlock == 0L || this->secondTaxaBlock == 0L)
    {
        errormsg << "Expecting TAXA command to precede an ASSOCIATES command.";
        throw NxsException(errormsg, token);
    }
    token.GetNextToken();
    for (;; )
    {
        std::set<unsigned> fSet;
        while (!token.IsPunctuationToken() || !(token.Equals(";") || token.Equals(",") || token.Equals("/")))
        {
            try {
                this->firstTaxaBlock->GetIndicesForLabel(token.GetTokenReference(), &fSet);
            }
            catch(...)
            {
                errormsg << "Unrecognized taxon \"" << token.GetTokenReference() << "\" in ASSOCIATES command";
                throw NxsException(errormsg, token);
            }
            token.GetNextToken();
        }
        if (!token.Equals("/"))
        {
            errormsg << "Expecting / in ASSOCIATES command, found \"" << token.GetTokenReference() << "\"";
            throw NxsException(errormsg, token);
        }

        if (fSet.empty())
        {
            errormsg << "Expecting taxon labels from the first TAXA block before the / in ASSOCIATES command.";
            throw NxsException(errormsg, token);
        }
        token.GetNextToken();

        std::set<unsigned> sSet;

        while (!token.IsPunctuationToken() || !(token.Equals(";") || token.Equals(",") || token.Equals("/")))
        {
            try {
                this->secondTaxaBlock->GetIndicesForLabel(token.GetTokenReference(), &sSet);
            }
            catch(...)
            {
                errormsg << "Unrecognized taxon \"" << token.GetTokenReference() << "\" in ASSOCIATES command";
                throw NxsException(errormsg, token);
            }
            token.GetNextToken();
        }

        if (!(token.Equals(";") || token.Equals(",")))
        {
            errormsg << "Expecting , or ; in ASSOCIATES command, found \"" << token.GetTokenReference() << "\"";
            throw NxsException(errormsg, token);
        }

        if (sSet.empty())
        {
            errormsg << "Expecting taxon labels from the second TAXA block after the / in ASSOCIATES command.";
            throw NxsException(errormsg, token);
        }

        for (std::set<unsigned>::const_iterator fIt = fSet.begin(); fIt != fSet.end(); ++fIt)
        {
            this->AddAssociation(*fIt, sSet);
        }
        if (token.Equals(";"))
        {
            break;
        }
        token.GetNextToken();
    }
}
コード例 #27
0
ファイル: nxsblock.cpp プロジェクト: beiko-lab/gengis
/*----------------------------------------------------------------------------------------------------------------------
| throws a NxsException with the token info for `token` 
| `expected` should fill in the phrase "Expecting ${expected}, but found..."
| expected can be NULL.
|
| Sets this->errormsg
*/
void NxsBlock::GenerateNxsException(NxsToken &token, const char *message) const
	{
	if (message)
		errormsg = message;
	throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
	}
コード例 #28
0
ファイル: nxstaxablock.cpp プロジェクト: rforge/phylobase
/*----------------------------------------------------------------------------------------------------------------------
|	This function provides the ability to read everything following the block name (which is read by the NxsReader 
|	object) to the end or endblock statement. Characters are read from the input stream in. Overrides the abstract 
|	virtual function in the base class. 
*/
void NxsTaxaBlock::Read(
  NxsToken &token)	/* the token used to read from in */
	{
	ntax				= 0;
	unsigned nominal_ntax	= 0;
	isEmpty				= false;
	isUserSupplied		= true;

	DemandEndSemicolon(token, "BEGIN TAXA");

	for (;;)
		{
		token.GetNextToken();

		if (token.Equals("DIMENSIONS"))
			{
			// This should be the NTAX keyword
			//
			token.GetNextToken(); 

			if (!token.Equals("NTAX"))
				{
				errormsg = "Expecting NTAX keyword, but found ";
				errormsg += token.GetToken();
				errormsg += " instead";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}

			DemandEquals(token, "after NTAX");
			nominal_ntax = DemandPositiveInt(token, "NTAX");
			DemandEndSemicolon(token, "DIMENSIONS");
			}	// if (token.Equals("DIMENSIONS"))

		else if (token.Equals("TAXLABELS")) 
			{
			if (nominal_ntax <= 0) 
				{
				errormsg = "NTAX must be specified before TAXLABELS command";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}

			for (unsigned i = 0; i < nominal_ntax; i++)
				{
				token.GetNextToken();
				//@pol should check to make sure this is not punctuation
				AddTaxonLabel(token.GetToken());
				}
			DemandEndSemicolon(token, "TAXLABELS");
			}	// if (token.Equals("TAXLABELS")) 

		else if (token.Equals("END") || token.Equals("ENDBLOCK"))
			{
			DemandEndSemicolon(token, "ENDBLOCK");
			break;
			}	// if (token.Equals("END") || token.Equals("ENDBLOCK"))

		else
			{
			SkippingCommand(token.GetToken());
			do
				{
				token.GetNextToken();
				}
			while (!token.AtEOF() && !token.Equals(";"));

			if (token.AtEOF())
				{
				errormsg = "Unexpected end of file encountered";
				throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
				}
			}	// token not END, ENDBLOCK, TAXLABELS, or DIMENSIONS
		}	// GetNextToken loop
	}
コード例 #29
0
ファイル: nxstaxablock.cpp プロジェクト: cran/rncl
/* This function is called by derived classes right before they start to parse a command
	that requires a Taxa block.
	If a taxa block has not been set at this point, and one cannot be created then
	a NxsException will be generated.

	This enables lazy initialization of the taxa field.
*/
void NxsTaxaBlockSurrogate::AssureTaxaBlock(bool allocBlock, NxsToken &token, const char *cmd)
	{
	if (!allocBlock)
		{
		if (taxa != NULL)
			return;
		if (!nxsReader)
			{
			NxsString  errormsg =  "API Error: No nxsReader during parse in NxsTaxaBlockSurrogate::AssureTaxaBlock";
			throw NxsNCLAPIException(errormsg, token);
			}
		unsigned nTb;
		NxsTaxaBlockAPI * cb = nxsReader->GetTaxaBlockByTitle(NULL, &nTb);
		if (cb == NULL)
			{
			NxsString errormsg =  "TAXA Block has been not been read, but a ";
			if (cmd)
				errormsg += cmd;
			errormsg += " command (which requires a TAXA block) has been encountered. Either add a TAXA block or (for blocks other than the TREES block) you may use a \"DIMENSIONS NEWTAXA NTAX= ...\" command to introduces taxa.";
			throw NxsException(errormsg, token);
			}
		if (nTb > 1)
			{
			NxsString errormsg =  "Multiple TAXA Blocks have been read (or implied using NEWTAXA in other blocks) and a ";
			if (cmd)
				errormsg += cmd;
			errormsg += " command (which requires a TAXA block) has been encountered";
			std::string bn = token.GetBlockName();
			if (!bn.empty())
				{
				errormsg += " in a ";
				errormsg += bn;
				errormsg += " block.";
				}
			errormsg += ".\nThis can be caused by reading multiple files. It is possible that\neach file is readable separately, but cannot be read unambiguously when read in sequence.\n";
			errormsg += "One way to correct this is to use the\n    TITLE some-unique-name-here ;\ncommand in the TAXA block and an accompanying\n    LINK TAXA=the-unique-title-goes here;\n";
			errormsg += "command to specify which TAXA block is needed.";
			cb->WarnDangerousContent(errormsg, token);
			}
		taxa = cb;
		return;
		}
	if (nxsReader != NULL)
		{
		NxsTaxaBlockFactory * tbf = nxsReader->GetTaxaBlockFactory();
		if (tbf)
			{
			std::string s("TAXA");
			taxa = tbf->GetBlockReaderForID(s, nxsReader, &token);
			ownsTaxaBlock = true;
			passedRefOfOwnedBlock = false;
			taxaLinkStatus = NxsBlock::BLOCK_LINK_TO_IMPLIED_BLOCK;
			}
		}
	if (taxa == NULL)
		{
		taxa = new NxsTaxaBlock();
		ownsTaxaBlock = true;
		passedRefOfOwnedBlock = false;
		taxaLinkStatus = NxsBlock::BLOCK_LINK_TO_IMPLIED_BLOCK;
		}
	}
コード例 #30
0
ファイル: BlockParams.cpp プロジェクト: pombredanne/exa-bayes
void BlockParams::parseScheme(NxsToken& token, Category cat, nat &idCtr)
{
  auto numPart = tralnPtr->getNumberOfPartitions();
  auto partAppeared = std::vector<bool>(numPart, false); 

  token.GetNextToken();
  assert(token.GetToken().EqualsCaseInsensitive("=")); 
  token.GetNextToken();
  assert(token.GetToken().EqualsCaseInsensitive("(")); 

  auto scheme = std::vector<std::vector<nat>>{}; 
  while(not token.GetToken().EqualsCaseInsensitive(")") )
    {
      auto schemePart = std::vector<nat>{}; 
      bool startingNext = true; 
      
      // parse one partition part 
      while( not token.GetToken().EqualsCaseInsensitive(")") 	     
	     && (startingNext || not token.GetToken().EqualsCaseInsensitive(",")) )
	{
	  startingNext = false; 
	  // check if the separation item is an expasion item (-)
	  auto isLinkedRange =  token.GetToken().EqualsCaseInsensitive("-") ; 
	  auto isUnlinkedRange = token.GetToken().EqualsCaseInsensitive(":") ; 

	  token.GetNextToken();
	  nat part = token.GetToken().ConvertToInt();
	  nat start = ( isLinkedRange || isUnlinkedRange )  ? schemePart.back() +1  : part; 
	  nat end = part + 1 ;  

	  for(nat i = start ;  i < end ; ++i )
	    {
	      if(not (i < numPart))
		partitionError(i, numPart); 
	      if(partAppeared.at(i))
		{
		  tout << "error: partition " << i << " occurring twice in the same scheme. Check your parameter-block!" << std::endl; 
		  exitFunction(-1, true); 
		}
	      partAppeared.at(i) = true; 

	      if(isUnlinkedRange)
		{
		  scheme.push_back(schemePart);
		  schemePart = {i}; 
		}
	      else 
		schemePart.push_back(i); 
	    }

	  token.GetNextToken(); 
	}

      scheme.push_back(schemePart); 
    }

  // instantiate the parameters 
  for(auto schemePart : scheme )
    {
      assert(schemePart.size()  > 0 ); 
      parameters.push_back(CategoryFuns::getParameterFromCategory(cat,idCtr,getNumSeen(cat), schemePart, tralnPtr->getNumberOfTaxa()));
      ++idCtr; 
    }
}