xref: /dokuwiki/inc/Parsing/ModeRegistry.php (revision a7e1021671c06230d0a9890646b3531d28d5d29a)
1<?php
2
3namespace dokuwiki\Parsing;
4
5use dokuwiki\Extension\PluginInterface;
6use dokuwiki\Extension\SyntaxPlugin;
7use dokuwiki\Parsing\ParserMode\Acronym;
8use dokuwiki\Parsing\ParserMode\AbstractMode;
9use dokuwiki\Parsing\ParserMode\Camelcaselink;
10use dokuwiki\Parsing\ParserMode\Entity;
11use dokuwiki\Parsing\ParserMode\Smiley;
12use dokuwiki\Parsing\Handler;
13use dokuwiki\Parsing\Parser;
14
15/**
16 * The set of parser modes for a single parse, plus the mode taxonomy.
17 *
18 * A ModeRegistry is built once per parse (see p_get_instructions) and
19 * carries the parse-specific state: the active syntax flavour, the
20 * block-EOL bookkeeping, and the sub-parser pool. It is a short-lived
21 * value, not a singleton — two parses in the same request (e.g. a plugin
22 * rendering bundled DW text inside an otherwise-Markdown page) get two
23 * independent registries.
24 *
25 * Three distinct concepts meet here; keep them apart:
26 *
27 *   1. The user's configured syntax PREFERENCE is a setting. Its source
28 *      of truth is $conf['syntax']. Read it only in UI code (editor
29 *      toolbar, admin settings, syntax-preference plugins) — never from
30 *      inside the parser. $conf['syntax'] enters the parser exactly once,
31 *      at the top-level entry point, as this registry's constructor
32 *      argument.
33 *
34 *   2. The active parse's syntax is a PARAMETER of this registry
35 *      (getSyntax / isDwPreferred / isMdPreferred). Every mode descends from
36 *      AbstractMode, which Parser::addMode() injects this registry into, so a
37 *      mode reads it via $this->registry; a plugin handle()/render() reads
38 *      $handler->getModeRegistry(). No code inside inc/Parsing/ reads
39 *      $conf['syntax'] directly.
40 *
41 *   3. The mode TAXONOMY — which mode names belong to which category — is
42 *      owned by this registry instance ($this->categories), seeded from the
43 *      immutable DEFAULT_CATEGORIES and extended with plugin_* entries during
44 *      loadPluginModes(). Core reads it through the instance accessors
45 *      (getModesForCategories / getCategories). The legacy global
46 *      $PARSER_MODES is kept only as a deprecated mirror, published during
47 *      loadPluginModes() for third-party plugins that read the array directly
48 *      and for the bundled info plugin — no core code reads it.
49 */
50class ModeRegistry
51{
52    // Category constants (preserving the historical 'substition' typo)
53    public const CATEGORY_CONTAINER    = 'container';
54    public const CATEGORY_BASEONLY     = 'baseonly';
55    public const CATEGORY_FORMATTING   = 'formatting';
56    public const CATEGORY_SUBSTITUTION = 'substition';
57    public const CATEGORY_PROTECTED    = 'protected';
58    public const CATEGORY_DISABLED     = 'disabled';
59    public const CATEGORY_PARAGRAPHS   = 'paragraphs';
60
61    /**
62     * The built-in mode taxonomy: category => list of mode names.
63     *
64     * Immutable defaults. Each registry starts from a copy of this in
65     * $this->categories; loadPluginModes() then merges plugin_* entries into
66     * that copy. Being a const, it is never mutated and so needs no resetting
67     * between parses or tests.
68     */
69    protected const DEFAULT_CATEGORIES = [
70        self::CATEGORY_CONTAINER  => ['listblock', 'table', 'gfm_listblock', 'gfm_table', 'gfm_quote', 'gfm_hr'],
71        self::CATEGORY_BASEONLY   => ['header', 'gfm_header'],
72        self::CATEGORY_FORMATTING => [
73            'strong', 'emphasis', 'underline', 'monospace',
74            'subscript', 'superscript', 'deleted', 'footnote',
75            'gfm_emphasis', 'gfm_emphasis_underscore', 'gfm_strong_underscore',
76            'gfm_emphasis_strong', 'gfm_emphasis_strong_underscore',
77            'gfm_deleted', 'gfm_backtick_single', 'gfm_backtick_double',
78        ],
79        self::CATEGORY_SUBSTITUTION => [
80            'acronym', 'smiley', 'wordblock', 'entity',
81            'camelcaselink', 'internallink', 'media', 'externallink',
82            'linebreak', 'emaillink', 'windowssharelink', 'filelink',
83            'notoc', 'nocache', 'multiplyentity', 'quotes', 'rss',
84            'gfm_link', 'gfm_media', 'gfm_escape', 'gfm_linebreak',
85            'gfm_html_entity',
86        ],
87        self::CATEGORY_PROTECTED  => ['preformatted', 'code', 'file', 'gfm_code', 'gfm_file'],
88        self::CATEGORY_DISABLED   => ['unformatted'],
89        self::CATEGORY_PARAGRAPHS => ['eol'],
90    ];
91
92    /** @var array{sort: int, mode: string, obj: AbstractMode}[]|null */
93    protected ?array $modes = null;
94
95    /** @var array<string, array{parsers: Parser[], inUse: int}> Pool of sub-parsers per exclusion-set identifier. */
96    protected array $subParsers = [];
97
98    /** @var string[] Modes that handle their own line endings (skip EOL connection) */
99    protected array $blockEolModes = [];
100
101    /** @var string the syntax flavour this parse runs under (dw, md, dw+md, md+dw) */
102    protected string $syntax;
103
104    /** @var array<string, string[]> this parse's mode taxonomy (defaults + plugin modes) */
105    protected array $categories = self::DEFAULT_CATEGORIES;
106
107    /**
108     * @param string $syntax the syntax flavour for this parse: one of
109     *     'dw', 'md', 'dw+md', 'md+dw'. This is the active-parse parameter,
110     *     not the user preference — see the class docblock.
111     */
112    public function __construct(string $syntax)
113    {
114        $this->syntax = $syntax;
115    }
116
117    /**
118     * The syntax flavour of this parse.
119     *
120     * @return string one of 'dw', 'md', 'dw+md', 'md+dw'
121     */
122    public function getSyntax(): string
123    {
124        return $this->syntax;
125    }
126
127    /**
128     * Get all mode names in the given categories of this parse's taxonomy.
129     *
130     * @param string[] $categories One or more CATEGORY_* constants
131     * @return string[] Unique list of mode names
132     */
133    public function getModesForCategories(array $categories): array
134    {
135        $modes = [];
136        foreach ($categories as $cat) {
137            if (isset($this->categories[$cat])) {
138                $modes = array_merge($modes, $this->categories[$cat]);
139            }
140        }
141        return array_unique($modes);
142    }
143
144    /**
145     * Get this parse's raw category map.
146     *
147     * @return array<string, string[]> Category name => list of mode names
148     */
149    public function getCategories(): array
150    {
151        return $this->categories;
152    }
153
154    /**
155     * Register a mode in a category of this parse's taxonomy.
156     *
157     * @param string $category One of the CATEGORY_* constants
158     * @param string $modeName The mode name to register
159     * @return void
160     */
161    public function registerMode(string $category, string $modeName): void
162    {
163        $this->categories[$category][] = $modeName;
164    }
165
166    /**
167     * Register a mode that handles its own line endings.
168     * Modes registered here will be skipped by Eol's connectTo().
169     *
170     * @param string $mode The mode name
171     * @return void
172     */
173    public function registerBlockEolMode(string $mode): void
174    {
175        $this->blockEolModes[] = $mode;
176    }
177
178    /**
179     * Get all modes that handle their own line endings.
180     *
181     * @return string[]
182     */
183    public function getBlockEolModes(): array
184    {
185        return $this->blockEolModes;
186    }
187
188    /**
189     * Whether DokuWiki is the preferred syntax (`dw` or `dw+md`).
190     *
191     * Modes that have to choose between DW-flavored and MD-flavored
192     * behavior at runtime read this flag. Compare with isMdPreferred()
193     * — exactly one of the two is true for any valid `$conf['syntax']`
194     * setting.
195     */
196    public function isDwPreferred(): bool
197    {
198        return in_array($this->syntax, ['dw', 'dw+md'], true);
199    }
200
201    /**
202     * Whether Markdown is the preferred syntax (`md` or `md+dw`).
203     */
204    public function isMdPreferred(): bool
205    {
206        return in_array($this->syntax, ['md', 'md+dw'], true);
207    }
208
209    /**
210     * Get all parser modes, fully instantiated and sorted by priority.
211     *
212     * This includes syntax plugins, built-in modes, formatting modes, and
213     * data-driven modes (smileys, acronyms, entities). Built once per
214     * registry and memoised for that registry's (short) lifetime.
215     *
216     * @return array[] Each entry is ['sort' => int, 'mode' => string, 'obj' => AbstractMode]
217     */
218    public function getModes(): array
219    {
220        if ($this->modes !== null) {
221            return $this->modes;
222        }
223
224        $this->modes = [];
225        $loadDw = in_array($this->syntax, ['dw', 'dw+md', 'md+dw'], true);
226        $loadMd = in_array($this->syntax, ['md', 'dw+md', 'md+dw'], true);
227
228        $this->loadPluginModes();
229        $this->loadAlwaysModes();
230        if ($loadDw) $this->loadDokuWikiModes();
231        if ($loadMd) $this->loadMarkdownModes();
232        $this->loadDataModes();
233
234        usort($this->modes, self::sortModes(...));
235        return $this->modes;
236    }
237
238    //region Sub-parser pool
239
240    /**
241     * Acquire a sub-parser for the given exclusion set.
242     *
243     * The registry maintains a pool of sub-parsers per exclusion key.
244     * Each acquire returns the next free instance from that pool;
245     * releaseSubParser must be called (with the same exclusion set)
246     * once the caller is done. If all instances in a pool are already
247     * checked out — re-entrancy on the same key — a fresh instance is
248     * built and appended to the pool. Real-world nesting for any one
249     * mode tops out at a handful of levels, so pool growth is bounded.
250     *
251     * Use this primitive when the caller wants to hold the parser
252     * across multiple parse() calls (e.g. iterating over list items).
253     * For single-shot use, prefer {@see withSubParser} so release is
254     * automatic.
255     *
256     * The returned Parser is shared infrastructure: callers must call
257     * `$parser->getHandler()->reset()` before each parse() to avoid
258     * inheriting state from a previous use.
259     *
260     * @param string[] $excludeCategories CATEGORY_* constants whose modes should be excluded
261     * @param string[] $excludeModes specific mode names to exclude in addition to category-based exclusions
262     */
263    public function acquireSubParser(
264        array $excludeCategories = [self::CATEGORY_BASEONLY],
265        array $excludeModes = []
266    ): Parser {
267        $key = $this->subParserKey($excludeCategories, $excludeModes);
268        $entry = $this->subParsers[$key] ?? ['parsers' => [], 'inUse' => 0];
269
270        if ($entry['inUse'] >= count($entry['parsers'])) {
271            $entry['parsers'][] = $this->buildSubParser($excludeCategories, $excludeModes);
272        }
273        $parser = $entry['parsers'][$entry['inUse']];
274        $entry['inUse']++;
275        $this->subParsers[$key] = $entry;
276        return $parser;
277    }
278
279    /**
280     * Release a previously-acquired sub-parser back to its pool.
281     *
282     * Should be paired with a prior {@see acquireSubParser} call for
283     * the same exclusion set. Callers must release in LIFO order with
284     * respect to other acquires on the same key — the implementation
285     * does not enforce LIFO, but out-of-order release would silently
286     * hand the same parser to two callers, so the caller is responsible
287     * for the discipline. Wrapping each acquire/release pair in a
288     * single try/finally (or using {@see withSubParser}) makes the
289     * ordering correct by construction.
290     *
291     * Throws if no acquire is outstanding for the given key — that
292     * indicates an acquire/release imbalance bug in the caller.
293     *
294     * @param string[] $excludeCategories
295     * @param string[] $excludeModes
296     * @throws \RuntimeException on release without a matching acquire
297     */
298    public function releaseSubParser(
299        array $excludeCategories = [self::CATEGORY_BASEONLY],
300        array $excludeModes = []
301    ): void {
302        $key = $this->subParserKey($excludeCategories, $excludeModes);
303        if (!isset($this->subParsers[$key]) || $this->subParsers[$key]['inUse'] <= 0) {
304            throw new \RuntimeException(
305                "releaseSubParser called without matching acquireSubParser for key '$key'"
306            );
307        }
308        $this->subParsers[$key]['inUse']--;
309    }
310
311    /**
312     * Run a callback with an exclusively-held sub-parser.
313     *
314     * Convenience wrapper around acquire/release. The parser is checked
315     * out for the duration of the callback, then released even if the
316     * callback throws. Preferred shape for single-shot sub-parses
317     * (one parse() call per acquire); use the explicit pair for cases
318     * where the parser is held across a loop or other longer scope.
319     *
320     * @template T
321     * @param string[] $excludeCategories
322     * @param string[] $excludeModes
323     * @param callable(Parser): T $fn
324     * @return T
325     */
326    public function withSubParser(
327        array $excludeCategories,
328        array $excludeModes,
329        callable $fn
330    ) {
331        $parser = $this->acquireSubParser($excludeCategories, $excludeModes);
332        try {
333            return $fn($parser);
334        } finally {
335            $this->releaseSubParser($excludeCategories, $excludeModes);
336        }
337    }
338
339    /**
340     * Build a fresh Parser preconfigured with every active mode except
341     * the ones excluded.
342     *
343     * Mode objects are cloned before being attached so that
344     * Parser::addMode() pointing each mode at the sub-parser's lexer does not
345     * clobber the main parser's mode references.
346     *
347     * @param string[] $excludeCategories
348     * @param string[] $excludeModes
349     */
350    protected function buildSubParser(
351        array $excludeCategories,
352        array $excludeModes
353    ): Parser {
354        $categories = $this->getCategories();
355        $excluded = $excludeModes;
356        foreach ($excludeCategories as $cat) {
357            $excluded = array_merge($excluded, $categories[$cat] ?? []);
358        }
359
360        $parser = new Parser(new Handler($this), $this);
361        foreach ($this->getModes() as $m) {
362            if (in_array($m['mode'], $excluded, true)) continue;
363            // Mode objects expose a single $Lexer slot which Parser::addMode()
364            // overwrites at registration time. The objects in $this->modes are
365            // already attached to the main parser's lexer; reusing them here
366            // would clobber that reference and break the main parse. Clone so
367            // the sub-parser gets its own copy with its own $Lexer slot.
368            $parser->addMode($m['mode'], clone $m['obj']);
369        }
370        return $parser;
371    }
372
373    /**
374     * Build the cache key used to identify a sub-parser exclusion set.
375     */
376    protected function subParserKey(array $excludeCategories, array $excludeModes): string
377    {
378        return implode(',', $excludeCategories) . '|' . implode(',', $excludeModes);
379    }
380
381    //endregion
382
383    //region Mode loading
384
385    /**
386     * Load syntax plugin modes and register them in their categories.
387     */
388    protected function loadPluginModes(): void
389    {
390        global $PARSER_MODES;
391
392        // Publish this parse's taxonomy into the deprecated global mirror right
393        // before plugins load — third-party plugins read $PARSER_MODES directly
394        // (often from their constructor) and the info plugin reads it at render.
395        // Core never reads the mirror; it reads $this->categories. The mirror is
396        // kept in sync incrementally below so a plugin loaded later sees the
397        // modes registered by plugins loaded before it (historical behaviour).
398        // @deprecated reading $PARSER_MODES directly — use the ModeRegistry API.
399        $PARSER_MODES = $this->categories;
400
401        $plugins = plugin_list('syntax');
402        foreach ($plugins as $p) {
403            $obj = plugin_load('syntax', $p);
404            if (!$obj instanceof PluginInterface) continue;
405            $this->categories[$obj->getType()][] = "plugin_$p";
406            $PARSER_MODES[$obj->getType()][] = "plugin_$p";
407            $this->modes[] = [
408                'sort' => $obj->getSort(),
409                'mode' => "plugin_$p",
410                'obj'  => $obj,
411            ];
412            unset($obj);
413        }
414    }
415
416    /**
417     * Load modes that have no equivalent in the other syntax.
418     * These are always active regardless of the syntax setting.
419     */
420    protected function loadAlwaysModes(): void
421    {
422        global $conf;
423
424        $modes = [
425            'strong', 'subscript', 'superscript',
426            'footnote', 'eol', 'preformatted',
427            'gfm_quote', 'gfm_hr',
428            'externallink', 'emaillink', 'windowssharelink',
429            'notoc', 'nocache', 'rss',
430        ];
431
432        if ($conf['typography']) {
433            $modes[] = 'quotes';
434            $modes[] = 'multiplyentity';
435        }
436
437        $this->instantiateModes($modes);
438    }
439
440    /**
441     * Load DokuWiki-specific modes for features that also exist in Markdown.
442     * Skipped when syntax is 'md'.
443     */
444    protected function loadDokuWikiModes(): void
445    {
446        $modes = [
447            'emphasis', 'deleted', 'code', 'header',
448            'linebreak', 'internallink', 'media', 'table',
449            'monospace', 'unformatted', 'file',
450        ];
451
452        // Underline only loads when DokuWiki is preferred. In MD-preferred
453        // modes, `__` means strong (via gfm_strong_underscore) and loading
454        // Underline here would conflict.
455        //
456        // Listblock only loads when DokuWiki is preferred. In MD-preferred
457        // modes, GfmListblock owns the `-`/`*`/`+` markers and zero-indent
458        // top-level items, which conflicts with DokuWiki's required-2-space-
459        // indent list model.
460        if ($this->isDwPreferred()) {
461            $modes[] = 'underline';
462            $modes[] = 'listblock';
463        }
464
465        $this->instantiateModes($modes);
466    }
467
468    /**
469     * Load Markdown-specific modes for features that also exist in DokuWiki.
470     * Skipped when syntax is 'dw'.
471     */
472    protected function loadMarkdownModes(): void
473    {
474        $modes = [
475            'gfm_escape', 'gfm_linebreak', 'gfm_html_entity',
476            'gfm_emphasis', 'gfm_emphasis_strong', 'gfm_deleted',
477            'gfm_backtick_single', 'gfm_backtick_double',
478            'gfm_header', 'gfm_link', 'gfm_media',
479            'gfm_code', 'gfm_file', 'gfm_table',
480        ];
481
482        // Underscore-based emphasis and strong only load when Markdown is
483        // preferred. In DW-preferred modes, `__` means underline and loading
484        // these would conflict.
485        //
486        // GfmListblock only loads when Markdown is preferred. In DW-preferred
487        // modes, the DokuWiki Listblock owns the `-`/`*` markers (with the
488        // 2-space indent rule); the two list models cannot co-exist.
489        if ($this->isMdPreferred()) {
490            $modes[] = 'gfm_emphasis_underscore';
491            $modes[] = 'gfm_strong_underscore';
492            $modes[] = 'gfm_emphasis_strong_underscore';
493            $modes[] = 'gfm_listblock';
494        }
495
496        $this->instantiateModes($modes);
497    }
498
499    /**
500     * Load data-driven modes that require constructor arguments
501     * (smileys, acronyms, entities) and optional config-gated modes.
502     */
503    protected function loadDataModes(): void
504    {
505        global $conf;
506
507        $obj = new Smiley(array_keys(getSmileys()));
508        $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'smiley', 'obj' => $obj];
509
510        $obj = new Acronym(array_keys(getAcronyms()));
511        $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'acronym', 'obj' => $obj];
512
513        $obj = new Entity(array_keys(getEntities()));
514        $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'entity', 'obj' => $obj];
515
516        if (!empty($conf['camelcase'])) {
517            $obj = new Camelcaselink();
518            $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'camelcaselink', 'obj' => $obj];
519        }
520    }
521
522    /**
523     * Instantiate mode classes by name and add them to the mode list.
524     *
525     * Mode names are split on `_` and each segment is PascalCased to form the
526     * class name (e.g. `gfm_emphasis_underscore` → `GfmEmphasisUnderscore`,
527     * `internallink` → `Internallink`, `strong` → `Strong`).
528     *
529     * @param string[] $modeNames
530     */
531    protected function instantiateModes(array $modeNames): void
532    {
533        foreach ($modeNames as $mode) {
534            $class = implode('', array_map(ucfirst(...), explode('_', $mode))); // snake_case to PascalCase
535            $class = 'dokuwiki\\Parsing\\ParserMode\\' . $class; // prepend namespace
536            $obj = new $class();
537            $this->modes[] = [
538                'sort' => $obj->getSort(),
539                'mode' => $mode,
540                'obj'  => $obj,
541            ];
542        }
543    }
544
545    //endregion
546
547    /**
548     * Callback function for usort
549     *
550     * @param array $a
551     * @param array $b
552     * @return int
553     */
554    public static function sortModes(array $a, array $b): int
555    {
556        return $a['sort'] <=> $b['sort'];
557    }
558}
559