#  @-rule aliasing.
195038
protected function aliasAtRules()
    {
        if (empty($this->aliases['at-rules'])) {

            return;
        }

        $aliases = $this->aliases['at-rules'];
        $regex = Regex::$patt;

        foreach ($aliases as $at_rule => $at_rule_aliases) {

            $matches = $this->string->matchAll("~@$at_rule" . '[\s{]~i');

            // Find at-rules that we want to alias.
            while ($match = array_pop($matches)) {

                $curly_match = new BalancedMatch($this->string, $match[0][1]);

                if (! $curly_match->match) {
                    // Couldn't match the block.
                    continue;
                }

                // Build up string with aliased blocks for splicing.
                $original_block = $curly_match->whole();
                $new_blocks = [];

                foreach ($at_rule_aliases as $alias) {

                    // Copy original block, replacing at-rule with alias name.
                    $copy_block = str_replace("@$at_rule", "@$alias", $original_block);

                    // Aliases are nearly always prefixed, capture the current vendor name.
                    preg_match($regex->vendorPrefix, $alias, $vendor);

                    $vendor = $vendor ? $vendor[1] : null;

                    // Duplicate rules.
                    if (preg_match_all($regex->r_token, $copy_block, $copy_matches)) {

                        $originals = [];
                        $replacements = [];

                        foreach ($copy_matches[0] as $rule_label) {

                            // Clone the matched rule.
                            $originals[] = $rule_label;
                            $clone_rule = clone $this->tokens->get($rule_label);

                            $clone_rule->vendorContext = $vendor;

                            // Store the clone.
                            $replacements[] = $this->tokens->add($clone_rule);
                        }

                        // Finally replace the original labels with the cloned rule labels.
                        $copy_block = str_replace($originals, $replacements, $copy_block);
                    }

                    // Add the copied block to the stack.
                    $new_blocks[] = $copy_block;
                }

                // The original version is always pushed last in the list.
                $new_blocks[] = $original_block;

                // Splice in the blocks.
                $curly_match->replace(implode("\n", $new_blocks));
            }
        }
    }
242243
def _bin(g):
    """"""
    new_rules = []
    for rule in g.rules:
        if len(rule.rhs) > 2:
            new_rules += _split(rule)
        else:
            new_rules.append(rule)
    return Grammar(new_rules)
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
57505
function Rule (subrules, type, handler, props, groupProps, encoding) {
  var self = this
  var n = subrules.length

  this.props = props

  this.debug = false

  // Used for cloning
  this.subrules = subrules

  // Required by Atok#_resolveRules
  for (var p in groupProps)
    this[p] = groupProps[p]

  // Runtime values for continue props
  this.continue = this.props.continue[0]
  this.continueOnFail = this.props.continue[1]

  this.type = type
  this.handler = handler

  // For debug
  this.prevHandler = null
  this.id = this.type !== null ? this.type : handler
  // Id for debug
  this._id = (handler !== null ? (handler.name || '#emit()') : this.type)

  // Subrule pattern index that matched (-1 if only 1 pattern)
  this.idx = -1

  // Single subrule: special case for trimRight
  this.single = (n === 1)

  // First subrule
  var subrule = this.first = n > 0
    ? SubRule.firstSubRule( subrules[0], this.props, encoding, this.single )
    // Special case: no rule given -> passthrough
    : SubRule.emptySubRule

  // Special case: one empty rule -> tokenize whole buffer
  if (n === 1 && subrule.length === 0) {
    subrule = this.first = SubRule.allSubRule
    // Make infinite loop detection ignore this
    this.length = -1
  } else {
    // First subrule pattern length (max of all patterns if many)
    // - used in infinite loop detection
    this.length = this.first.length
  }

  // Instantiate and link the subrules
  // { test: {Function}
  // , next: {SubRule|undefined}
  // }
  var prev = subrule
  // Many subrules or none
  for (var i = 1; i < n; i++) {
    subrule = SubRule.SubRule( subrules[i], this.props, encoding )
    prev.next = subrule
    subrule.prev = prev // Useful in some edge cases
    prev = subrule
    if (this.length < subrule.length) this.length = subrule.length
  }

  // Last subrule (used for trimRight and matched idx)
  this.last = subrule

  // Set the first and last subrules length based on trim properties
  if (!this.props.trimLeft) this.first.length = 0
  if (!this.single && !this.props.trimRight) this.last.length = 0

  this.next = null
  this.nextFail = null
  this.currentRule = null
}
818484
function standardizeRule( rule ) {
		rule.elements = convertValidatorToHash( rule.elements, /\s+/ ) || null;
		rule.propertiesOnly = rule.propertiesOnly || ( rule.elements === true );

		var delim = /\s*,\s*/,
			i;

		for ( i in validators ) {
			rule[ i ] = convertValidatorToHash( rule[ i ], delim ) || null;
			rule[ validatorsRequired[ i ] ] = extractRequired( convertValidatorToHash(
				rule[ validatorsRequired[ i ] ], delim ), rule[ i ] ) || null;
		}

		rule.match = rule.match || null;
	}
