Construct a new ruleset
543656
function Ruleset(rules, composite) {
  if (!(this instanceof Ruleset)) {
    return new Ruleset(rules, composite);
  }
  this.composite = composite || 'all';
  this.rules = rules || [];
}
567132
def rules(cls, attr=None):
        
        try:
            if attr is None:
                attr = cls._rules_attr()
            return getattr(cls, attr).keys()
        except TypeError:
            return ()
1351152
public function setupRules()
    {
        $identifier = '[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*';
        $this->rules->addMany([
            'comment'          => new Rule(new CommentMatcher(['//'], [['/*', '*/']])),
            'keyword'          => new Rule(new WordMatcher([
                'break', 'default', 'func', 'interface', 'select', 'case', 'defer', 'go', 'map', 'struct', 'chan',
                'else', 'goto', 'package', 'switch', 'const', 'fallthrough', 'if', 'range', 'type', 'continue', 'for',
                'import', 'return', 'var',
            ])),
            'number'           => [
                'integer' => new Rule(new RegexMatcher('/\b([1-9]\d*|0x\x+|[0-7]+)\b/si')),
                'float'   => new Rule(new RegexMatcher('/\v((?:\d+\.\d*(?P<exponent>e[+-]?\d+)?|\.\d+(?&exponent)?|\d+(?&exponent))i?)\b/si')),
            ],
            'string'           => [
                'rune' => new Rule(new RegexMatcher('/(\'(?:\\\(?:[abfnrtv\\\'"]|[0-7]{3}|x\x{2})|u\x{4}|U\x{8})\')/si')),
                CommonFeatures::strings(['single' => '`', 'double' => '"']),
            ],

            'constant.special' => new Rule(new WordMatcher(['true', 'false', 'iota'])),
            'type'             => new Rule(new RegexMatcher('/((?:\*\s*)?(?:u?int(?:8|16|32|64|ptr)?|float(?:32|64)|complex(?:64|128)|byte|rune|string|error))/')),
            'symbol'           => [
                'function'  => new Rule(new RegexMatcher("/func\\s*($identifier)/")),
                'struct'    => new Rule(new RegexMatcher("/type\\s*($identifier)\\s*struct/")),
                'interface' => new Rule(new RegexMatcher("/type\\s*($identifier)\\s*interface/")),
            ],
            'call'             => new Rule(new RegexMatcher("/($identifier)\\s*\\(/i"), ['priority' => -1]),

            'operator' => [
                new Rule(new RegexMatcher('~((?>&{2}|<-|[+-]{2}|\|\||[+&=!/:%*^-|]?=|<{1,2}=?|>{1,2}=?|&^=?))~si')),
                'punctuation' => new Rule(new RegexMatcher('/([;,]|\.\.\.)/')),
            ],
        ]);
    }
