]> sipb.mit.edu Git - ikiwiki.git/blob - doc/todo/tracking_bugs_with_dependencies.mdwn
707790a750fbe6667f1c5d0ce7f12ea7c48f43c1
[ikiwiki.git] / doc / todo / tracking_bugs_with_dependencies.mdwn
1 I like the idea of [[tips/integrated_issue_tracking_with_ikiwiki]], and I do so on several wikis.  However, as far as I can tell, ikiwiki has no functionality which can represent dependencies between bugs and allow pagespecs to select based on dependencies.  For instance, I can't write a pagespec which selects all bugs with no dependencies on bugs not marked as done.  --[[JoshTriplett]]
2
3 > I started having a think about this.  I'm going to start with the idea that expanding
4 > the pagespec syntax is the way to attack this.  It seems that any pagespec that is going
5 > to represent "all bugs with no dependencies on bugs not marked as done" is going to
6 > need some way to represent "bugs not marked as done" as a collection of pages, and
7 > then represent "bugs which do not link to pages in the previous collection".
8 >
9 > One way to do this would be to introduce variables into the pagespec, along with
10 > universal and/or existential [[!wikipedia Quantification]].  That looks quite complex.
11 >
12 >> I thought about this briefly, and got about that far.. glad you got
13 >> further. :-) --[[Joey]]
14
15 >> Or, one [[!taglink could_also_refer|pagespec_in_DL_style]] to the language of [[!wikipedia description logics]]: their formulas actually define classes of objects through quantified relations to other classes. --Ivan Z.
16
17 > Another option would be go with a more functional syntax.  The concept here would
18 > be to allow a pagespec to appear in a 'pagespec function' anywhere a page can.  e.g.
19 > I could pass a pagespec to `link()` and that would return true if there is a link to any
20 > page matching the pagespec.  This makes the variables and existential quantification
21 > implicit.  It would allow the example requested above:
22 >
23 >> `bugs/* and !*/Discussion and !link(bugs/* and !*/Discussion and !link(done))`
24 >
25 > Unfortunately, this is also going to make the pagespec parsing more complex because
26 > we now need to parse nested sets of parentheses to know when the nested pagespec
27 > ends, and that isn't a regular language (we can't use regular expression matching for
28 > easy parsing).
29 >
30 >> Also, it may cause ambiguities with page names that contain parens
31 >> (though some such ambigutities already exist with the pagespec syntax).
32 >
33 > One simplification of that would be to introduce some pagespec [[shortcuts]].  We could
34 > then allow pagespec functions to take either pages, or named pagespec shortcuts.  The
35 > pagespec shortcuts would just be listed on a special page, like current [[shortcuts]].
36 > (It would probably be a good idea to require that shortcuts on that page can only refer
37 > to named pagespecs higher up that page than themselves.  That would stop some
38 > looping issues...)  These shortcuts would be used as follows: when trying to match
39 > a page (without globs) you look to see if the page exists.  If it does then you have a
40 > match.  If it doesn't, then you look to see if a similarly named pagespec shortcut
41 > exists.  If it does, then you check that pagespec recursively to see if you have a match.
42 > The ordering requirement on named pagespecs stops infinite recursion.
43 >
44 > Does that seem like a reasonable first approach?
45 >
46 > -- [[Will]]
47
48 >> Having a separate page for the shortcuts feels unwieldly.. perhaps
49 >> instead the shortcut could be defined earlier in the scope of the same
50 >> pagespec that uses it?
51 >> 
52 >> Example: `define(~bugs, bugs/* and !*/Discussion) and define(~openbugs, ~bugs and !link(done)) and ~openbugs and !link(~openbugs)`
53
54 >>> That could work.  parens are only ever nested 1 deep in that grammar so it is regular and the current parsing would be ok.
55
56 >> Note that I made the "~" explicit, not implicit, so it could be left out. In the case of ambiguity between
57 >> a definition and a page name, the definition would win.
58
59 >>> That was my initial thought too :), but when implementing it I decided that requiring the ~ made things easier.  I'll probably require the ~ for the first pass at least.
60
61 >> So, equivilant example: `define(bugs, bugs/* and !*/Discussion) and define(openbugs, bugs and !link(done)) and openbugs and !link(openbugs)`
62 >> 
63
64 >> Re recursion, it is avoided.. but building a pagespec that is O(N^X) where N is the
65 >> number of pages in the wiki is not avoided. Probably need to add DOS prevention.
66 >>  --[[Joey]]
67
68 >>> If you memoize the outcomes of the named pagespecs you can make in O(N.X), no?
69 >>> -- [[Will]]
70
71 >>>> Yeah, guess that'd work. :-)
72
73 > <a id="another_kind_of_links" />One quick further thought.  All the above discussion assumes that 'dependency' is the
74 > same as 'links to', which is not really true.  For example, you'd like to be able to say
75 > "This bug does not depend upon [ [ link to other bug ] ]" and not have a dependency.
76 > Without having different types of links, I don't see how this would be possible.
77 >
78 > -- [[Will]]
79
80 >> I saw that this issue is targeted at by the work on [[structured page data#another_kind_of_links]]. --Ivan Z.
81
82 Okie - I've had a quick attempt at this.  Initial patch attached.  This one doesn't quite work.
83 And there is still a lot of debugging stuff in there.
84
85 At the moment I've added a new preprocessor plugin, `definepagespec`, which is like
86 shortcut for pagespecs.  To reference a named pagespec, use `~` like this:
87
88     [ [!definepagespec name="bugs" spec="bugs/* and !*/Discussion"]]
89     [ [!definepagespec name="openbugs" spec="~bugs and !link(done)"]]
90     [ [!definepagespec name="readybugs" spec="~openbugs and !link(~openbugs)"]]
91
92 At the moment the problem is in `match_link()` when we're trying to find a sub-page that
93 matches the appropriate page spec.  There is no good list of pages available to iterate over.
94
95     foreach my $nextpage (keys %IkiWiki::pagesources)
96
97 does not give me a good list of pages.  I found the same thing when I was working on
98 this todo [[todo/Add_a_plugin_to_list_available_pre-processor_commands]].
99
100 > I'm not sure why iterating over `%pagesources` wouldn't work here, it's the same method
101 > used by anything that needs to match a pagespec against all pages..? --[[Joey]]
102
103 >> My uchecked hypothesis is that %pagesources is created after the refresh hook.
104 >> I've also been concerned about how globally defined pagespec shortcuts would interact with
105 >> the page dependancy system.  Your idea of internally defined shortcuts should fix that. -- [[Will]]
106
107 >>> You're correct, the refresh hook is run very early, before pagesources
108 >>> is populated. (It will be partially populated on a refresh, but will
109 >>> not be updated to reflect new pages.) Agree that internally defined
110 >>> seems the way to go. --[[Joey]]
111
112 Immediately below is a patch which seems to basically work.  Lots of debugging code is still there
113 and it needs a cleanup, but I thought it worth posting at this point.  (I was having problems
114 with old style glob lists, so i just switched them off for the moment.)
115
116 The following three inlines work for me with this patch:
117
118     Bugs:
119     
120     [ [!inline pages="define(~bugs, bugs/* and ! */Discussion) and ~bugs" archive="yes"]]
121     
122     OpenBugs:
123     
124     [ [!inline pages="define(~bugs, bugs/* and ! */Discussion) and define(~openbugs,~bugs and !link(done)) and ~openbugs" archive="yes"]]
125     
126     ReadyBugs:
127     
128     [ [!inline pages="define(~bugs, bugs/* and ! */Discussion) and define(~openbugs,~bugs and !link(done)) and define(~readybugs,~openbugs and !link(~openbugs)) and ~readybugs" archive="yes"]]
129
130 > Nice! Could the specfuncsref be passed in %params? I'd like to avoid
131 > needing to change the prototype of every pagespec function, since several
132 > plugins define them too. --[[Joey]]
133
134 >> Maybe - it needs more thought.  I also considered it when I was going though changing all those plugins :).
135 >> My concern was that `%params` can contain other user-defined parameters,
136 >> e.g. `link(target, otherparameter)`, and that means that the specFuncs could be clobbered by a user (or other
137 >> weird security hole).  I thought it better to separate it, but I didn't think about it too hard.  I might move it to
138 >> the first parameter rather than the second.  Ikiwiki is my first real perl hacking and I'm still discovering
139 >> good ways to write things in perl.
140 >>
141 >>>> `%params` contains the parameters passed to `pagespec_match`, not
142 >>>> user-supplied parameters. The user-supplied parameter to a function
143 >>>> like `match_glob()` or `match_link()` is passed in the second positional parameter. --[[Joey]]
144
145 >>>>> OK.  That seems reasonable then.  The only problem is that my PERLfu is not strong enough to make it
146 >>>>> work.  I really have to wonder what substance was influencing the designers of PERL...
147 >>>>> I can't figure out how to use the %params.  And I'm pissed off enough with PERL that I'm not going
148 >>>>> to try and figure it out any more.  There are two patches below now.  The first one uses an extra
149 >>>>> argument and works.  The second one tries to use %params and doesn't - take your pick :-). -- [[Will]]
150
151 >> What do you think is best to do about `is_globlist()`?  At the moment it requires that the 'second word', as
152 >> delimited by a space and ignoring parens, is 'and' or 'or'.  This doesn't hold in the above example pagespecs (so I just hard wired it to 0 to test my patch).
153 >> My thought was just to search for 'and' or 'or' as words anywhere in the pagespec.  Thoughts?
154
155 >>> Dunno, we could just finish deprecating it. Or change the regexp to
156 >>> skip over spaces in parens. (`/[^\s]+\s+([^)]+)/`) --[[Joey]]
157
158 >>>> I think I have a working regexp now.
159
160 >> Oh, one more thing.  In pagespec_translate (now pagespec_makeperl), there is a part of the regular expression for `# any other text`.
161 >> This contained `()`, which has no effect.  I replaced that with `\(\)`, but that is a change in the definition of pagespecs unrelated to the
162 >> rest of this patch. In a related change, commands were not able to contain `)` in their parameters.  I've extended that so the cannot
163 >> contain `(` or `)`.  -- [[Will]]
164
165 >>> `[^\s()]+` is a character class matching all characters not spaces or
166 >>> parens. Since the pervious terminals in the regexp consume most
167 >>> occurances of an open paren or close paren, it's unlikely for one to
168 >>> get through to that part of the regexp. For example, "foo()" will be
169 >>> matched by the command matcher; "(foo)" will be matched by the open
170 >>> paren literal terminal. "foo(" and "foo)" can get through to the
171 >>> end, and would be matched as a page name, if it didn't exclude parens.
172 >>>
173 >>> So why exclude them? Well, consider "foo and(bar and baz)". We don't
174 >>> want it to match "and(" as a page name!
175 >>> 
176 >>> Escaping the parens in the character class actually changes nothing; the
177 >>> changed character class still matches all characters not spaces or
178 >>> parens. (Try it!).
179 >>> 
180 >>> Re commands containing '(', I don't really see any reason not to
181 >>> allow that, unless it breaks something. --[[Joey]]
182
183 >>>> Oh, I didn't realise you didn't need to escape parens inside [].  All else I
184 >>>> I understood.  I have stopped commands from containing parens because
185 >>>> once you allow that then you might have a extra level of depth in the parsing
186 >>>> of define() statements. -- [[Will]]
187
188 >>> Updated patch.  Moved the specFuncsRef to the front of the arg list.  Still haven't thought through the security implications of
189 >>> having it in `%params`.  I've also removed all the debugging `print` statements.  And I've updated the `is_globlist()` function.
190 >>> I think this is ready for people other than me to have a play.  It is not well enough tested to commit just yet.
191 >>> -- [[Will]]
192
193 I've lost track of the indent level, so I'm going back to not indented - I think this is a working [[patch]] taking into
194 account all comments above (which doesn't mean it is above reproach :) ).  --[[Will]]
195
196 > Very belated code review of last version of the patch:
197
198 > * `is_globlist` is no longer needed
199
200 >> Good :)
201
202 > * I don't understand why the pagespec match regexp is changed
203 >   from having flags `igx` to `ixgs`. Don't see why you
204 >   want `.` to match '\n` in it, and don't see any `.` in the regexp 
205 >   anyway?
206
207 >> Because you have to define all the named pagespecs in the pagespec, you sometimes end up with very long pagespecs.  I found it useful to split them over multiple lines.  That didn't work at one point and I added the 's' to make it work.  I may have further altered the regex since then to make the 's' redundant.  Remove it and see if multi-line pagespecs still work. :)
208
209 >>> Well, I can tell you that multi-line pagespecs are supported w/o
210 >>> your patch .. I use them all the time. The reason I find your
211 >>> use of `/s` unlikely is because without it `\s` already matches
212 >>> a newline. Only if you want to treat a newline as non-whitespace
213 >>> is `/s` typically necessary. --[[Joey]] 
214
215 > * Some changes of `@_` to `%params` in `pagespec_makeperl` do not
216 >   make sense to me. I don't see where \%params is defined and populated,
217 >   except with `\$params{specFunc}`.
218
219 >> I'm not a perl hacker.  This was a mighty battle for me to get going.
220 >> There is probably some battlefield carnage from my early struggles
221 >> learning perl left here. Part of this is that @_ / @params already
222 >> existed as a way of passing in extra parameters.  I didn't want to
223 >> pollute that top level namespace - just at my own parameter (a hash)
224 >> which contained the data I needed.
225
226 >>> I think I understand how the various `%params`
227 >>> (there's not just one) work in your code now, but it's really a mess.
228 >>> Explaining it in words would take pages.. It could be fixed by,
229 >>> in `pagespec_makeperl` something like:
230 >>> 
231 >>>     my %specFuncs;
232 >>>     push @_, specFuncs => \%specFuncs;
233 >>> 
234 >>> With that you have the hash locally available for populating
235 >>> inside `pagespec_makeperl`, and when the `match_*` functions
236 >>> are called the same hash data will be available inside their
237 >>> `@_` or `%params`. No need to change how the functions are called
238 >>> or do any of the other hacks.
239 >>>
240 >>> Currently, specFuncs is populated by building up code
241 >>> that recursively calls `pagespec_makeperl`, and is then
242 >>> evaluated when the pagespec gets evaluated. My suggested
243 >>> change to `%params` will break that, but that had to change 
244 >>> anyway.
245 >>>
246 >>> It probably has a security hole, and is certianly inviting
247 >>> one, since the pagespec definition is matched by a loose regexp (`.*`)
248 >>> and then subject to string interpolation before being evaluated
249 >>> inside perl code. I recently changed ikiwiki to never interpolate
250 >>> user-supplied strings when translating pagespecs, and that
251 >>> needs to happen here too. The obvious way, it seems to me,
252 >>> is to not generate perl code, but just directly run perl code that
253 >>> populates specFuncs.
254
255 >>>> I don't think this is as bad as you make out, but your addition of the
256 >>>> data array will break with the recursion my patch adds in pagespec_makeperl.
257 >>>> To fix that I'll need to pass a reference to that array into pagespec_makeperl.
258 >>>> I think I can then do the same thing to $params{specFuncs}.  -- [[Will]]
259
260 > * Seems that the only reason `match_glob` has to check for `~` is
261 >   because when a named spec appears in a pagespec, it is translated
262 >   to `match_glob("~foo")`. If, instead, `pagespec_makeperl` checked
263 >   for named specs, it could convert them into `check_named_spec("foo")`
264 >   and avoid that ugliness.
265
266 >> Yeah - I wanted to make named specs syntactically different on my first pass.  You are right in that this could be made a fallback - named specs always override pagenames.
267
268 > * The changes to `match_link` seem either unecessary, or incomplete.
269 >   Shouldn't it check for named specs and call
270 >   `check_named_spec_existential`?
271
272 >>  An earlier version did.  Then I realised it wasn't actually needed in that case - match_link() already included a loop that was like a type of existential matching.  Each time through the loop it would
273 >> call match_glob().  match_glob() in turn will handle the named spec.  I tested this version briefly and it seemed to work.  I remember looking at this again later and wondering if I had mis-understood
274 >> some of the logic in match_link(), which might mean there are cases where you would need an explicit call to check_named_spec_existential() - I never checked it properly after having that thought.
275
276 >>> In the common case, `match_link` does not call `match_glob`,
277 >>> because the link target it is being asked to check for is a single
278 >>> page name, not a glob.
279
280 >>>> A named pagespec should fall into the glob case.  These two pagespecs should be the same:
281
282     link(a*)
283
284 >>>> and
285
286     define(aStar, a*) and link(aStar)
287
288 >>>> In the first case, we want the pagespec to match any page that links to a page matching the glob.
289 >>>> In the second case, we want the pagespec to match any page that links to a page matching the named spec.
290 >>>> match_link() was already doing existential part.  The patches to this code were simply to remove the `lc()`
291 >>>> call from the named pagespec name.  Can that `lc` be removed entirely? -- [[Will]]
292
293 > * Generally, the need to modify `match_*` functions so that they
294 >   check for and handle named pagespecs seems suboptimal, if
295 >   only because there might be others people may want to use named
296 >   pagespecs with. It would be possible to move this check
297 >   to `pagespec_makeperl`, by having it check if the parameter
298 >   passed to a pagespec function looked like a named pagespec.
299 >   The only issue is that some pagespec functions take a parameter
300 >   that is not a page name at all, and it could be weird
301 >   if such a parameter were accidentially interpreted as a named
302 >   pagespec. (But, that seems unlikely to happen.)
303
304 >> Possibly.  I'm not sure which I prefer between the current solution and that one.  Each have advantages and disadvantages.
305 >> It really isn't much code for the match functions to add a call to check_named_spec_existential().
306
307 >>> But if a plugin adds its own match function, it has
308 >>> to explicitly call that code to support named pagespecs.
309
310 >>>> Yes, and it can do that in just three lines of code.  But if we automatically check for named pagespecs all the time we
311 >>>> potentially break any matching function that doesn't accept pages, or wants to use multiple arguments.
312
313 > * I need to check if your trick to avoid infinite recursion
314 >   works if there are two named specs that recursively
315 >   call one-another. I suspect it does, but will test this
316 >   myself..
317
318 >> It worked for me. :)
319
320 > * I also need to verify if memoizing the named pagespecs has
321 >   really guarded against very expensive pagespecs DOSing the wiki..
322
323 > --[[Joey]] 
324
325 >>  There is one issue that I've been thinking about that I haven't raised anywhere (or checked myself), and that is how this all interacts with page dependencies.
326 >>  Firstly, I'm not sure anymore that the `pagespec_merge` function will continue to work in all cases.
327
328 >>> The problem I can see there is that if two pagespecs
329 >>> get merged and both use `~foo` but define it differently,
330 >>> then the second definition might be used at a point when
331 >>> it shouldn't (but I haven't verified that really happens).
332 >>> That could certianly be a show-stopper. --[[Joey]] 
333
334 >>>> Even if that works, this is a good argument for having a syntactic difference between named pagespecs and normal pages.
335 >>>> If you're joining two pagespecs with 'or', you don't want a named pagespec in the first part overriding a page name in the
336 >>>> second part.  Oh, and I assume 'or' has the right operator precedence that "a and b or c" is "(a and b) or c", and not "a and (b or c)" -- [[Will]]
337
338 >>>>> Looks like its bracketed in the code anyway... -- [[Will]]
339
340 >>  Secondly, it seems that there are two types of dependency, and ikiwiki
341 >>  currently only handles one of them.  The first type is "Rebuild this
342 >>  page when any of these other pages changes" - ikiwiki handles this.
343 >>  The second type is "rebuild this page when set of pages referred to by
344 >>  this pagespec changes" - ikiwiki doesn't seem to handle this.  I
345 >>  suspect that named pagespecs would make that second type of dependency
346 >>  more important.  I'll try to come up with a good example. -- [[Will]]
347
348 >>> Hrm, I was going to build an example of this with backlinks, but it
349 >>> looks like that is handled as a special case at the moment (line 458 of
350 >>> render.pm).  I'll see if I can breapk
351 >>> things another way.  Fixing this properly would allow removal of that special case. -- [[Will]]
352
353 >>>> I can't quite understand the distinction you're trying to draw
354 >>>> between the two types of dependencies. Backlinks are a very special
355 >>>> case though and I'll be suprised if they fit well into pagespecs.
356 >>>> --[[Joey]] 
357
358 >>>>> The issue is that the existential pagespec matching allows you to build things that have similar
359 >>>>> problems to backlinks.
360 >>>>> e.g. the following inline:
361
362     \[[!inline pages="define(~done, link(done)) and link(~done)" archive=yes]]
363
364 >>>>> includes any page that links to a page that links to done.  Now imagine I add a new link to 'done' on
365 >>>>> some random page somewhere - a page which some other page links to which didn't previously get included - the set of pages accepted by the pagespec, and hence the set of
366 >>>>> pages inlined, will change.  But, there is no dependency anywhere on the page that I altered, so
367 >>>>> ikiwiki will not rebuild the page with the inline in it.  What is happening is that the page that I altered affects
368 >>>>> the set of pages matched by the pagespec without itself being matched by the pagespec, and hence included in the dependency list.
369
370 >>>>> To make this work well, I think you need to recognise two types of dependencies for each page (and no
371 >>>>> special cases for particular types of links, eg backlinks).  The first type of dependency says, "The content of
372 >>>>> this page depends upon the content of these other pages".  The `add_depends()` in the shortcuts
373 >>>>> plugin is of this form: any time the shortcuts page is edited, any page with a shortcut on it
374 >>>>> is rebuilt.  The inline plugin also needs to add dependencies of this form to detect when the inlined
375 >>>>> content changes.  By contrast, the map plugin does not need a dependency of this form, because it
376 >>>>> doesn't actually care about the content of any pages, just which pages it needs to include (which we'll handle next).
377
378 >>>>> The second type of dependency says, "The content of this page depends upon the exact set of pages matched
379 >>>>> by this pagespec".  The first type of dependency was about the content of some pages, the second type is about
380 >>>>> which pages get matched by a pagespec.  This is the type of dependency tracking that the map plugin needs.
381 >>>>> If the set of pages matched by map pagespec changes, then the page with the map on it needs to be rebuilt to show a different list of pages.
382 >>>>> Inline needs this type of dependency as well as the previous type - This type handles a change in which pages
383 >>>>> are inlined, the previous type handles a change in the content of any of those pages.  Shortcut does not need this type of
384 >>>>> dependency.  Most of the places that use `add_depends()` seem to need this type of dependency rather than the first type.
385
386 >>>>> Implementation Details:  The first type of dependency can be handled very similarly to the current
387 >>>>> dependency system.  You just need to keep a list of pages that the content depends upon.  You could
388 >>>>> keep that list as a pagespec, but if you do this you might want to check that the pagespec doesn't change,
389 >>>>> possibly by adding a dependency of the second type along with the dependency of the first type.
390
391 >>>>> The second type of dependency is a little more tricky.  For each page, we'd need a list of pagespecs that
392 >>>>> the page depended on, and for each pagespec you'd want to store the list of pages that currently match it.
393 >>>>> On refresh, you'd need to check each pagespec to see if the set of pages that match it has changed, and if
394 >>>>> that set has changed, then rebuild the dependent page(s).  Oh, and for this second type of dependency, I
395 >>>>> don't think you can merge pagespecs.  If I wanted to know if either "\*" or "link(done)" changes, then just checking
396 >>>>> to see if the set of pages matched by "\* or link(done)" changes doesn't work.
397
398 >>>>> The current system works because even though you usually want dependencies of the second type, the set of pages
399 >>>>> referred to by a pagespec can only change if one of those pages itself changes.  i.e. A dependency check of the
400 >>>>> first type will catch a dependency change of the second type with current pagespecs.
401 >>>>> This doesn't work with backlinks, and it doesn't work with existential matching.  Backlinks are currently special-cased.  I don't know
402 >>>>> how to special-case existential matching - I suspect you're better off just getting the dependency tracking right.
403
404 >>>>> I also tried to come up with other possible solutions: e.g. can we find the dependencies for a pagespec?  That
405 >>>>> would be the set of pages where a change on one of those pages could lead to a change in the set of pages matched by the pagespec.
406 >>>>> For old-style pagespecs without backlinks, the dependency set for a pagespec is the same as the set of pages the pagespec matches.
407 >>>>> Unfortunately, with existential matching, the set of pages that each
408 >>>>> pagespec depends upon can quickly become "*", which is not very useful.  -- [[Will]]
409
410 Patch updated to use closures rather than inline generated code for named pagespecs.  Also includes some new use of ErrorReason where appropriate. -- [[Will]]
411
412 ----
413
414     diff --git a/IkiWiki.pm b/IkiWiki.pm
415     index 061a1c6..1e78a63 100644
416     --- a/IkiWiki.pm
417     +++ b/IkiWiki.pm
418     @@ -1774,8 +1774,12 @@ sub pagespec_merge ($$) {
419         return "($a) or ($b)";
420      }
421      
422     -sub pagespec_translate ($) {
423     +# is perl really so dumb it requires a forward declaration for recursive calls?
424     +sub pagespec_translate ($$);
425     +
426     +sub pagespec_translate ($$) {
427         my $spec=shift;
428     +   my $specFuncsRef=shift;
429      
430         # Convert spec to perl code.
431         my $code="";
432     @@ -1789,7 +1793,9 @@ sub pagespec_translate ($) {
433                 |
434                         \)              # )
435                 |
436     -                   \w+\([^\)]*\)   # command(params)
437     +                   define\(\s*~\w+\s*,((\([^()]*\)) | ([^()]+))+\) # define(~specName, spec) - spec can contain parens 1 deep
438     +           |
439     +                   \w+\([^()]*\)   # command(params) - params cannot contain parens
440                 |
441                         [^\s()]+        # any other text
442                 )
443     @@ -1805,10 +1811,19 @@ sub pagespec_translate ($) {
444                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
445                         $code.=' '.$word;
446                 }
447     -           elsif ($word =~ /^(\w+)\((.*)\)$/) {
448     +           elsif ($word =~ /^define\(\s*(~\w+)\s*,(.*)\)$/s) {
449     +                   my $name = $1;
450     +                   my $subSpec = $2;
451     +                   my $newSpecFunc = pagespec_translate($subSpec, $specFuncsRef);
452     +                   return if $@ || ! defined $newSpecFunc;
453     +                   $specFuncsRef->{$name} = $newSpecFunc;
454     +                   push @data, qq{Created named pagespec "$name"};
455     +                   $code.="IkiWiki::SuccessReason->new(\$data[$#data])";
456     +           }
457     +           elsif ($word =~ /^(\w+)\((.*)\)$/s) {
458                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
459                                 push @data, $2;
460     -                           $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
461     +                           $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_, specFuncs => \$specFuncsRef)";
462                         }
463                         else {
464                                 push @data, qq{unknown function in pagespec "$word"};
465     @@ -1817,7 +1832,7 @@ sub pagespec_translate ($) {
466                 }
467                 else {
468                         push @data, $word;
469     -                   $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
470     +                   $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_, specFuncs => \$specFuncsRef)";
471                 }
472         }
473      
474     @@ -1826,7 +1841,7 @@ sub pagespec_translate ($) {
475         }
476      
477         no warnings;
478     -   return eval 'sub { my $page=shift; '.$code.' }';
479     +   return eval 'memoize (sub { my $page=shift; '.$code.' })';
480      }
481      
482      sub pagespec_match ($$;@) {
483     @@ -1839,7 +1854,7 @@ sub pagespec_match ($$;@) {
484                 unshift @params, 'location';
485         }
486      
487     -   my $sub=pagespec_translate($spec);
488     +   my $sub=pagespec_translate($spec, +{});
489         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
490                 if $@ || ! defined $sub;
491         return $sub->($page, @params);
492     @@ -1850,7 +1865,7 @@ sub pagespec_match_list ($$;@) {
493         my $spec=shift;
494         my @params=@_;
495      
496     -   my $sub=pagespec_translate($spec);
497     +   my $sub=pagespec_translate($spec, +{});
498         error "syntax error in pagespec \"$spec\""
499                 if $@ || ! defined $sub;
500         
501     @@ -1872,7 +1887,7 @@ sub pagespec_match_list ($$;@) {
502      sub pagespec_valid ($) {
503         my $spec=shift;
504      
505     -   my $sub=pagespec_translate($spec);
506     +   my $sub=pagespec_translate($spec, +{});
507         return ! $@;
508      }
509      
510     @@ -1919,6 +1934,68 @@ sub new {
511      
512      package IkiWiki::PageSpec;
513      
514     +sub check_named_spec($$;@) {
515     +   my $page=shift;
516     +   my $specName=shift;
517     +   my %params=@_;
518     +
519     +   return IkiWiki::ErrorReason->new("Unable to find specFuncs in params to check_named_spec()!")
520     +           unless exists $params{specFuncs};
521     +
522     +   my $specFuncsRef=$params{specFuncs};
523     +
524     +   return IkiWiki::ErrorReason->new("Named page spec '$specName' is not valid")
525     +           unless (substr($specName, 0, 1) eq '~');
526     +
527     +   if (exists $specFuncsRef->{$specName}) {
528     +           # remove the named spec from the spec refs
529     +           # when we recurse to avoid infinite recursion
530     +           my $sub = $specFuncsRef->{$specName};
531     +           delete $specFuncsRef->{$specName};
532     +           my $result = $sub->($page, %params);
533     +           $specFuncsRef->{$specName} = $sub;
534     +           return $result;
535     +   } else {
536     +           return IkiWiki::ErrorReason->new("Page spec '$specName' does not exist");
537     +   }
538     +}
539     +
540     +sub check_named_spec_existential($$$;@) {
541     +   my $page=shift;
542     +   my $specName=shift;
543     +   my $funcref=shift;
544     +   my %params=@_;
545     +
546     +   return IkiWiki::ErrorReason->new("Unable to find specFuncs in params to check_named_spec_existential()!")
547     +                   unless exists $params{specFuncs};
548     +   my $specFuncsRef=$params{specFuncs};
549     +   
550     +   return IkiWiki::ErrorReason->new("Named page spec '$specName' is not valid")
551     +           unless (substr($specName, 0, 1) eq '~');
552     +
553     +   if (exists $specFuncsRef->{$specName}) {
554     +           # remove the named spec from the spec refs
555     +           # when we recurse to avoid infinite recursion
556     +           my $sub = $specFuncsRef->{$specName};
557     +           delete $specFuncsRef->{$specName};
558     +           
559     +           foreach my $nextpage (keys %IkiWiki::pagesources) {
560     +                   if ($sub->($nextpage, %params)) {
561     +                           my $tempResult = $funcref->($page, $nextpage, %params);
562     +                           if ($tempResult) {
563     +                                   $specFuncsRef->{$specName} = $sub;
564     +                                   return IkiWiki::SuccessReason->new("Existential check of '$specName' matches because $tempResult");
565     +                           }
566     +                   }
567     +           }
568     +           
569     +           $specFuncsRef->{$specName} = $sub;
570     +           return IkiWiki::FailReason->new("No page in spec '$specName' was successfully matched");
571     +   } else {
572     +           return IkiWiki::ErrorReason->new("Named page spec '$specName' does not exist");
573     +   }
574     +}
575     +
576      sub derel ($$) {
577         my $path=shift;
578         my $from=shift;
579     @@ -1937,6 +2014,10 @@ sub match_glob ($$;@) {
580         my $glob=shift;
581         my %params=@_;
582         
583     +   if (substr($glob, 0, 1) eq '~') {
584     +           return check_named_spec($page, $glob, %params);
585     +   }
586     +
587         $glob=derel($glob, $params{location});
588      
589         my $regexp=IkiWiki::glob2re($glob);
590     @@ -1959,8 +2040,9 @@ sub match_internal ($$;@) {
591      
592      sub match_link ($$;@) {
593         my $page=shift;
594     -   my $link=lc(shift);
595     +   my $fullLink=shift;
596         my %params=@_;
597     +   my $link=lc($fullLink);
598      
599         $link=derel($link, $params{location});
600         my $from=exists $params{location} ? $params{location} : '';
601     @@ -1975,25 +2057,37 @@ sub match_link ($$;@) {
602                 }
603                 else {
604                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
605     -                           if match_glob($p, $link, %params);
606     +                           if match_glob($p, $fullLink, %params);
607                         $p=~s/^\///;
608                         $link=~s/^\///;
609                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
610     -                           if match_glob($p, $link, %params);
611     +                           if match_glob($p, $fullLink, %params);
612                 }
613         }
614         return IkiWiki::FailReason->new("$page does not link to $link");
615      }
616      
617      sub match_backlink ($$;@) {
618     -   return match_link($_[1], $_[0], @_);
619     +   my $page=shift;
620     +   my $backlink=shift;
621     +   my @params=@_;
622     +
623     +   if (substr($backlink, 0, 1) eq '~') {
624     +           return check_named_spec_existential($page, $backlink, \&match_backlink, @params);
625     +   }
626     +
627     +   return match_link($backlink, $page, @params);
628      }
629      
630      sub match_created_before ($$;@) {
631         my $page=shift;
632         my $testpage=shift;
633         my %params=@_;
634     -   
635     +
636     +   if (substr($testpage, 0, 1) eq '~') {
637     +           return check_named_spec_existential($page, $testpage, \&match_created_before, %params);
638     +   }
639     +
640         $testpage=derel($testpage, $params{location});
641      
642         if (exists $IkiWiki::pagectime{$testpage}) {
643     @@ -2014,6 +2108,10 @@ sub match_created_after ($$;@) {
644         my $testpage=shift;
645         my %params=@_;
646         
647     +   if (substr($testpage, 0, 1) eq '~') {
648     +           return check_named_spec_existential($page, $testpage, \&match_created_after, %params);
649     +   }
650     +
651         $testpage=derel($testpage, $params{location});
652      
653         if (exists $IkiWiki::pagectime{$testpage}) {