For each Rule B -> c where c is a known terminal, this function
        searches for B occurences in rules with the form A -> B and sets
        A -> c.
320898
def _check_self_replicate(self, myntr):
        
        # print 'BFS Dictionary Update - Self Replicate'
        find = 0
        for nonterm in self.grammar.grammar_nonterminals_map:
            for i in self.grammar.grammar_nonterminals_map[nonterm]:
                if self.grammar.grammar_rules[i][0] not in self.resolved and not isinstance(
                        self.grammar.grammar_rules[i][1], (set, tuple)) \
                        and self.grammar.grammar_rules[i][1] == myntr:
                    self.resolved[self.grammar.grammar_rules[i][0]] = self.resolved[myntr]
                    if self._checkfinal(self.grammar.grammar_rules[i][0]):
                        return self.resolved[self.grammar.grammar_rules[i][0]]
                    if self.grammar.grammar_rules[i][0] not in self.bfs_queue:
                        self.bfs_queue.append(self.grammar.grammar_rules[i][0])
                    find = 1
        if find == 1:
            return 1
        return 0
1050273
function (ruleObj) {

            if (!ruleObj.rule || (!ruleObj.regex && !ruleObj.message)) {
                // {debug}
                window.Debug.log({
                    'function': '$.alterValidationRules()',
                    'message': 'ERROR - Missing one or multiple parameter(s) {rule, regex, message}'
                });
                window.Debug.print();
                // {/debug}
                return false;
            }

            ruleObj.rule = ruleObj.rule.toUpperCase();

            if (ruleObj.regex) {

                var regex = _buildRegexFromString(ruleObj.regex);

                if (!(regex instanceof RegExp)) {
                    // {debug}
                    window.Debug.log({
                        'function': '$.alterValidationRules(rule)',
                        'arguments': regex.toString(),
                        'message': 'ERROR - Invalid rule'
                    });
                    window.Debug.print();
                    // {/debug}
                    return false;
                }

                _rules[ruleObj.rule] = regex;
            }

            if (ruleObj.message) {
                _messages[ruleObj.rule] = ruleObj.message;
            }

            return true;
        }
402195
function find_rule_global(gender, name, nametype_rulesets, features) {
        if (!features) features = {};
        var tags = [];
        for (var key in features) {
            if (features.hasOwnProperty(key)) tags.push(key);
        }
        if (nametype_rulesets.exceptions) {
            var rule = find_rule_local(
                gender, name, nametype_rulesets.exceptions, true, tags);
            if (rule) return rule;
        }
        return find_rule_local(
            gender, name, nametype_rulesets.suffixes, false, tags);
    }
1336585
function(rule) {
      var ans = arguments[1] !== undefined ? [arguments[1]] : [],
          state;
      while (true) {
        state = this.bt.current_state();
        try { ans.push(rule.call(this)) } 
        catch (f) {
          this.bt.catch_mismatch(f);
          this.bt.restore(state);
          break;
        }
      }
      return ans
    }
881994
function findBeginningAndEnd(cm, symb, inclusive) {
    var cur = cm.getCursor();
    var line = cm.getLine(cur.line);
    var chars = line.split('');
    var start = undefined;
    var end = undefined;
    var firstIndex = chars.indexOf(symb);

    // the decision tree is to always look backwards for the beginning first,
    // but if the cursor is in front of the first instance of the symb,
    // then move the cursor forward
    if (cur.ch < firstIndex) {
      cur.ch = firstIndex;
      cm.setCursor(cur.line, firstIndex+1);
    }
    // otherwise if the cursor is currently on the closing symbol
    else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
      end = cur.ch; // assign end to the current cursor
      --cur.ch; // make sure to look backwards
    }

    // if we're currently on the symbol, we've got a start
    if (chars[cur.ch] == symb && end == null)
      start = cur.ch + 1; // assign start to ahead of the cursor
    else {
      // go backwards to find the start
      for (var i = cur.ch; i > -1 && start == null; i--)
        if (chars[i] == symb) start = i + 1;
    }

    // look forwards for the end symbol
    if (start != null && end == null) {
      for (var i = start, len = chars.length; i < len && end == null; i++) {
        if (chars[i] == symb) end = i;
      }
    }

    // nothing found
    // FIXME still enters insert mode
    if (start == null || end == null) return {
      start: cur, end: cur  
    };

    // include the symbols
    if (inclusive) {
      --start; ++end;
    }

    return {
      start: {line: cur.line, ch: start},
      end: {line: cur.line, ch: end}
    };
  }
532735
function getRule(recognizer, dfa) {
    const description = dfa.decision.toString();
    const ruleIndex = dfa.atnStartState.ruleIndex;

    const ruleNames = recognizer.ruleNames;
    if (ruleIndex < 0 || ruleIndex >= ruleNames.length) {
        return description;
    }
    const ruleName = ruleNames[ruleIndex] || '<unknown>';
    return description + " (" + ruleName + ")";
}
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
815321
function compileRuleset (path, rules) {
  const ruleset = pathParser.parse(path)

  ruleset.rules = {}

  for (const ruleType in rules) {
    ruleset.rules[ruleType] = ruleParser.parse(
      rules[ruleType], ruleset.variables
    )
  }

  return ruleset
}
272816
def _nest_rules(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr):
        
        if c_property == self.construct and rule[MEDIA] == media:
            rule[CODESTR] = c_codestr
            self.manage_children(
                rule, p_selectors, p_parents, p_children, scope, media)
        else:
            c_property = self.apply_vars(
                c_property, rule[CONTEXT], rule[OPTIONS], rule, True)

            c_selectors = self.normalize_selectors(c_property)
            c_selectors, _, c_parents = c_selectors.partition(' extends ')

            better_selectors = set()
            c_selectors = c_selectors.split(',')
            for c_selector in c_selectors:
                for p_selector in p_selectors:
                    if c_selector == self.construct:
                        better_selectors.add(p_selector)
                    elif '&' in c_selector:  # Parent References
                        better_selectors.add(
                            c_selector.replace('&', p_selector))
                    elif p_selector:
                        better_selectors.add(p_selector + ' ' + c_selector)
                    else:
                        better_selectors.add(c_selector)
            better_selectors = ','.join(sorted(better_selectors))

            if c_parents:
                parents = set(p.strip() for p in c_parents.split('&'))
                parents.discard('')
                if parents:
                    better_selectors += ' extends ' + '&'.join(sorted(parents))

            _rule = spawn_rule(rule, codestr=c_codestr, deps=set(), context=rule[CONTEXT].copy(), options=rule[OPTIONS].copy(), selectors=better_selectors, properties=[], final=False, media=media, lineno=c_lineno)

            p_children.appendleft(_rule)