341773
public function setupRules()
    {
        $this->rules->addMany([
            'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
                'context' => ['!operator.escape', '!comment', '!string', '!expression'],
            ]),

            'string.heredoc' => new Rule(new RegexMatcher('/<<<\s*(\w+)\R(?P<string>.*?)\R\1;/sm', ['string' => Token::NAME, 0 => 'keyword.heredoc']), ['context' => ['!comment']]),
            'string.nowdoc'  => new Rule(new RegexMatcher('/<<<\s*\'(\w+)\'\R(?P<string>.*?)\R\1;/sm', ['string' => Token::NAME, 0 => 'keyword.nowdoc']), ['context' => ['!comment']]),

            'variable' => new Rule(new RegexMatcher('/(?:[^\\\]|^)(\$[a-z_]\w*)/i'), [
                'context' => ['*comment.docblock', '!string.nowdoc', '!string.single', '!comment']
            ]),
            'variable.property' => new Rule(new RegexMatcher('/(?=(?:\w|\)|\])\s*->([a-z_]\w*))/i'), [
                'priority' => -2,
                'context' => ['*comment.docblock', '!string.nowdoc', '!string.single', '!comment']
            ]),

            'symbol.function' => new Rule(new RegexMatcher('/function\s+([a-z_]\w+)\s*\(/i')),
            'symbol.class'    => [
                new Rule(new RegexMatcher('/(?:class|new|use|extends)\s+([\w\\\]+)/i')),
                new Rule(new RegexMatcher('/([\w\\\]+)::/i')),
                new Rule(new RegexMatcher('/@(?:var|property(?:-read|-write)?)(?:\s+|\s+\$\w+\s+)([^$][\w\\\]+)/i'), ['context' => ['comment.docblock']]),
            ],
            
            'expression.in-string' => new Rule(new RegexMatcher('/(?=(\{\$((?>[^${}]+|(?1))+)\}))/x'), [
                'context' => ['string'],
                'factory' => new TokenFactory(LanguageToken::class),
                'inject'  => $this
            ]),

            'symbol.class.interface' => [
                new Rule(new RegexMatcher('/interface\s+([\w\\\]+)/i')),
                new Rule(new DelegateRegexMatcher(
                    '/implements\s+((?:[\w\\\]+)(?:,\s*([\w\\\]+))+)/i',
                    function($match, TokenFactoryInterface $factory) {
                        foreach (preg_split('/,\s*/', $match[1][0], 0, PREG_SPLIT_OFFSET_CAPTURE) as $interface) {
                            yield $factory->create(Token::NAME, [
                                'pos' => $match[1][1] + $interface[1],
                                'length' => strlen($interface[0])]
                            );
                        }
                    }
                )),
            ],

            'symbol.namespace' => [
                /*new Rule(new RegexMatcher('/(\\\{0,2}(?:\w+\\\{1,2})+)\w+/i'), [
                    'context' => ['*symbol', '*none']
                ]),*/

                new Rule(new RegexMatcher('/namespace\s*(\\\{0,2}(?:\w+\\\{1,2})+\w+);/i'), [
                    'context' => ['*symbol', '*none']
                ]),
            ],

            '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' => ['string.double', '!operator.escape']
                ]),
                new Rule(new RegexMatcher('/(\\\[\'\\\])/i'), [
                    'context' => ['string', '!operator.escape']
                ]),
            ],

            'comment' => new Rule(new CommentMatcher(['//', '#'], [
                '$.docblock' => ['/**', '*/'],
                ['/*', '*/']
            ]), ['priority' => 4]),

            'symbol.annotation' => new Rule(new RegexMatcher('/[\s]+(@[\w-]+)/i'), [
                'context' => ['comment.docblock']
            ]),

            'call' => new Rule(new RegexMatcher('/([a-z_]\w*)\s*\(/i'), ['priority' => -1]),

            'constant' => new Rule(new WordMatcher(array_merge([
                '__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__',
                '__LINE__', '__METHOD__', '__NAMESPACE__', '__TRAIT__',
            ], array_keys(get_defined_constants(true)["Core"]))), ['priority' => -2]),
            'constant.static' => new Rule(new RegexMatcher('/(?:[\w\\\]+::|const\s+)(\w+)/i'), ['priority' => -2]),

            'keyword' => new Rule(new WordMatcher([
                '__halt_compiler', 'abstract', 'and', 'array',
                'as', 'break', 'callable', 'case', 'catch',
                'class', 'clone', 'const', 'continue', 'declare',
                'default', 'die', 'do', 'echo', 'else', 'elseif',
                'empty', 'enddeclare', 'endfor', 'endforeach', 'endif',
                'endswitch', 'endwhile', 'eval', 'exit', 'extends',
                'final', 'finally', 'for', 'foreach', 'function',
                'global', 'goto', 'if', 'implements', 'include', 'include_once',
                'instanceof', 'insteadof', 'interface', 'isset', 'list',
                'namespace', 'new', 'or', 'print', 'private', 'protected',
                'public', 'require', 'require_once', 'return', 'static',
                'switch', 'throw', 'trait', 'try', 'unset', 'parent', 'self',
                'use', 'var', 'while', 'xor', 'yield'
            ]), ['context' => ['!string', '!variable', '!comment']]),

            'keyword.cast' => new Rule(
                new RegexMatcher('/(\((?:int|integer|bool|boolean|float|double|real|string|array|object|unset)\))/')
            ),

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

            'operator.punctuation' => new Rule(new WordMatcher([',', ';'], ['separated' => false]), ['priority' => 0]),
        ]);
    }