145907
public function setupRules()
    {
        $this->rules->addMany([
            'call' => new Rule(new RegexMatcher(
                '/(?>(?<![^\\\]\\\)(?<=\n|\(|\)|\||;|`|^|do|if|then|else|fi|esac|done\$\(|^\$\s)\s*\b(\w+))(?!\s*=)/i'
            ), ['priority' => 1, 'context' => ['*none', '*expression']]),

            'comment' => new Rule(new CommentMatcher(['#'])),
            'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"']),

            'keyword' => new Rule(new WordMatcher([
                'if', 'then', 'else', 'elif', 'fi', 'case', 'esac', 'for', 'select', 'while', 'until', 'do', 'done',
                'in', 'function', 'time', 'coproc'
            ]), ['priority' => 3]),

            'variable'  => [
                'assign' => new Rule(new RegexMatcher('/(\w+)[+-]?=/')),
                new Rule(new RegexMatcher('/(\$\w+)/i'), ['context' => ['*none', '*string.double']]),
                'special'  => new Rule(new RegexMatcher('/(\$[#@_])/i'), ['context' => ['*none', '*string.double']]),
                'argument' => new Rule(new RegexMatcher('/(\$\d+)/i'), ['context' => ['*none', '*string.double']]),
                new Rule(new RegexMatcher('/\$\{(\w+)(.*?)\}/i', [ 1 => Token::NAME, 2 => 'string' ]), ['context' => ['*none', '*string.double']])
            ],

            'number'    => new Rule(new RegexMatcher('/(-?(?:0[0-7]+|0[xX][0-9a-fA-F]+|0b[01]+|\d+))/')),
            'delimiter' => new Rule(new RegexMatcher('/^(\$)/m')),

            'symbol.parameter' => new Rule(new RegexMatcher('/[\s|](-{1,2}[\w-]+=?)\b/i'), [
                'priority' => 0,
                'context'  => ['!string', '!comment', '!call']
            ]),

            'expression' => [
                new Rule(new RegexMatcher('/(?=(\$\(((?>[^$()]+|(?1))+)\)))/x'), [
                    'context' => Validator::everywhere(),
                    'factory' => new TokenFactory(LanguageToken::class),
                    'inject'  => $this
                ]),
            ],

            'operator.escape' => new Rule(new RegexMatcher('/(\\\(?:x[0-9a-fA-F]{1,2}|u\{[0-9a-fA-F]{1,6}\}|[0-7]{1,3}|.))/i'), [
                'context' => ['*']
            ]),
        ]);
    }
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;
        }
1200201
public void alias( Object ...args ) {
        if( args.length % 2 == 1 )
            throw new RuntimeException("Even number of arguments expected");

        for (int i = 0; i < args.length; i += 2) {
            aliasGeneric( args[i], (String)args[i+1]);
        }
    }
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
243859
private function _checkAliases($text) {
		if ($this->_isActive('checkAliases')) {
			$key = strtolower($text);
			if (array_key_exists($key, $this->_aliasedFunctions)) {
				$msg = $this->_getMessage('ALIASED_FUNCTION', $this->_aliasedFunctions[$key]['old'], $this->_aliasedFunctions[$key]['new']);
				$this->_writeError('checkAliases', $msg);
			}
		}
	}
4629
private void updateRuleIndexes(CQIE rule) {
		Function head = rule.getHead();
		ruleIndex.put(head.getFunctionSymbol(), rule);
		updateRuleIndexByBodyPredicate(rule);
	}
