Creates a string representation of a grammar
973036
function grammarToString(grammarName) {
        return grammarRules(grammarName).map(function (r) { return r.fullName + " <- " + r.definition; }).join('\n');
    }
997923
def dump_grammar(self, out=sys.stdout):
        
        for rule in sorted(self.rule2name.items()):
            out.write("%s\n" % rule2str(rule[0]))
        return
28212
def get_variable_grammar(self):
        
        # Defining a expression for valid word
        word_expr = Word(alphanums + '_' + '-')
        word_expr2 = Word(initChars=printables, excludeChars=['{', '}', ',', ' '])
        name_expr = Suppress('variable') + word_expr + Suppress('{')
        state_expr = ZeroOrMore(word_expr2 + Optional(Suppress(",")))
        # Defining a variable state expression
        variable_state_expr = Suppress('type') + Suppress(word_expr) + Suppress('[') + Suppress(Word(nums)) + \
            Suppress(']') + Suppress('{') + Group(state_expr) + Suppress('}') + Suppress(';')
        # variable states is of the form type description [args] { val1, val2 }; (comma may or may not be present)

        property_expr = Suppress('property') + CharsNotIn(';') + Suppress(';')  # Creating a expr to find property

        return name_expr, variable_state_expr, property_expr
411598
def _ToString(x):
    """"""
    # Some cross-language values for primitives.  This is tested in
    # jsontemplate_test.py.
    if x is None:
        return 'null'
    if isinstance(x, six.string_types):
        return x
    return pprint.pformat(x)