64438
function setRuleModel (roles, rule, rules, origRule) {
    // allow/deny is last element of rule
    var allow = rule.pop()
    // blanket rule for all models
    if (rule.length === 0) {
        // create role access rule map
        if (!rules.allow) {
            rules.allow = {}
        }
        // set rule for each role
        _.each(roles, role => {
            rules.allow[role] = allow
        })
        // break
        return
    }

    // model name is first clause of rule
    var model = rule.shift()
    // create map of models
    if (!rules.model) {
        rules.model = {}
    }
    // create entry for model
    if (!rules.model[model]) {
        rules.model[model] = {}
    }

    // blanket rule for single model
    if (rule.length === 0) {
        // create role access rule map
        if (!rules.model[model].allow) {
            rules.model[model].allow = {}
        }
        // set rule for each role
        _.each(roles, role => {
            rules.model[model].allow[role] = allow
        })
        // break
        return
    }

    // action follows model name
    var action = rule.shift()
    // create map of actions
    if (!rules.model[model].action) {
        rules.model[model].action = {}
    }
    // create entry for action
    if (!rules.model[model].action[action]) {
        rules.model[model].action[action] = {}
    }

    // create action does not have any options
    if (action === 'create') {
        // there should be no more rule clauses
        if (rule.length === 0) {
            // create role access rule map
            if (!rules.model[model].action[action].allow) {
                rules.model[model].action[action].allow = {}
            }
            // set rule for each role
            _.each(roles, role => {
                rules.model[model].action[action].allow[role] = allow
            })
            // break
            return
        }
        else {
            throw new Error('invalid rule '+origRule)
        }
    }
    // all other actions apply to existing model instances and can
    // apply either to any instance or to instances owned by session
    else {
        // if there are two rule clauses then next is a state
        if (rule.length === 2) {
            var state = rule.shift()
            // create map of states
            if (!rules.model[model].action[action].state) {
                rules.model[model].action[action].state = {}
            }
            // create entry for state
            if (!rules.model[model].action[action].state[state]) {
                rules.model[model].action[action].state[state] = {}
            }
            // own/any clause follows state
            rules = rules.model[model].action[action].state[state]
        }
        // otherwise own/any clause follows action
        else {
            rules = rules.model[model].action[action]
        }
        // there must be one additional rule clause
        if (rule.length === 1) {
            var scope = rule.shift()
            // scope must be own or any
            assert.ok(scope === 'own' || scope === 'any', 'invalid rule '+origRule)
            // create map for scope
            if (!rules[scope]) {
                rules[scope] = {}
            }
            // create role access rule map
            if (!rules[scope].allow) {
                rules[scope].allow = {}
            }
            // set rule for each role
            _.each(roles, role => {
                rules[scope].allow[role] = allow
            })
        }
        else {
            throw new Error('invalid rule '+origRule)
        }
    }
}
90455
public function buildItemRuleSet() : RuleSet
    {
        $ruleSet = $this->buildFeedRuleSet();
        $ruleSet
            ->add(new Author())
            ->add(new Description('content'), ['summary']);

        return $ruleSet;
    }
57655
public function updateRulesetUniques($ruleset = null)
    {
        $rules = $this->getRuleset($ruleset);
        $this->setRuleset($ruleset, $this->injectUniqueIdentifierToRules($rules));
    }