137436
static function &aliasTable()
    {
        $aliasTable =& $GLOBALS['eZCharsetInfoTable'];
        if ( !is_array( $aliasTable ) )
        {
            $aliasTable = array( 'ascii' => 'us-ascii',
                                 'latin1' => 'iso-8859-1',
                                 'latin2' => 'iso-8859-2',
                                 'latin3' => 'iso-8859-3',
                                 'latin4' => 'iso-8859-4',
                                 'latin5' => 'iso-8859-9',
                                 'latin6' => 'iso-8859-10',
                                 'latin7' => 'iso-8859-13',
                                 'latin8' => 'iso-8859-14',
                                 'latin9' => 'iso-8859-15',
                                 'cyrillic' => 'iso-8859-5',
                                 'arabic' => 'iso-8859-6',
                                 'greek' => 'iso-8859-7',
                                 'hebrew' => 'iso-8859-8',
                                 'thai' => 'iso-8859-11',

                                 'koi8-r' => 'koi8-r',
                                 'koi-8-r' => 'koi8-r',
                                 'koi8r' => 'koi8-r',

                                 'koi8-u' => 'koi8-u',
                                 'koi-8-u' => 'koi8-u',
                                 'koi8u' => 'koi8-u',

                                 'cp1250' => 'windows-1250',
                                 'cp1251' => 'windows-1251',
                                 'cp1252' => 'windows-1252',
                                 'cp1253' => 'windows-1253',
                                 'cp1254' => 'windows-1254',
                                 'cp1255' => 'windows-1255',
                                 'cp1256' => 'windows-1256',
                                 'cp1257' => 'windows-1257',
                                 'cp1258' => 'windows-1258',
                                 'winlatin1' => 'windows-1252',
                                 'winlatin2' => 'windows-1250',
                                 'wincyrillic' => 'windows-1251',
                                 'wingreek' => 'windows-1253',
                                 'winturkish' => 'windows-1254',
                                 'winhebrew' => 'windows-1255',
                                 'winarabic' => 'windows-1256',
                                 'winbaltic' => 'windows-1257',
                                 'winvietnamese' => 'windows-1258',

                                 'doslatinus' => 'cp437',
                                 'dosgreek' => 'cp737',
                                 'dosbaltrim' => 'cp775',
                                 'doslatin1' => 'cp850',
                                 'doslatin2' => 'cp852',
                                 'doscyrillic' => 'cp855',
                                 'dosturkish' => 'cp857',
                                 'dosportuguese' => 'cp860',
                                 'dosicelandic' => 'cp861',
                                 'doshebrew' => 'cp862',
                                 'doscanadaf' => 'cp863',
                                 'dosarabic' => 'cp864',
                                 'dosnordic' => 'cp865',
                                 'dosgreek2' => 'cp869',
                                 'doscyrillicrussian' => 'cp866',
                                 'dosthai' => 'cp874',

                                 'macroman' => 'macintosh',
                                 'nextstep' => 'next',

                                 'utf8' => 'utf-8',
                                 'utf7' => 'utf-7',

                                 'utf16' => 'utf-16',
                                 'utf16be' => 'utf-16be',
                                 'utf16le' => 'utf-16le',

                                 'utf32' => 'utf-32',
                                 'utf32be' => 'utf-32be',
                                 'utf32le' => 'utf-32le',

                                 'ucs4' => 'ucs-4',
                                 'ucs4be' => 'ucs-4be',
                                 'ucs4le' => 'ucs-4le',

                                 'ucs2' => 'ucs-2',
                                 'ucs2be' => 'ucs-2be',
                                 'ucs2le' => 'ucs-2le',

                                 'shift-jis' => 'cp932',
                                 'gbk' => 'gbk',
                                 'euc-cn' => 'euc-cn',
                                 'unifiedhangul' => 'cp849',
                                 'uhc' => 'cp849',
                                 'big5' => 'cp850'
                                 );
            for ( $i = 1; $i <= 15; ++$i )
            {
                $aliasTable["iso8859-$i"] = "iso-8859-$i";
                $aliasTable["iso8859$i"] = "iso-8859-$i";
            }
            $aliasTable['unicode'] = 'unicode';
        }
        return $aliasTable;
    }
782501
function reportUnusedRules( ast, session, options ) {

    const used = {};
    function yes( node ) {

        used[ node.name || node ] = true;

    }

    options.allowedStartRules.forEach( yes );
    session.buildVisitor( { rule_ref: yes } )( ast );

    ast.rules.forEach( rule => {

        if ( used[ rule.name ] !== true ) {

            session.warn(
                `Rule "${ rule.name }" is not referenced.`,
                rule.location
            );

        }

    } );

}
500435
public function getAliases() {
        $result = [];

        foreach ($this->rules as $name => $rule) {
            if (!empty($rule['aliasOf']) && $rule['aliasOf'] === $this->currentRuleName) {
                $result[] = $name;
            }
        }

        return $result;
    }
1342937
private function parseRule($rule) {
		$parsed = [false];
		if (preg_match('#^([a-z][a-z\d_]+)\s*\((.+)\)\s*$#i', $rule, $ms)) {
			$method = trim($ms[1]);
			$ops    = trim($ms[2]);
		} else {
			$method = trim($rule);
			$ops    = '';
		}
		$parsed[0] = $method;
		$parsed[1] = $ops;

		return $parsed;
	}
393589
public function setupRules()
    {
        parent::setupRules();

        $this->rules->remove('symbol.selector.tag');
        $this->rules->add('symbol.selector.tag', new Rule(new RegexMatcher('/(?>[\s{};]|^)(?=(\w+)[^;}]*\{)/m'), [
            'context' => ['!symbol', '!string', '!number']
        ]));

        $this->rules->add('variable', new Rule(new RegexMatcher('/(\$[\w-]+)/'), ['context' => $this->everywhere()]));
    }
1128665
function flattenRules(rules) {
  var out = {};

  rules.forEach(function(rule) {
    // Ignore anything that doesn't look like a CSS rule
    if (rule.type !== 'rule') return;
    rule.selectors.forEach(function(sel) {
      if (!out[sel]) out[sel] = {};

      rule.declarations.forEach(function(decl) {
        out[sel][decl.property] = decl.value;
      });
    });
  });

  return out;
}