本文整理汇总了C++中Grammar类的典型用法代码示例。如果您正苦于以下问题:C++ Grammar类的具体用法?C++ Grammar怎么用?C++ Grammar使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Grammar类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: newGrammar
Grammar* newGrammar(const CHAR* pszGrammarFile)
{
if (!pszGrammarFile)
return NULL;
// Read grammar from binary file
Grammar* pGrammar = new Grammar();
if (!pGrammar->readBinary(pszGrammarFile)) {
#ifdef DEBUG
printf("Unable to read binary grammar file %s\n", pszGrammarFile);
#endif
delete pGrammar;
return NULL;
}
return pGrammar;
}
示例2: gen_aux
void gen_aux(const Grammar& g, const std::string& word, std::list<std::string>& ret)
{
if(!bracketed(word)) {
ret.push_back(word);
}
else {
Grammar::const_iterator it = g.find(word);
if(it == g.end())
throw std::logic_error("empty rule");
const Rule_collection& c = it->second;
const Rule& r = c[nrand(c.size())];
for(Rule::const_iterator i = r.begin(); i != r.end(); ++i)
gen_aux(g, *i, ret);
}
}
示例3: execute
void CylinderRule::execute(Grammar &grammar, Context &context, Shape &shape) {
if (shape.getShapeType() != ST_Prism) {
// La règle ne s'applique que sur un prisme
throw std::runtime_error("build_cylinder can only be used on Prism primitives");
}
Prism const& prism = static_cast<Prism const&>(shape);
std::vector<glm::vec2> const &points = prism.poly.getPoints();
const int n = points.size();
// Find the centroid
glm::vec2 centroid;
for (int i = 0; i < n; i++) {
centroid += points[i];
}
centroid /= n;
glm::vec3 centroid3d(centroid.x, 0, centroid.y);
centroid3d = centroid3d + glm::vec3(0, context.terrain->getHeight(centroid), 0);
// Build a cylinder of center 'centroid' of radius 'radius' and height 'height'
float radius = GRandom.RandomNumber(radius_min, radius_max);
float height = GRandom.RandomNumber(height_min, height_max);
Circle2D circle(radius, centroid3d);
Cylinder cyl(circle, height);
// Successeurs
if (successors.size() != 1) {
throw std::runtime_error("build_cylinder operation must have only one successor");
}
CSymbol *succ = *successors.begin();
grammar.resolve(succ, context, cyl);
}
示例4: LoadTxtEx
/********************************************************************
Читаем из текстового файла секции расширенного описания статьи.
Под расширенным описанием подразумевается список координат-атрибутов,
формы, грамматическая сеть и специфические для производных классов
поля.
*********************************************************************/
void Base_Entry::LoadTxtEx(
Macro_Parser& txtfile,
Grammar& gram
)
{
// *** Считываем описание статьи ***
bool looping = true;
BethToken token;
CP_Array common;
while (looping)
{
if (txtfile.eof())
{
Print_Error(txtfile);
gram.GetIO().merr().printf("End of file has been reached before entry body completely loaded\n");
throw E_ParserError();
}
const BSourceState back = txtfile.tellp();
token = txtfile.read();
if (token.GetToken() == B_CFIGPAREN)
{
// Описание статьи закончено
looping = false;
break;
}
if (token.GetToken() == B_OTRIPAREN)
{
txtfile.seekp(token.GetBegin());
SkipNetSection(txtfile, gram);
continue;
}
if (ProcessSection(txtfile, gram, token))
continue;
txtfile.seekp(back);
if (LoadAttribute(txtfile, gram))
continue;
// Загружаем словоформу.
LoadForm(
txtfile,
gram,
common,
GramCoordAdr(UNKNOWN, UNKNOWN),
UNKNOWN,
GramCoordAdr(UNKNOWN, UNKNOWN),
UNKNOWN,
UNKNOWN
);
} // конец цикла считывания описания статьи
return;
}
示例5: normalize
//===========================================================================
static void normalize(
Element & rule,
Element const * parent,
Grammar & rules
) {
if (rule.elements.size() == 1) {
Element & elem = rule.elements.front();
if (elem.type != Element::kTerminal
|| parent && parent->type == Element::kChoice && rule.m == 1
&& rule.n == 1) {
rule.m *= elem.m;
rule.n = max({rule.n, elem.n, rule.n * elem.n});
rule.type = elem.type;
rule.value = elem.value;
vector<Element> tmp{move(elem.elements)};
rule.elements = move(tmp);
return normalize(rule, parent, rules);
}
}
if (rule.eventName.size())
rule.eventRule = rules.eventAlways(rule.eventName);
for (auto && elem : rule.elements)
normalize(elem, &rule, rules);
switch (rule.type) {
case Element::kChoice: normalizeChoice(rule); break;
case Element::kSequence: normalizeSequence(rule); break;
case Element::kRule: normalizeRule(rule, rules); break;
case Element::kTerminal: break;
}
}
示例6: grammar
SAWYER_EXPORT std::string
IfEq::eval(const Grammar &grammar, const std::vector<std::string> &args) {
ASSERT_require(args.size() == 4);
std::string v1 = grammar.unescape(args[0]);
std::string v2 = grammar.unescape(args[1]);
return grammar(v1==v2 ? args[2] : args[3]);
}
示例7: ReadAdditionalInfo
void SG_DeclensionForm::ReadAdditionalInfo( Grammar &gram, const SG_DeclensionTable &table, Macro_Parser& txtfile )
{
// :: flexer рег_выражение for регулярное_выражение
while( !txtfile.eof() )
{
BethToken t = txtfile.read();
if( t==B_FOR )
{
UFString re = strip_quotes( txtfile.read().string() ).c_str();
if( table.GetClass()!=UNKNOWN )
{
const SG_Class &cls = (const SG_Class&)gram.classes()[ table.GetClass() ];
const int id_lang = cls.GetLanguage();
if( id_lang!=UNKNOWN )
{
const SG_Language &lang = gram.GetDict().GetSynGram().languages()[id_lang];
lang.SubstParadigmPattern(re);
}
}
condition_str = re;
condition = boost::wregex( re.c_str(), boost::basic_regex<wchar_t>::icase );
valid_condition = true;
}
else if( t==B_FLEXER )
{
UFString re = strip_quotes( txtfile.read().string() ).c_str();
flexer_flags_str = re;
flexer_flags = boost::wregex( re.c_str(), boost::basic_regex<wchar_t>::icase );
valid_flexer_flags = true;
}
else
{
txtfile.seekp(t);
break;
}
}
return;
}
示例8: processOptions
//===========================================================================
bool processOptions(Grammar & rules) {
if (!*rules.optionString(kOptionRoot)) {
logMsgError() << "Option not found, " << kOptionRoot;
return false;
}
string prefix = rules.optionString(kOptionApiPrefix);
if (prefix.empty()) {
logMsgError() << "Option not found, " << kOptionApiPrefix;
return false;
}
ensureOption(rules, kOptionApiParserClass, prefix + "Parser");
ensureOption(rules, kOptionApiBaseClass, prefix + "ParserBase");
auto & f = use_facet<ctype<char>>(locale());
f.tolower(prefix.data(), prefix.data() + prefix.size());
ensureOption(rules, kOptionApiParserHeader, prefix + "parse.h");
ensureOption(rules, kOptionApiParserCpp, prefix + "parse.cpp");
ensureOption(rules, kOptionApiBaseHeader, prefix + "parsebase.h");
return true;
}
示例9:
boost::shared_ptr<Shape> ShapeLOperator::apply(boost::shared_ptr<Shape>& shape, const Grammar& grammar, std::list<boost::shared_ptr<Shape> >& stack) {
float actual_frontWidth;
float actual_leftWidth;
if (frontWidth.type == Value::TYPE_RELATIVE) {
actual_frontWidth = shape->_scope.x * grammar.evalFloat(frontWidth.value, shape);
}
else {
actual_frontWidth = shape->_scope.x * grammar.evalFloat(frontWidth.value, shape);
}
if (leftWidth.type == Value::TYPE_RELATIVE) {
actual_leftWidth = shape->_scope.y * grammar.evalFloat(leftWidth.value, shape);
}
else {
actual_leftWidth = shape->_scope.y * grammar.evalFloat(leftWidth.value, shape);
}
return shape->shapeL(shape->_name, actual_frontWidth, actual_leftWidth);
}
示例10: CheckAttr
/*********************************************************************
Все атрибуты должны быть определены! Метод вызывается после чтения
тела описания Статьи.
**********************************************************************/
void Base_Entry::CheckAttr(Macro_Parser& txtfile, Grammar& gram)
{
if (is_quantor(GetClass()))
return;
const GramClass& cl = gram.classes()[GetClass()];
const int na = CastSizeToInt(cl.attrs().size());
for (int i = 0; i < na; i++)
{
const GramCoordAdr iglob = cl.attrs()[i];
const GramClass &cls = gram.classes()[GetClass()];
if (GetAttrState(iglob) == UNKNOWN)
{
lem::zbool def_unk;
for (lem::Container::size_type j = 0; j < cl.attr_defaults.size(); ++j)
{
if (cl.attr_defaults[j].first == iglob && cl.attr_defaults[j].second == UNKNOWN)
{
def_unk = true;
break;
}
}
if (!def_unk)
{
// Состояние аттрибута не определено!
Print_Error(txtfile);
gram.GetIO().merr().printf(
"Not defined attribute [%us] state\n",
gram.coords()[iglob.GetIndex()].GetName()[iglob.GetVar()].c_str()
);
throw E_ParserError();
}
}
}
return;
}
示例11: copyRules
//===========================================================================
bool copyRules(
Grammar & out,
Grammar const & src,
string_view rootname,
bool failIfExists
) {
auto root = src.element(rootname);
if (!root) {
logMsgError() << "Rule not found, " << rootname;
return false;
}
auto & rules = const_cast<set<Element> &>(out.rules());
auto ib = rules.insert(*root);
if (!ib.second) {
if (failIfExists) {
logMsgError() << "Rule already exists, " << rootname;
return false;
}
return true;
}
auto & elem = *ib.first;
if ((elem.flags & Element::fFunction)
&& (elem.flags & Element::fCharEvents)
) {
logMsgError() << "Rule with both Function and Char, " << elem.value;
return false;
}
if ((elem.flags & Element::fStartEvents) == Element::fStartEvents) {
logMsgError() << "Rule with both Start and Start+, " << elem.value;
return false;
}
if ((elem.flags & Element::fEndEvents) == Element::fEndEvents) {
logMsgError() << "Rule with both End and End+, " << elem.value;
return false;
}
if ((elem.flags & Element::fCharEvents) == Element::fCharEvents) {
logMsgError() << "Rule with both Char and Char+, " << elem.value;
return false;
}
return copyRequiredDeps(out, src, elem);
}
示例12: gen_aux
void gen_aux(const Grammar& g, const string& word, vector<string>& ret)
{
if (!bracketed(word)) {
ret.push_back(word);
} else {
// locate the rule that corresponds to the word
Grammar::const_iterator it = g.find(word);
if (it == g.end())
throw logic_error("empty rule");
// fetch the set of possible rules
const Rule_collection& c = it->second;
// from which we select one at random
const Rule& r = c[nrand(c.size())];
// recursively expand the selected rule
for (Rule::const_iterator i = r.begin(); i != r.end(); ++i)
gen_aux(g, *i, ret);
}
}
示例13: Grammar
Grammar *read_rule_set(string file) {
Grammar *grammar = new Grammar();
ifstream in_file;
in_file.open(file.c_str());
if (in_file.is_open()) {
int rule_num;
while (in_file >> rule_num) {
string X, blank, Y, Z;
bool is_unary;
int dir;
in_file >> is_unary;
if (!is_unary) {
in_file >> X >> Y >> Z >> dir;
int nt_X = grammar->to_nonterm(X);
int nt_Y = grammar->to_nonterm(Y);
int nt_Z = grammar->to_nonterm(Z);
BinaryRule rule(rule_num, nt_X, nt_Y, nt_Z, dir);
grammar->add_rule(rule);
} else {
示例14: gen_aux
void
gen_aux (const Grammar &g, const std::string &word, std::vector<std::string> &result)
{
if (!bracketed (word))
{
result.push_back (word);
}
else
{
Grammar::const_iterator it = g.find (word);
if (g.end() == it)
throw std::logic_error ("empty grammar rule");
const RuleCollection &rc = it->second;
const Rule &r = rc[nrand(rc.size())];
for (Rule::const_iterator r_it = r.begin(); r_it != r.end(); ++r_it)
gen_aux (g, *r_it, result);
}
}
示例15: PrintActionsNames
static void PrintActionsNames(std::wostream& os, Grammar& g, bool virt)
{
os << L"//\n";
os << L"const char* " << g.GetLanguageName() << L"_Actions_Text(";
os << L"" << g.GetLanguageName() << L"_Actions e)\n";
os << L"{\n";
os << L" switch(e)\n";
os << L" {\n";
for (int i = 0; i < g.GetNumberOfActions(); i++)
{
os << L" case " << g.GetActionName(i) << L": return \"" << g.GetActionName(i) << L"\";\n";
}
os << L" }\n";
os << L" return \"\";\n";
os << L"};\n";
}