515171
function buildGrammar(match, namespace, optOhmGrammarForTesting) {
  var builder = new Builder();
  var decl;
  var currentRuleName;
  var currentRuleFormals;
  var overriding = false;
  var metaGrammar = optOhmGrammarForTesting || ohmGrammar;

  // A visitor that produces a Grammar instance from the CST.
  var helpers = metaGrammar.createSemantics().addOperation('visit', {
    Grammar: function(n, s, open, rs, close) {
      var grammarName = n.visit();
      decl = builder.newGrammar(grammarName, namespace);
      s.visit();
      rs.visit();
      var g = decl.build();
      g.source = this.source.trimmed();
      if (grammarName in namespace) {
        throw errors.duplicateGrammarDeclaration(g, namespace);
      }
      namespace[grammarName] = g;
      return g;
    },

    SuperGrammar: function(_, n) {
      var superGrammarName = n.visit();
      if (superGrammarName === 'null') {
        decl.withSuperGrammar(null);
      } else {
        if (!namespace || !(superGrammarName in namespace)) {
          throw errors.undeclaredGrammar(superGrammarName, namespace, n.source);
        }
        decl.withSuperGrammar(namespace[superGrammarName]);
      }
    },

    Rule_define: function(n, fs, d, _, b) {
      currentRuleName = n.visit();
      currentRuleFormals = fs.visit()[0] || [];
      // If there is no default start rule yet, set it now. This must be done before visiting
      // the body, because it might contain an inline rule definition.
      if (!decl.defaultStartRule && decl.ensureSuperGrammar() !== Grammar.ProtoBuiltInRules) {
        decl.withDefaultStartRule(currentRuleName);
      }
      var body = b.visit();
      var description = d.visit()[0];
      var source = this.source.trimmed();
      return decl.define(currentRuleName, currentRuleFormals, body, description, source);
    },
    Rule_override: function(n, fs, _, b) {
      currentRuleName = n.visit();
      currentRuleFormals = fs.visit()[0] || [];
      overriding = true;
      var body = b.visit();
      var source = this.source.trimmed();
      var ans = decl.override(currentRuleName, currentRuleFormals, body, null, source);
      overriding = false;
      return ans;
    },
    Rule_extend: function(n, fs, _, b) {
      currentRuleName = n.visit();
      currentRuleFormals = fs.visit()[0] || [];
      var body = b.visit();
      var source = this.source.trimmed();
      var ans = decl.extend(currentRuleName, currentRuleFormals, body, null, source);
      return ans;
    },
    RuleBody: function(_, terms) {
      var args = terms.visit();
      return builder.alt.apply(builder, args).withSource(this.source);
    },

    Formals: function(opointy, fs, cpointy) {
      return fs.visit();
    },

    Params: function(opointy, ps, cpointy) {
      return ps.visit();
    },

    Alt: function(seqs) {
      var args = seqs.visit();
      return builder.alt.apply(builder, args).withSource(this.source);
    },

    TopLevelTerm_inline: function(b, n) {
      var inlineRuleName = currentRuleName + '_' + n.visit();
      var body = b.visit();
      var source = this.source.trimmed();
      var isNewRuleDeclaration =
          !(decl.superGrammar && decl.superGrammar.rules[inlineRuleName]);
      if (overriding && !isNewRuleDeclaration) {
        decl.override(inlineRuleName, currentRuleFormals, body, null, source);
      } else {
        decl.define(inlineRuleName, currentRuleFormals, body, null, source);
      }
      var params = currentRuleFormals.map(function(formal) { return builder.app(formal); });
      return builder.app(inlineRuleName, params).withSource(body.source);
    },

    Seq: function(expr) {
      return builder.seq.apply(builder, expr.visit()).withSource(this.source);
    },

    Iter_star: function(x, _) {
      return builder.star(x.visit()).withSource(this.source);
    },
    Iter_plus: function(x, _) {
      return builder.plus(x.visit()).withSource(this.source);
    },
    Iter_opt: function(x, _) {
      return builder.opt(x.visit()).withSource(this.source);
    },

    Pred_not: function(_, x) {
      return builder.not(x.visit()).withSource(this.source);
    },
    Pred_lookahead: function(_, x) {
      return builder.lookahead(x.visit()).withSource(this.source);
    },

    Lex_lex: function(_, x) {
      return builder.lex(x.visit()).withSource(this.source);
    },

    Base_application: function(rule, ps) {
      return builder.app(rule.visit(), ps.visit()[0] || []).withSource(this.source);
    },
    Base_range: function(from, _, to) {
      return builder.range(from.visit(), to.visit()).withSource(this.source);
    },
    Base_terminal: function(expr) {
      return builder.terminal(expr.visit()).withSource(this.source);
    },
    Base_paren: function(open, x, close) {
      return x.visit();
    },

    ruleDescr: function(open, t, close) {
      return t.visit();
    },
    ruleDescrText: function(_) {
      return this.sourceString.trim();
    },

    caseName: function(_, space1, n, space2, end) {
      return n.visit();
    },

    name: function(first, rest) {
      return this.sourceString;
    },
    nameFirst: function(expr) {},
    nameRest: function(expr) {},

    terminal: function(open, cs, close) {
      return cs.visit().join('');
    },

    oneCharTerminal: function(open, c, close) {
      return c.visit();
    },

    terminalChar: function(_) {
      return common.unescapeChar(this.sourceString);
    },

    escapeChar: function(_) {
      return this.sourceString;
    },

    NonemptyListOf: function(x, _, xs) {
      return [x.visit()].concat(xs.visit());
    },
    EmptyListOf: function() {
      return [];
    },

    _terminal: function() {
      return this.primitiveValue;
    }
  });
  return helpers(match).visit();
}
337338
function createStringifier (pp, spaces) {
  return function stringify (value) {
    var visitor = prettyPrintVisitor(pp, spaces)
    traverse(value, visitor)
    return visitor.result
  }
}
78195
function Grammar(delimiters) {
    this.delimiters = delimiters;

    this.internal = [
      makeEntry("START_IF", "if"),
      makeEntry("ELSE", "else"),
      makeEntry("ELSIF", "elsif"),
      makeEntry("END_IF", "endif"),
      makeEntry("NOT", "not"),
      makeEntry("EQUALITY", "=="),
      makeEntry("NOT_EQUALITY", "!="),
      makeEntry("GREATER_THAN_EQUAL", ">="),
      makeEntry("GREATER_THAN", ">"),
      makeEntry("LESS_THAN_EQUAL", "<="),
      makeEntry("LESS_THAN", "<"),
      makeEntry("START_EACH", "each"),
      makeEntry("END_EACH", "endeach"),
      makeEntry("ASSIGN", "as"),
      makeEntry("PARTIAL", "partial"),
      makeEntry("START_EXTEND", "extend"),
      makeEntry("END_EXTEND", "endextend"),
      makeEntry("MAGIC", ".")
    ];
  }
