Returns a Grammar instance (i.e., an object with a `match` method) for `tree`, which is the concrete syntax tree of a user-written grammar. The grammar will be assigned into `namespace` under the name of the grammar as specified in the source.
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();
}
1293221
def const_get_tree(tree)
      if tree.size == 1
        Object.const_get(tree.first)
      else
        tree[1..-1].inject(Object.const_get(tree.first)) { |new_base, part| new_base.const_get(part) }
      end
    rescue
      raise ArgumentError, "Can't figure out command class name from path #{path} - tried #{tree}"
    end
1328599
private Grammar cloneGrammarIntoNewResourceSet(Grammar original) {
		Resource originalResource = original.eResource();
		ResourceSet clonedResourceSet = EcoreUtil2.clone(new XtextResourceSet(), originalResource.getResourceSet());
		Resource clonedResource = clonedResourceSet.getResource(originalResource.getURI(), false);
		Grammar clonedGrammar = (Grammar) clonedResource.getContents().get(0);
		return clonedGrammar;
	}
387002
def get_tree(cls, parent=None):
        
        cls = get_result_class(cls)

        if parent is None:
            # return the entire tree
            return cls.objects.all()
        if parent.is_leaf():
            return cls.objects.filter(pk=parent.pk)
        return cls.objects.filter(
            tree_id=parent.tree_id,
            lft__range=(parent.lft, parent.rgt - 1))
677443
def tree(s, token=[WORD, POS, CHUNK, PNP, REL, LEMMA]):
    
    return Text(s, token)
1308077
function compile(grammar) {
  var compiler     = require('./compiler.js'),
      tree         = compiler.parser.matchAll(grammar, 'topLevel'),
	    parserString = compiler.translator.match(tree, 'trans');
  return parserString;
}
372965
def tree(self, level=0, prefix=''):
        
        text = '%s%s\n' % (prefix, self.value.text)
        prefix = '%s└── ' % ('    ' * level)
        if self._lesser:
            text += self._lesser.tree(level+1, prefix)
        if self._greater:
            text += self._greater.tree(level+1, prefix)
        return text
