1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
|
#========================================================================
#
# Badger::Logic
#
# DESCRIPTION
# Simple parser and evaluator for boolean logic expressions, e.g.
# 'purple or orange', 'animal and (eats_nuts or eats_berries)'
#
# AUTHOR
# Andy Wardley <abw@wardley.org>
#
#========================================================================
package Badger::Logic;
use Badger::Class
version => 0.01,
debug => 0,
base => 'Badger::Base',
as_text => 'text',
constants => 'HASH',
constant => {
LOGIC => 'Badger::Logic',
},
exports => {
any => 'LOGIC Logic',
},
messages => {
no_text => 'No text expression specified.',
no_rhs => 'Missing expression following "%s"',
bad_text => 'Unexpected text in expression: %s',
parse => 'Could not parse logic expression: %s',
no_rparen => 'Missing ")" at end of nested expression',
};
our $NODE = {
'item' => 'Badger::Logic::Item',
'not' => 'Badger::Logic::Not',
'and' => 'Badger::Logic::And',
'or' => 'Badger::Logic::Or',
};
*test = \&evaluate;
sub Logic {
return @_
? LOGIC->new(@_)
: LOGIC;
}
sub new {
my $class = shift;
my $text = shift;
return $class->error_msg('no_text')
unless defined $text;
bless {
text => ref $text ? $text : \$text,
}, $class;
}
sub evaluate {
my $self = shift;
my $args = @_ && ref $_[0] eq HASH ? shift : { @_ };
$self->tree->evaluate($args);
}
sub tree {
my $self = shift;
return $self->{ tree }
||= $self->parse($self->{ text });
}
sub text {
${ shift->{ text } };
}
sub tree_text {
shift->tree->text;
}
sub parse {
my $self = shift;
my $text = shift;
my $tref = ref $text ? $text : \$text;
$self->debug("parse($$tref)\n") if DEBUG;
my $expr = $self->parse_expr($tref)
|| return $self->error_msg( parse => $$tref );
$self->debug("expr: ", $expr->text) if DEBUG;
if ($$tref =~ / \G \s* (.+) $/cigsx) {
return $self->error_msg( bad_text => $1 );
}
return $expr;
}
sub parse_expr {
my $self = shift;
my $text = shift;
my $left = $self->parse_unary($text) || return;
$self->debug("got unary: ", $left->text) if DEBUG;
if ($$text =~ / \G \s+ (and|or) \s+ /cigx) {
my $op = $1;
$self->debug("binary op: $op\n") if $DEBUG;
my $right = $self->parse_expr($text)
|| return $self->error_msg( no_rhs => $op );
return $NODE->{ lc $op }->new( $left, $right );
}
elsif ($$text =~ / \G \s* \( /cgx) {
my $expr = $self->parse_expr($text)
|| return $self->error_msg( no_rhs => '(' );
$$text =~ / \G \s* \) /cgx
|| return $self->error_msg('no_rparen');
return $self->error_msg( bad_text => $1 );
}
return $left;
}
sub parse_unary {
my $self = shift;
my $text = shift;
if ($$text =~ / \G \s* (not) \s+ /cigx) {
my $op = $1;
$self->debug("unary op: $op\n") if $DEBUG;
my $right = $self->parse_term($text)
|| return $self->error_msg( no_rhs => $op );
return $NODE->{ lc $op }->new($right);
}
return $self->parse_term($text)
|| $self->decline('Not a unary expression');
}
sub parse_term {
my $self = shift;
my $text = shift;
if ($$text =~ / \G \s* (\w+) /cigx) {
$self->debug("item: $1\n") if $DEBUG;
return $NODE->{ item }->new($1);
}
elsif ($$text =~ / \G \s* (['"]) ((?:\\?.)*?) \1 /cigx) {
$self->debug("string: $2\n") if $DEBUG;
return $NODE->{ item }->new($2);
}
elsif ($$text =~ / \G \s* \( /cgx) {
my $expr = $self->parse_expr($text)
|| return $self->error_msg( no_rhs => '(' );
$$text =~ / \G \s* \) /cgx
|| return $self->error_msg('no_rparen');
return $expr;
}
return $self->decline('Not a term');
}
#=======================================================================
# node types
#=======================================================================
package Badger::Logic::Expr;
use base 'Badger::Base';
sub new {
my $class = shift;
bless [ @_ ], $class;
}
package Badger::Logic::Item;
use base 'Badger::Logic::Expr';
sub evaluate {
my $self = shift;
my $args = @_ && ref $_[0] eq 'HASH' ? shift : { @_ };
return $args->{ $self->[0] };
}
sub text {
$_[0]->[0];
}
package Badger::Logic::Not;
use base 'Badger::Logic::Expr';
sub evaluate {
my $self = shift;
return $self->[0]->evaluate(@_) ? 0 : 1;
}
sub text {
my $self = shift;
'(not ' . $self->[0]->text . ')';
}
package Badger::Logic::And;
use base 'Badger::Logic::Expr';
sub evaluate {
my $self = shift;
return $self->[0]->evaluate(@_)
&& $self->[1]->evaluate(@_);
}
sub text {
my $self = shift;
'(' . $self->[0]->text . ' and ' . $self->[1]->text . ')';
}
package Badger::Logic::Or;
use base 'Badger::Logic::Expr';
use Badger::Debug ':all';
sub evaluate {
my $self = shift;
return $self->[0]->evaluate(@_)
|| $self->[1]->evaluate(@_);
}
sub text {
my $self = shift;
'(' . $self->[0]->text . ' or ' . $self->[1]->text . ')';
}
1;
__END__
=head1 NAME
Badger::Logic - parse and evaluate simple logical expressions
=head1 SYNOPSIS
use Badger::Logic 'Logic';
my $logic = Logic('animal and (eats_nuts or eats_berries)');
my $values = {
animal => 1,
eats_nuts => 1,
}
if ($logic->test($values)) {
print "This is an animal that eats nuts or berries\n";
}
=head1 DESCRIPTION
This module implements a simple parser and evaluator for boolean logic
expressions. It evolved from a piece of code that I originally wrote to
handle role-based authentication in web applications.
=head1 EXPORTABLE SUBROUTINES
=head2 LOGIC
This is a shortcut alias to C<Badger::Logic>.
use Badger::Logic 'LOGIC';
my $logic = LOGIC->new($expr); # same as Badger::Logic->new($expr);
=head2 Logic()
This subroutine returns the name of the C<Badger::Logic> class when called
without arguments. Thus it can be used as an alias for C<Badger::Logic>
as per L<LOGIC>.
use Badger::Logic 'Logic';
my $logic = Logic->new($expr); # same as Badger::Logic->new($expr);
When called with arguments, it creates a new C<Badger::Logic> object.
my $logic = Logic($expr); # same as Badger::Logic->new($expr);
=head1 METHODS
=head2 new($expr)
Constructor method to create a new C<Badger::Logic> object from an expression.
my $logic = Badger::Logic->new('animal and (cat or dog)');
=head2 evaluate($values) / test($values)
Method to evaluate the expression. A reference to a hash array should be
passed containing the values that the expression can test.
my $values = {
animal => 1,
cat => 1,
};
if ($logic->evaluate($values)) {
print "This animal is a cat or a dog\n";
}
=head2 tree()
Returns a reference to the root of a tree of C<Badger::Logic::Node> objects
that represent the parsed expression.
=head2 text()
Returns a text representation of the logic expression.
=head1 INTERNAL METHODS
=head2 parse($text)
Main method to parse a logical expression. This calls L<parse_expr()> and
then checks that all of the text has been successfully parsed. It returns
a reference to a C<Badger::Logic::Node> object.
=head2 parse_expr($text)
Method to parse a binary expression.
=head2 parse_unary($text)
Method to parse a unary expression.
=head2 parse_term($text)
Method to parse a single term in a logical expression.
=head1 AUTHOR
Andy Wardley L<http://wardley.org>
=head1 COPYRIGHT
Copyright (C) 2007-2009 Andy Wardley. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
# Local Variables:
# mode: perl
# perl-indent-level: 4
# indent-tabs-mode: nil
# End:
#
# vim: expandtab shiftwidth=4:
|