1086629
function makeStringParser ( s ) {
				var len = s.length;

				return function () {
					var result = null;

					if ( message.substr( pos, len ) === s ) {
						result = s;
						pos += len;
					}

					return result;
				};
			}
820218
function CreateJsonGrammar(myna)  
{
    // Setup a shorthand for the Myna parsing library object
    let m = myna;    

    let g = new function() 
    {
        // These are helper rules, they do not create nodes in the parse tree.  
        this.escapedChar    = m.seq('\\', m.advance);
        this.quoteChar      = m.choice(this.escapedChar, m.notChar('"'));
        this.fraction       = m.seq(".", m.digit.zeroOrMore);    
        this.plusOrMinus    = m.char("+-");
        this.exponent       = m.seq(m.char("eE"), this.plusOrMinus.opt, m.digits); 
        this.comma          = m.char(",").ws;  

        // The following rules create nodes in the abstract syntax tree     
        this.string         = m.doubleQuoted(this.quoteChar.zeroOrMore).ast;
        this.null           = m.keyword("null").ast;
        this.bool           = m.keywords("true", "false").ast;
        this.number         = m.seq(this.plusOrMinus.opt, m.integer, this.fraction.opt, this.exponent.opt).ast;
            
        let _this = this;
        this.value = m.choice(this.string, this.bool, this.null, this.number, 
            // Using a lazy evaluation rule to allow recursive rule definitions  
            m.delay(function() { return m.choice(_this.object, _this.array); 
        }));

        this.array          = m.bracketed(m.delimited(this.value.ws, this.comma)).ast;
        this.pair           = m.seq(this.string, m.ws, ":", m.ws, this.value.ws).ast;
        this.object         = m.braced(m.delimited(this.pair.ws, this.comma)).ast;
    };

    // Register the grammar, providing a name and the default parse rule
    return m.registerGrammar("json", g, g.object);
}
65132
private Grammar getEqualGrammar(Grammar gr) {

		for (Grammar gx : this.grammars) {
			if (gr == gx) {
				// System.out.println("Exactly the same grammar found: " + gx);
				return gx;
			}

			if (isSameGrammarType(gr, gx)) {
				// type of grammar the same

				if (gr.getNumberOfEvents() == gx.getNumberOfEvents()) {
					List<Grammar> handled = new ArrayList<Grammar>();
					if (isEqualGrammar(gr, gx, handled)) {
						// the same grammar found
						// System.out.println("Same grammar found for: " + gx +
						// " == " + gr);
						return gx;
					}
				}
			}

		}

		return null;
	}
589876
def generate_make_string(out_f, max_step):
    """"""
    steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)]

    with Namespace(
        out_f,
        ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl']
    ) as nsp:
        generate_take(out_f, steps, nsp.prefix())

        out_f.write(
            '{0}template <int LenNow, int LenRemaining, char... Cs>\n'
            '{0}struct make_string;\n'
            '\n'
            '{0}template <char... Cs>'
            ' struct make_string<0, 0, Cs...> : string<> {{}};\n'
            .format(nsp.prefix())
        )

        disable_sun = False
        for i in reversed(steps):
            if i > 64 and not disable_sun:
                out_f.write('#ifndef __SUNPRO_CC\n')
                disable_sun = True
            out_f.write(
                '{0}template <int LenRemaining,{1}char... Cs>'
                ' struct make_string<{2},LenRemaining,{3}Cs...> :'
                ' concat<string<{4}>,'
                ' typename make_string<take(LenRemaining),'
                'LenRemaining-take(LenRemaining),Cs...>::type> {{}};\n'
                .format(
                    nsp.prefix(),
                    ''.join('char {0},'.format(n) for n in unique_names(i)),
                    i,
                    ''.join('{0},'.format(n) for n in unique_names(i)),
                    ','.join(unique_names(i))
                )
            )
        if disable_sun:
            out_f.write('#endif\n')