345848
def make_grammar(allow_errors):
  """"""
  if allow_errors in GRAMMAR_CACHE:
    return GRAMMAR_CACHE[allow_errors]

  tuple = p.Forward()
  catch_errors = p.Forward()
  catch_errors << (p.Regex('[^{};]*') - p.Optional(tuple) - p.Regex('[^;}]*'))

  def swallow_remainder():
    if allow_errors:
      return pattern('swallow_remainder', p.Suppress(catch_errors))
    return p.Empty()

  def swallow_errors(rule):
    """Extend the production rule by potentially eating errors.

    This does not return a p.NoMatch() because that messes up the error messages.
    """
    ret = rule
    if allow_errors:
      # Synchronize on the first semicolon or the first unbalanced closing curly
      ret = rule | pattern('catch_errors', parseWithLocation(p.Suppress(catch_errors), UnparseableNode))
    return ret

  class Grammar:
    keywords = ['and', 'or', 'not', 'if', 'then', 'else', 'include', 'inherit', 'null', 'true', 'false',
        'for', 'in']

    # This is a hack: this condition helps uselessly recursing into the grammar for
    # juxtapositions.
    early_abort_scan = ~p.oneOf([';', ',', ']', '}', 'for' ])

    expression = pattern('expression', p.Forward())

    comment = p.Regex('#') + ~p.FollowedBy(sym('.')) + p.restOfLine
    doc_comment = pattern('doc_comment', (sym('#.') - p.restOfLine))

    quotedIdentifier = pattern('quotedIdentifier', p.QuotedString('`', multiline=False))

    # - Must start with an alphascore
    # - May contain alphanumericscores and special characters such as : and -
    # - Must not end in a special character
    identifier = pattern('identifier', parseWithLocation(quotedIdentifier | p.Regex(r'[a-zA-Z_]([a-zA-Z0-9_:-]*[a-zA-Z0-9_])?'), Identifier))

    # Variable identifier (can't be any of the keywords, which may have lower matching priority)
    variable = pattern('variable', ~p.MatchFirst(p.oneOf(keywords)) + pattern('identifier', parseWithLocation(identifier.copy(), Var)))

    # Contants
    integer = pattern('integer', parseWithLocation(p.Word(p.nums), convertAndMake(int, Literal)))
    floating = pattern('floating', parseWithLocation(p.Regex(r'\d*\.\d+'), convertAndMake(float, Literal)))
    dq_string = pattern('dq_string', parseWithLocation(p.QuotedString('"', escChar='\\', unquoteResults=False, multiline=True), convertAndMake(unquote, Literal)))
    sq_string = pattern('sq_string', parseWithLocation(p.QuotedString("'", escChar='\\', unquoteResults=False, multiline=True), convertAndMake(unquote, Literal)))
    boolean = pattern('boolean', parseWithLocation(p.Keyword('true') | p.Keyword('false'), convertAndMake(mkBool, Literal)))
    null = pattern('null', parseWithLocation(p.Keyword('null'), Null))

    # List
    list_ = pattern('list', parseWithLocation(bracketedList('[', ']', ',', expression), List))

    # Tuple
    inherit = pattern('inherit', (kw('inherit') - p.ZeroOrMore(variable)).setParseAction(inheritNodes))
    schema_spec = pattern('schema_spec', parseWithLocation(p.Optional(p.Keyword('private').setParseAction(lambda: True), default=False)
                  - p.Optional(p.Keyword('required').setParseAction(lambda: True), default=False)
                  - p.Optional(expression, default=any_schema_expr), MemberSchemaNode))
    optional_schema = pattern('optional_schema', p.Optional(p.Suppress(':') - schema_spec, default=no_schema))

    expression_value = pattern('expression_value', sym('=') - swallow_errors(expression))
    void_value = pattern('void_value', parseWithLocation(p.FollowedBy(sym(';') | sym('}')), lambda loc: Void(loc, 'nonameyet')))
    member_value = pattern('member_value', swallow_errors(expression_value | void_value))
    named_member = pattern('named_member', parseWithLocation(identifier - optional_schema - member_value - swallow_remainder(), TupleMemberNode))
    documented_member = pattern('documented_member', parseWithLocation(parseWithLocation(p.ZeroOrMore(doc_comment), DocComment) + named_member, attach_doc_comment))
    tuple_member = early_abort_scan + pattern('tuple_member', swallow_errors(inherit | documented_member) - swallow_remainder())

    ErrorAwareTupleNode = functools.partial(TupleNode, allow_errors)
    tuple_members = pattern('tuple_members', parseWithLocation(listMembers(';', tuple_member), ErrorAwareTupleNode))
    tuple << pattern('tuple', parseWithLocation(bracketedList('{', '}', ';', tuple_member, allow_missing_close=allow_errors), ErrorAwareTupleNode))

    # Argument list will live by itself as a atom. Actually, it's a tuple, but we
    # don't call it that because we use that term for something else already :)
    arg_list = pattern('arg_list', bracketedList('(', ')', ',', expression).setParseAction(ArgList))

    parenthesized_expr = pattern('parenthesized_expr', (sym('(') - expression - ')').setParseAction(head))

    unary_op = pattern('unary_op', (p.oneOf(' '.join(functions.unary_operators.keys())) - expression).setParseAction(mkUnOp))

    if_then_else = pattern('if_then_else', parseWithLocation(kw('if') + expression +
                    kw('then') + expression +
                    kw('else') + expression, Condition))

    list_comprehension = pattern('list_comprehension', parseWithLocation(sym('[') + expression + kw('for') + variable + kw('in') +
        expression + p.Optional(kw('if') + expression) + sym(']'), ListComprehension))


    # We don't allow space-application here
    # Now our grammar is becoming very dirty and hackish
    deref = pattern('deref', p.Forward())
    include = pattern('include', parseWithLocation(kw('include') - deref, Include))

    atom = pattern('atom', (tuple
            | sq_string
            | dq_string
            | variable
            | floating
            | integer
            | boolean
            | list_
            | null
            | unary_op
            | parenthesized_expr
            | if_then_else
            | include
            | list_comprehension
            ))

    # We have two different forms of function application, so they can have 2
    # different precedences. This one: fn(args), which binds stronger than
    # dereferencing (fn(args).attr == (fn(args)).attr)
    applic1 = pattern('applic1', parseWithLocation(atom - p.ZeroOrMore(arg_list), mkApplications))

    # Dereferencing of an expression (obj.bar)
    deref << parseWithLocation(applic1 - p.ZeroOrMore(p.Suppress('.') - swallow_errors(identifier)), mkDerefs)

    # All binary operators at various precedence levels go here:
    # This piece of code does the moral equivalent of:
    #
    #     T = F*F | F/F | F
    #     E = T+T | T-T | T
    #
    # etc.
    term = deref
    for op_level in functions.binary_operators_before_juxtaposition:
      operator_syms = list(op_level.keys())
      term = (term - p.ZeroOrMore(p.oneOf(operator_syms) - term)).setParseAction(mkBinOps)

    # Juxtaposition function application (fn arg), must be 1-arg every time
    applic2 = pattern('applic2', parseWithLocation(term - p.ZeroOrMore(early_abort_scan + term), mkApplications))

    term = applic2
    for op_level in functions.binary_operators_after_juxtaposition:
      operator_syms = list(op_level.keys())
      term = (term - p.ZeroOrMore(p.oneOf(operator_syms) - term)).setParseAction(mkBinOps)

    expression << term

    # Two entry points: start at an arbitrary expression, or expect the top-level
    # scope to be a tuple.
    start = pattern('start', expression.copy().ignore(comment))
    start_tuple = tuple_members.ignore(comment)
  GRAMMAR_CACHE[allow_errors] = Grammar
  return Grammar