963473
public void updateRuleIndexByBodyPredicate(CQIE rule) {
		for (Function bodyAtom : rule.getBody()) {

			if (bodyAtom.isDataFunction()) {
				Predicate functionSymbol = bodyAtom.getFunctionSymbol();
				if (!ruleIndexByBodyPredicate.containsEntry(functionSymbol, rule)){
					ruleIndexByBodyPredicate.put(functionSymbol, rule);
				}
			} else if (bodyAtom.isAlgebraFunction() || bodyAtom.isOperation()) {
				updateRuleIndexByBodyPredicate_traverseBodyAtom(rule, bodyAtom);
			// BC: should we reintroduce arithmetic functions?
			//} else if (bodyAtom.isArithmeticFunction() || bodyAtom.isDataTypeFunction()){
			} else if (bodyAtom.isDataTypeFunction()){
				continue;
			} else {
				throw new IllegalStateException("Unknown Function");
			}
		}
	}
805920
def find_rule(self, rule):
        """"""
        defrule = lib.EnvFindDefrule(self._env, rule.encode())
        if defrule == ffi.NULL:
            raise LookupError("Rule '%s' not found" % defrule)

        return Rule(self._env, defrule)
480907
def add_stmt(stmt, arg_rules):
    """"""
    (arg, rules) = arg_rules
    stmt_map[stmt] = (arg, rules)
173667
def p_bound_terminal(self, p):
        """"""
        if p[1][0].literal in ['*', '**']:
            p[0] = [_Segment(_BINDING, '$%d' % self.binding_var_count),
                    p[1][0],
                    _Segment(_END_BINDING, '')]
            self.binding_var_count += 1
        else:
            p[0] = p[1]
637148
function findInnerRanges(rule) {
		// rule selector
		var ranges = [rule.nameRange(true)];

		// find nested sections, keep selectors only
		var nestedSections = cssSections.nestedSectionsInRule(rule);
		nestedSections.forEach(function(section) {
			ranges.push(range.create2(section.start, section._selectorEnd));
		});

		// add full property ranges and values
		rule.list().forEach(function(property) {
			ranges = ranges.concat(makePossibleRangesCSS(property));
		});

		ranges = range.sort(ranges);

		// optimize result: remove empty ranges and duplicates
		ranges = ranges.filter(function(item) {
			return !!item.length();
		});
		return utils.unique(ranges, function(item) {
			return item.toString();
		});
	}
55748
function Rule(rules) {
            this.rules = rules;
            // Identifies individual rule
            this.name = "";
            // Identifies the grammar that this rule belongs to 
            this.grammarName = "";
            // Identifies types of rules. Rules can have "types" that are different than the class name
            this.type = "";
            // Used to provide access to the name of the class 
            this.className = "Rule";
            // Indicates whether generated nodes should be added to the abstract syntax tree
            this._createAstNode = false;
            // A parser function, computed in a rule's constructor. If successful returns either the original or a new 
            // ParseState object. If it fails it returns null.
            this.parser = null;
            // A lexer function, computed in a rule's constructor. The lexer may update the ParseState if successful.
            // If it fails it is required that the lexer restore the ParseState index to the previous state. 
            // Lexers should only update the index. 
            this.lexer = null;
        }
1041804
function findClosest(c) {

    if (colorTab === null) return -1;
    var r = (c & 0xFF0000) >> 16;
    var g = (c & 0x00FF00) >> 8;
    var b = (c & 0x0000FF);
    var minpos = 0;
    var dmin = 256 * 256 * 256;
    var len = colorTab.length;

    for (var i = 0; i < len;) {
      var dr = r - (colorTab[i++] & 0xff);
      var dg = g - (colorTab[i++] & 0xff);
      var db = b - (colorTab[i] & 0xff);
      var d = dr * dr + dg * dg + db * db;
      var index = i / 3;
      if (usedEntry[index] && (d < dmin)) {
        dmin = d;
        minpos = index;
      }
      i++;
    }
    return minpos;
  }
1364227
def process_rules(rules, fixed_text, cur = 0, cur_end = 1):
    
    replaced = ''
    # iterate through rules
    for rule in rules:
        matched = False
        # iterate through matches
        for match in rule['matches']:
            matched = process_match(match, fixed_text, cur, cur_end)
            # Break out of loop if we dont' have a match. Here we are
            # trusting avrodict to have listed matches sequentially
            if not matched:
                break
        # If a match is found, stop looping through rules any further
        if matched:
            replaced = rule['replace']
            break

    # if any match has been found return replace value
    if matched:
        return replaced
    else:
        return None