1091877
def _term(g):
    """"""
    all_t = {x for rule in g.rules for x in rule.rhs if isinstance(x, T)}
    t_rules = {t: Rule(NT('__T_%s' % str(t)), [t], weight=0, alias='Term') for t in all_t}
    new_rules = []
    for rule in g.rules:
        if len(rule.rhs) > 1 and any(isinstance(x, T) for x in rule.rhs):
            new_rhs = [t_rules[x].lhs if isinstance(x, T) else x for x in rule.rhs]
            new_rules.append(Rule(rule.lhs, new_rhs, weight=rule.weight, alias=rule.alias))
            new_rules.extend(v for k, v in t_rules.items() if k in rule.rhs)
        else:
            new_rules.append(rule)
    return Grammar(new_rules)
10073
def process_grammars(self, grammars):
        """"""
        for path in self.default_grammars:
            grammars.insert(0, open(os.path.relpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                                 os.path.normcase(path)))))
        for fo in grammars:
            logging.debug("Processing grammar content of %s", fo.name)
            self.set_namespace(os.path.splitext(os.path.basename(fo.name))[0])
            for line in fo:
                self.parse_line(line)
            self.handle_empty_line()
        self.resolve_xref()
        self.calculate_leaf_paths()
1338557
def t_string_NGRAPH(t):
    "
    global __STRING

    P = {' ': 0, "'": 2, '.': 8, ':': 10}
    N = {' ': 0, "'": 1, '.': 4, ':': 5}

    __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])
833785
def fromstring(cls, s, *args, **kwargs):
        
        s = s.replace("\(", "&lparen;")
        s = s.replace("\)", "&rparen;")
        s = s.replace("\[", "&lbrack;")
        s = s.replace("\]", "&rbrack;")
        s = s.replace("\{", "&lcurly;")
        s = s.replace("\}", "&rcurly;")
        p = []
        i = 0
        for m in re.finditer(r"\[.*?\]|\(.*?\)", s):
            # Spaces in a range encapsulated in square brackets are encoded.
            # "[Windows Vista]" is one range, don't split on space.
            p.append(s[i:m.start()])
            p.append(s[m.start():m.end()].replace(" ", "&space;")); i=m.end()
        p.append(s[i:])
        s = "".join(p) 
        s = s.replace("][", "] [")
        s = s.replace(")(", ") (")
        s = s.replace("\|", "&vdash;")
        s = re.sub(r"\s+\|\s+", "|", s)  
        s = re.sub(r"\s+", " ", s)
        s = re.sub(r"\{\s+", "{", s)
        s = re.sub(r"\s+\}", "}", s)
        s = s.split(" ")
        s = [v.replace("&space;"," ") for v in s]
        P = cls([], *args, **kwargs)
        G, O, i = [], [], 0
        for s in s:
            constraint = Constraint.fromstring(s.strip("{}"), taxonomy=kwargs.get("taxonomy", TAXONOMY))
            constraint.index = len(P.sequence)
            P.sequence.append(constraint)
            # Push a new group on the stack if string starts with "{".
            # Parse constraint from string, add it to all open groups.
            # Pop latest group from stack if string ends with "}".
            # Insert groups in opened-first order (i).
            while s.startswith("{"):
                s = s[1:]
                G.append((i, [])); i+=1
                O.append([])
            for g in G:
                g[1].append(constraint)
            while s.endswith("}"):
                s = s[:-1]
                if G: O[G[-1][0]] = G[-1][1]; G.pop()
        P.groups = [g for g in O if g]
        return P
350250
def nl2br(s):
    
    if not isinstance(s, basestring):
        s = str(s)
    s = re.sub(r'\r\n|\r|\n', '\n', s)
    paragraphs = re.split('\n{2,}', s)
    paragraphs = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paragraphs]
    return '\n\n'.join(paragraphs)
633539
function undeclaredGrammar(grammarName, namespace, interval) {
  var message = namespace ?
      'Grammar ' + grammarName + ' is not declared in namespace ' + Namespace.toString(namespace) :
      ' ' + grammarName;
  return createError(message, interval);
}