1062707
def on_rule(node, compiled_grammar)
      name = process(node.children[0], compiled_grammar)

      if compiled_grammar.has_terminal?(name)
        compiled_grammar.add_error(
          "the rule name #{name.inspect} is already used as a terminal name",
          node.source_line
        )
      end

      if compiled_grammar.has_rule_with_branches?(name)
        compiled_grammar.add_error(
          "the rule #{name.inspect} has already been defined",
          node.source_line
        )

        return
      end

      branches = node.children[1..-1].map do |child|
        process(child, compiled_grammar)
      end

      rule = compiled_grammar.lookup_rule(name)

      rule.branches.concat(branches)
    end
1270361
private static void analyzeNode(TreeGraphNode t, TreeGraphNode root, Collection<GrammaticalRelation> relations) {
    // if (t.numChildren() > 0) {          // don't do leaves
    if (t.isPhrasal()) {    // don't do leaves or preterminals!
      TreeGraphNode tHigh = t.highestNodeWithSameHead();
      for (GrammaticalRelation egr : relations) {
        if (egr.isApplicable(t)) {
          for (Tree u : egr.getRelatedNodes(t, root)) {
            tHigh.addArc(GrammaticalRelation.getAnnotationClass(egr), (TreeGraphNode) u);
          }
        }
      }
      // now recurse into children
      for (TreeGraphNode kid : t.children()) {
        analyzeNode(kid, root, relations);
      }
    }
  }
102720
def compile_pattern(self, input, debug=False, with_tree=False):
        """"""
        tokens = tokenize_wrapper(input)
        try:
            root = self.driver.parse_tokens(tokens, debug=debug)
        except parse.ParseError as e:
            raise PatternSyntaxError(str(e))
        if with_tree:
            return self.compile_node(root), root
        else:
            return self.compile_node(root)
975097
def parse(cls, parser, text, pos):  # pylint: disable=W0613
        """'"""
        if not text.strip():
            return text, SyntaxError("Invalid value")

        class Rule(object):
            grammar = attr('value', SpiresSimpleValue), omit(re.compile(".*"))

        try:
            tree = pypeg2.parse(text, Rule, whitespace="")
        except SyntaxError:
            return text, SyntaxError("Expected %r" % cls)
        else:
            r = tree.value

        if r.value.lower() in ('and', 'or', 'not'):
            return text, SyntaxError("Invalid value %s" % r.value)

        return text[len(r.value):], r
540048
public GrammaticalStructure newGrammaticalStructure(Tree t) {
    try {
      if (puncFilter == null) {
        if (hf == null) {
          return (GrammaticalStructure) con.newInstance(t);
        } else {
          return (GrammaticalStructure) con.newInstance(t, hf);
        }
      } else {
        if (hf == null) {
          return (GrammaticalStructure) con.newInstance(t, puncFilter);
        } else {
          return (GrammaticalStructure) con.newInstance(t, puncFilter, hf);
        }
      }
    } catch (InstantiationException e) {
      throw new RuntimeException("Cannot instantiate " + con.getDeclaringClass().getName(), e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(con.getDeclaringClass().getName() + "(Tree t) does not have public access", e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException("Failed to invoke " + con, e);
    }
  }
798485
def get_tree(cls, parent=None):
        
        cls = get_result_class(cls)

        if parent is None:
            # return the entire tree
            return cls.objects.all()
        if parent.is_leaf():
            return cls.objects.filter(pk=parent.pk)
        return cls.objects.filter(
            path__startswith=parent.path,
            depth__gte=parent.depth
        ).order_by(
            'path'
        )
319706
def to_qtree(self, instring, schema):
        
        root_list = self.to_syntax_tree(instring, schema)
        return qtree_translator.translate(root_list)
157076
function (inside, before, insert, root) {
			root = root || _.languages;
			var grammar = root[inside];
			var ret = {};
				
			for (var token in grammar) {
			
				if (grammar.hasOwnProperty(token)) {
					
					if (token == before) {
					
						for (var newToken in insert) {
						
							if (insert.hasOwnProperty(newToken)) {
								ret[newToken] = insert[newToken];
							}
						}
					}
					
					ret[token] = grammar[token];
				}
			}
			
			return root[inside] = ret;
		}
1204503
def on_rule_prototype(node, compiled_grammar)
      name = process(node.children[0], compiled_grammar)

      return if compiled_grammar.has_rule?(name)

      rule = Rule.new(name, node.source_line)

      compiled_grammar.add_rule(rule)
    end