the "word" path part regex only allows singular period characters
[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   return sub { {} } unless length($spec);
39   for ($_[1]) {
40     my @match;
41     PARSE: { do {
42       push @match, $self->_parse_spec_section($_)
43         or $self->_blam("Unable to work out what the next section is");
44       if (/\G\)/gc) {
45         $self->_blam("Found closing ) with no opening (") unless $nested;
46         last PARSE;
47       }
48       last PARSE if (pos == length);
49       $match[-1] = $self->_parse_spec_combinator($_, $match[-1])
50         or $self->_blam('No valid combinator - expected + or |');
51     } until (pos == length) }; # accept trailing whitespace
52     if ($nested and pos == length) {
53       pos = $nested - 1;
54       $self->_blam("No closing ) found for opening (");
55     }
56     return $match[0] if (@match == 1);
57     return match_and(@match);
58   }
59 }
60
61 sub _parse_spec_combinator {
62   my ($self, $spec, $match) = @_;
63   for ($_[1]) {
64
65     /\G\+/gc and
66       return $match;
67
68     /\G\|/gc and
69       return do {
70         my @match = $match;
71         PARSE: { do {
72           push @match, $self->_parse_spec_section($_)
73             or $self->_blam("Unable to work out what the next section is");
74           last PARSE if (pos == length);
75           last PARSE unless /\G\|/gc; # give up when next thing isn't |
76         } until (pos == length) }; # accept trailing whitespace
77         return match_or(@match);
78       };
79   }
80   return;
81 }
82
83 sub _parse_spec_section {
84   my ($self) = @_;
85   for ($_[1]) {
86
87     # GET POST PUT HEAD ...
88
89     /\G([A-Z]+)/gc and
90       return match_method($1);
91
92     # /...
93
94     /\G(?=\/)/gc and
95       return $self->_url_path_match($_);
96
97     # .* and .html
98
99     /\G\.(\*|\w+)/gc and
100       return match_extension($1);
101
102     # (...)
103
104     /\G\(/gc and
105       return $self->_parse_spec($_, pos);
106
107     # !something
108
109     /\G!/gc and
110       return match_not($self->_parse_spec_section($_));
111
112     # ?<param spec>
113     /\G\?/gc and
114       return $self->_parse_param_handler($_, 'query');
115
116     # %<param spec>
117     /\G\%/gc and
118       return $self->_parse_param_handler($_, 'body');
119
120     # *<param spec>
121     /\G\*/gc and
122       return $self->_parse_param_handler($_, 'uploads');
123   }
124   return; # () will trigger the blam in our caller
125 }
126
127 sub _url_path_match {
128   my ($self) = @_;
129   for ($_[1]) {
130     my @path;
131     my $end = '';
132     my $keep_dot;
133     PATH: while (/\G\//gc) {
134       /\G\.\.\./gc
135         and do {
136           $end = '(/.*)';
137           last PATH;
138         };
139       push @path, $self->_url_path_segment_match($_)
140         or $self->_blam("Couldn't parse path match segment");
141       /\G\.\*/gc
142         and do {
143           $keep_dot = 1;
144           last PATH;
145         };
146     }
147     if (@path && !$end && !$keep_dot) {
148       length and $_ .= '(?:\.\w+)?' for $path[-1];
149     }
150     my $re = '^('.join('/','',@path).')'.$end.'$';
151     $re = qr/$re/;
152     if ($end) {
153       return match_path_strip($re);
154     } else {
155       return match_path($re);
156     }
157   }
158   return;
159 }
160
161 sub _url_path_segment_match {
162   my ($self) = @_;
163   for ($_[1]) {
164     # trailing / -> require / on end of URL
165     /\G(?:(?=[+|\)])|$)/gc and
166       return '';
167     # word chars only -> exact path part match
168     /
169         \G(
170             (?:             # start matching at a space followed by:
171                     [\w\-]  # word chars or dashes
172                 |           # OR
173                     \.      # a period
174                     (?!\.)  # not followed by another period
175             )
176             +               # then grab as far as possible
177         )
178     /gcx and
179       return "\Q$1";
180     # ** -> capture unlimited path parts
181     /\G\*\*/gc and
182       return '(.*?[^/])';
183     # * -> capture path part
184     /\G\*/gc and
185       return '([^/]+?)';
186   }
187   return ();
188 }
189
190 sub _parse_param_handler {
191   my ($self, $spec, $type) = @_;
192
193   for ($_[1]) {
194     my (@required, @single, %multi, $star, $multistar, %positional, $have_kw);
195     my %spec;
196     my $pos_idx = 0;
197     PARAM: { do {
198
199       # ?:foo or ?@:foo
200
201       my $is_kw = /\G\:/gc;
202
203       # ?@foo or ?@*
204
205       my $multi = /\G\@/gc;
206
207       # @* or *
208
209       if (/\G\*/gc) {
210
211         $self->_blam("* is always named; no need to supply :") if $is_kw;
212
213         if ($star) {
214           $self->_blam("Can only use one * or \@* in a parameter match");
215         }
216
217         $spec{star} = { multi => $multi };
218       } else {
219
220         # @foo= or foo= or @foo~ or foo~
221
222         /\G(\w+)/gc or $self->_blam('Expected parameter name');
223
224         my $name = $1;
225
226         # check for = or ~ on the end
227
228         /\G\=/gc
229           ? push(@{$spec{required}||=[]}, $name)
230           : (/\G\~/gc or $self->_blam('Expected = or ~ after parameter name'));
231
232         # record positional or keyword
233
234         push @{$spec{$is_kw ? 'named' : 'positional'}||=[]},
235           { name => $name, multi => $multi };
236       }
237     } while (/\G\&/gc) }
238
239     return Web::Dispatch::Predicates->can("match_${type}")->(\%spec);
240   }
241 }
242
243 1;