add & and | overloading to and and or
[dbsrgits/Data-Query.git] / lib / Data / Query / ExprBuilder.pm
1 package Data::Query::ExprBuilder;
2
3 use strictures 1;
4 use Data::Query::Constants qw(DQ_OPERATOR DQ_VALUE);
5 use Scalar::Util ();
6
7 use overload (
8   # binary operators
9   (map {
10     my ($overload, $as) = ref($_) ? @$_ : ($_, $_);
11     $overload => sub {
12       Data::Query::ExprBuilder->new({
13         expr => {
14           type => DQ_OPERATOR,
15           operator => { perl => $as },
16           args => [
17            map {
18              (Scalar::Util::blessed($_)
19              && $_->isa('Data::Query::ExprBuilder'))
20                ? $_->{expr}
21                : {
22                    type => DQ_VALUE,
23                    subtype => { perl => 'Scalar' },
24                    value => $_
25                  }
26             } $_[2] ? @_[1,0] : @_[0,1]
27           ]
28         },
29       });
30     }
31   }
32     qw(+ - * / % ** << >> . < > == != lt le gt ge eq ne),
33
34     # since 'and' and 'or' aren't operators we borrow the bitwise ops
35     [ '&' => 'and' ], [ '|' => 'or' ],
36   ),
37   # unsupported
38   (map {
39     my $op = $_;
40     $op => sub { die "Can't use operator $op on a ".ref($_[0]) }
41    } qw(<=> cmp x ^ ~)
42   ),
43 ); 
44
45 sub new {
46   bless({ %{$_[1]} }, (ref($_[0])||$_[0]));
47 }
48
49 1;