1327453
function setRuleModule (roles, rule, rules, origRule) {
    // allow/deny is last element of rule
    var allow = rule.pop()
    // blanket rule for all modules
    if (rule.length === 0) {
        // create role access rule map
        if (!rules.allow) {
            rules.allow = {}
        }
        // set rule for each role
        _.each(roles, role => {
            rules.allow[role] = allow
        })
        // break
        return
    }

    // module name is first clause of rule
    var module = rule.shift()
    // create map of models
    if (!rules.module) {
        rules.module = {}
    }
    // create entry for module
    if (!rules.module[module]) {
        rules.module[module] = {}
    }

    // blanket rule for single module
    if (rule.length === 0) {
        // create role access rule map
        if (!rules.module[module].allow) {
            rules.module[module].allow = {}
        }
        // set rule for each role
        _.each(roles, role => {
            rules.module[module].allow[role] = allow
        })
    }
    // rule for method
    else if (rule.length === 1) {
        var method = rule.shift()
        // create map of methods
        if (!rules.module[module].method) {
            rules.module[module].method = {}
        }
        // create method entry
        if (!rules.module[module].method[method]) {
            rules.module[module].method[method] = {}
        }
        // create role access rule map
        if (!rules.module[module].method[method].allow) {
            rules.module[module].method[method].allow = {}
        }
        // set rule for each role
        _.each(roles, role => {
            rules.module[module].method[method].allow[role] = allow
        })
    }
    // invalid rule
    else {
        throw new Error('invalid rule '+origRule)
    }
}
503777
def build_alpha_part(ruleset, root_node):
        
        # Adds a dummy rule with InitialFact as LHS for always generate
        # the alpha part matching InitialFact(). This is needed for the
        # CE using InitialFact
        ruleset = ruleset.copy()
        ruleset.add(Rule(InitialFact()))

        # Generate a dictionary with rules and the set of facts of the
        # rule.
        rule_facts = {rule: extract_facts(rule) for rule in ruleset}

        # For each fact build a list of checker function capable of
        # check for each part in the fact.
        fact_checks = {fact: set(generate_checks(fact))
                       for fact in chain.from_iterable(rule_facts.values())}

        # Make a ranking of the most used checks
        check_rank = Counter(chain.from_iterable(fact_checks.values()))

        def weighted_check_sort(check):
            """Sort check by its type and number of times seen."""
            if isinstance(check, TypeCheck):
                return (float('inf'), hash(check))
            elif isinstance(check, FactCapture):
                return (float('-inf'), hash(check))
            elif isinstance(check, FeatureCheck):
                return (check_rank[check], hash(check))
            else:
                raise TypeError("Unknown check type.")  # pragma: no cover

        def weighted_rule_sort(rule):
            """Sort rules by the average weight of its checks."""
            total = 0
            for fact in rule_facts[rule]:
                for check in fact_checks[fact]:
                    total += check_rank[check]
            return total / len(rule_facts[rule])

        sorted_rules = sorted(ruleset, key=weighted_rule_sort, reverse=True)

        fact_terminal_nodes = dict()
        # For rule in rank order and for each rule fact also in rank
        # order, build the alpha brank looking for an existing node
        # first.
        for rule in sorted_rules:
            for fact in rule_facts[rule]:
                current_node = root_node
                fact_sorted_checks = sorted(
                    fact_checks[fact],
                    key=weighted_check_sort,
                    reverse=True)

                for check in fact_sorted_checks:
                    # Look for a child node with the given check in the
                    # current parent node.
                    for child in current_node.children:
                        if child.node.matcher is check:
                            current_node = child.node
                            break
                    else:
                        # Create a new node and append as child
                        new_node = FeatureTesterNode(check)
                        current_node.add_child(new_node, new_node.activate)
                        current_node = new_node

                fact_terminal_nodes[fact] = current_node

        # Return this dictionary containing the last alpha node for each
        # fact.
        return fact_terminal_nodes
