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