92aa9b61cbbf9b635a29b755edcd889764af082b
[catagits/Web-Simple.git] / lib / Web / Dispatch / Parser.pm
1 package Web::Dispatch::Parser;
2
3 sub DEBUG () { 0 }
4
5 BEGIN {
6   if ($ENV{WEB_DISPATCH_PARSER_DEBUG}) {
7     no warnings 'redefine';
8     *DEBUG = sub () { 1 }
9   }
10 }
11
12 use Sub::Quote;
13 use Web::Dispatch::Predicates;
14 use Moo;
15
16 has _cache => (
17   is => 'lazy', default => quote_sub q{ {} }
18 );
19
20 sub diag { if (DEBUG) { warn $_[0] } }
21
22 sub _blam {
23   my ($self, $error) = @_;
24   my $hat = (' ' x (pos||0)).'^';
25   die "Error parsing dispatch specification: ${error}\n
26 ${_}
27 ${hat} here\n";
28 }
29
30 sub parse {
31   my ($self, $spec) = @_;
32   $spec =~ s/\s+//g; # whitespace is not valid
33   return $self->_cache->{$spec} ||= $self->_parse_spec($spec);
34 }
35
36 sub _parse_spec {
37   my ($self, $spec, $nested) = @_;
38   for ($_[1]) {
39     my @match;
40     PARSE: { do {
41       push @match, $self->_parse_spec_section($_)
42         or $self->_blam("Unable to work out what the next section is");
43       if (/\G\)/gc) {
44         $self->_blam("Found closing ) with no opening (") unless $nested;
45         last PARSE;
46       }
47       last PARSE if (pos == length);
48       $match[-1] = $self->_parse_spec_combinator($_, $match[-1])
49         or $self->_blam('No valid combinator - expected + or |');
50     } until (pos == length) }; # accept trailing whitespace
51     if ($nested and pos == length) {
52       pos = $nested - 1;
53       $self->_blam("No closing ) found for opening (");
54     }
55     return $match[0] if (@match == 1);
56     return match_and(@match);
57   }
58 }
59
60 sub _parse_spec_combinator {
61   my ($self, $spec, $match) = @_;
62   for ($_[1]) {
63
64     /\G\+/gc and
65       return $match;
66
67     /\G\|/gc and
68       return do {
69         my @match = $match;
70         PARSE: { do {
71           push @match, $self->_parse_spec_section($_)
72             or $self->_blam("Unable to work out what the next section is");
73           last PARSE if (pos == length);
74           last PARSE unless /\G\|/gc; # give up when next thing isn't |
75         } until (pos == length) }; # accept trailing whitespace
76         return match_or(@match);
77       };
78   }
79   return;
80 }
81
82 sub _parse_spec_section {
83   my ($self) = @_;
84   for ($_[1]) {
85
86     # GET POST PUT HEAD ...
87
88     /\G([A-Z]+)/gc and
89       return $self->_http_method_match($_, $1);
90
91     # /...
92
93     /\G(?=\/)/gc and
94       return $self->_url_path_match($_);
95
96     # .* and .html
97
98     /\G\.(\*|\w+)/gc and
99       return $self->_url_extension_match($_, $1);
100
101     # (...)
102
103     /\G\(/gc and
104       return $self->_parse_spec($_, pos);
105
106     # !something
107
108     /\G!/gc and
109       return match_not($self->_parse_spec_section($_));
110
111     # ?<param spec>
112     /\G\?/gc and
113       return $self->_parse_param_handler($_, 'query');
114
115     # %<param spec>
116     /\G\%/gc and
117       return $self->_parse_param_handler($_, 'body');
118   }
119   return; # () will trigger the blam in our caller
120 }
121
122 sub _http_method_match {
123   my ($self, $str, $method) = @_;
124   match_method($method);
125 }
126
127 sub _url_path_match {
128   my ($self) = @_;
129   for ($_[1]) {
130     my @path;
131     my $end = '';
132     PATH: while (/\G\//gc) {
133       /\G\.\.\./gc
134         and do {
135           $end = '(/.*)';
136           last PATH;
137         };
138       push @path, $self->_url_path_segment_match($_)
139         or $self->_blam("Couldn't parse path match segment");
140     }
141     if (@path && !$end) {
142       length and $_ .= '(?:\.\w+)?' for $path[-1];
143     }
144     my $re = '^('.join('/','',@path).')'.$end.'$';
145     $re = qr/$re/;
146     if ($end) {
147       return match_path_strip($re);
148     } else {
149       return match_path($re);
150     }
151   }
152   return;
153 }
154
155 sub _url_path_segment_match {
156   my ($self) = @_;
157   for ($_[1]) {
158     # trailing / -> require / on end of URL
159     /\G(?:(?=[+|\)])|$)/gc and
160       return '';
161     # word chars only -> exact path part match
162     /\G([\w\-]+)/gc and
163       return "\Q$1";
164     # ** -> capture unlimited path parts
165     /\G\*\*/gc and
166       return '(.*?[^/])';
167     # * -> capture path part
168     /\G\*/gc and
169       return '([^/]+?)';
170   }
171   return ();
172 }
173
174 sub _url_extension_match {
175   my ($self, $str, $extension) = @_;
176   match_extension($extension);
177 }
178
179 sub _parse_param_handler {
180   my ($self, $spec, $type) = @_;
181
182   require Web::Simple::ParamParser;
183   my $unpacker = Web::Simple::ParamParser->can("get_unpacked_${type}_from");
184
185   for ($_[1]) {
186     my (@required, @single, %multi, $star, $multistar, %positional, $have_kw);
187     my $pos_idx = 0;
188     PARAM: { do {
189
190       # ?:foo or ?@:foo
191
192       my $is_kw = /\G\:/gc;
193
194       # ?@foo or ?@*
195
196       my $multi = /\G\@/gc;
197
198       # @* or *
199
200       if (/\G\*/gc) {
201
202         $self->_blam("* is always named; no need to supply :") if $is_kw;
203
204         $multi ? ($multistar = 1) : ($star = 1);
205
206         $have_kw = 1;
207
208         if ($star && $multistar) {
209           $self->_blam("Can't use * and \@* in the same parameter match");
210         }
211       } else {
212
213         # @foo= or foo= or @foo~ or foo~
214
215         /\G(\w+)/gc or $self->_blam('Expected parameter name');
216
217         my $name = $1;
218
219         # check for = or ~ on the end
220
221         /\G\=/gc
222           ? push(@required, $name)
223           : (/\G\~/gc or $self->_blam('Expected = or ~ after parameter name'));
224
225         # record the key in the right category depending on the multi (@) flag
226
227         $multi ? ($multi{$name} = 1) : (push @single, $name);
228
229         # record positional or keyword
230
231         $is_kw ? ($have_kw = 1) : ($positional{$name} = $pos_idx++);
232       }
233     } while (/\G\&/gc) }
234
235     return sub {
236       my $raw = $unpacker->($_[0]);
237       foreach my $name (@required) {
238         return unless exists $raw->{$name};
239       }
240       my (%p, %done);
241       my @p = (undef) x $pos_idx;
242       foreach my $name (
243         @single,
244         ($star
245           ? (grep { !exists $multi{$_} } keys %$raw)
246           : ()
247         )
248       ) {
249         if (exists $raw->{$name}) {
250           if (exists $positional{$name}) {
251             $p[$positional{$name}] = $raw->{$name}->[-1];
252           } else {
253             $p{$name} = $raw->{$name}->[-1];
254           }
255         }
256         $done{$name} = 1;
257       }
258       foreach my $name (
259         keys %multi,
260         ($multistar
261           ? (grep { !exists $done{$_} && !exists $multi{$_} } keys %$raw)
262           : ()
263         )
264       ) {
265         if (exists $positional{$name}) {
266           $p[$positional{$name}] = $raw->{$name}||[];
267         } else {
268           $p{$name} = $raw->{$name}||[];
269         }
270       }
271       $p[$pos_idx] = \%p if $have_kw;
272       return ({}, @p);
273     };
274   }
275 }
276
277 1;