355556
function build_rules(filters, arr) {
    var rules = [];
    for(var i=0; i<arr.length; i++) {
        var r = arr[i], rule
        if(!contains_expr(r)) throw OptError('Rule MUST contain an option.');
        switch(r.length) {
            case 1:
                rule = build_rule(filters, r[0]);
                break;
            case 2:
                var expr = LONG_SWITCH_RE.test(r[0]) ? 0 : 1;
                var alias = expr == 0 ? -1 : 0;
                var desc = alias == -1 ? 1 : -1;
                rule = build_rule(filters, r[alias], r[expr], r[desc]);
                break;
            case 3:
                rule = build_rule(filters, r[0], r[1], r[2]);
                break;
            default:
            case 0:
                continue;
        }
        rules.push(rule)
    }
    return rules;
}
372798
def _load_rules(self):
        """"""
        for ruleset in self.active_rulesets:
            section_name = 'sweep_rules_' + ruleset.lower()
            try:
                ruledefs = getattr(self.config, section_name)
            except AttributeError:
                raise error.UserError("There is no [{}] section in your configuration"
                                      .format(section_name.upper()))
            for ruledef, filtercond in ruledefs.items():
                if ruledef.endswith('.filter'):
                    rulename = ruledef.rsplit('.', 1)[0]
                    rule = SweepRule(ruleset, rulename,
                                     int(ruledefs.get(rulename + '.prio', '999')),
                                     ruledefs.get(rulename + '.order', self.default_order),
                                     parse_cond(filtercond))
                    self.rules.append(rule)

        self.rules.sort(key=lambda x: (x.prio, x.name))

        return self.rules
421805
def build_beta_part(ruleset, alpha_terminals):
        
        for rule in ruleset:
            if isinstance(rule[0], OR):
                for subrule in rule[0]:
                    wire_rule(rule, alpha_terminals, lhs=subrule)
            else:
                wire_rule(rule, alpha_terminals, lhs=rule)
373493
def _process_rules(self, rules: dict, system: System):
        
        self._source = None # reset the template source
        if not self._shall_proceed(rules):
            return
        self.context.update(rules.get('context', {}))
        self.path = rules.get('path', '')
        self.source = rules.get('source', None)
        self._process_rule(rules.get('system', None), {'system': system})
        for module in system.modules:
            self._process_rule(rules.get('module', None), {'module': module})
            for interface in module.interfaces:
                self._process_rule(rules.get('interface', None), {'interface': interface})
            for struct in module.structs:
                self._process_rule(rules.get('struct', None), {'struct': struct})
            for enum in module.enums:
                self._process_rule(rules.get('enum', None), {'enum': enum})
1204034
def get_rulesets():
    "
    rulesets_dirs = get_ruleset_dirs()
    ruleset_files = []
    for rulesets_dir in rulesets_dirs:
        for f in os.listdir(rulesets_dir):
            for ext in EXTS:
                file_path = os.path.join(rulesets_dir, f)
                if os.path.isfile(file_path) and f.lower().endswith(ext):
                    ruleset_files.append((f[:-len(ext)], file_path))
    return ruleset_files
372199
def add_rule(self, name, callable_):
        """"""
        assert isinstance(name, basestring)
        assert callable(callable_)
        self.project_rules_.add_rule(name, callable_)
891442
function applyRules(rules, stem) {

  for (let i = 0, l = rules.length; i < l; i++) {
    const [min, pattern, replacement = ''] = rules[i];

    if (stem.slice(-pattern.length) === pattern) {
      const newStem = stem.slice(0, -pattern.length) + replacement,
            m = computeM(newStem);

      if (m <= min)
        continue;

      return newStem;
    }
  }

  return stem;
}
1072899
def load_rule_definitions(self, ruleset_generator = False, rule_dirs = []):
        

        # Load rules from JSON files
        self.rule_definitions = {}
        for rule_filename in self.rules:
            for rule in self.rules[rule_filename]:
                if not rule.enabled and not ruleset_generator:
                    continue
            self.rule_definitions[os.path.basename(rule_filename)] = RuleDefinition(rule_filename, rule_dirs = rule_dirs)
        # In case of the ruleset generator, list all available built-in rules
        if ruleset_generator:
            rule_dirs.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/findings'))
            rule_filenames = []
            for rule_dir in rule_dirs:
                rule_filenames += [f for f in os.listdir(rule_dir) if os.path.isfile(os.path.join(rule_dir, f))]
            for rule_filename in rule_filenames:
                if rule_filename not in self.rule_definitions:
                    self.rule_definitions[os.path.basename(rule_filename)] = RuleDefinition(rule_filename)