lib/LaTeXML/Common/Model/RelaxNG.pm untested

filter: Statementstmt 0.0% 0 / 567 Branchbran 0.0% 0 / 278 Conditioncond 0.0% 0 / 99 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 1018 CC 140 SCAR 48.0
CC
140
Cov
0%
simplify
272.0
toTeX
272.0
extractContent
210.0
CRAP 121.3
1 # /=====================================================================\ #
2 # | LaTeXML::Common::Model::RelaxNG | #
3 # | Extract Model information from a RelaxNG schema | #
4 # |=====================================================================| #
5 # | Part of LaTeXML: | #
6 # | Public domain software, produced as part of work done by the | #
7 # | United States Government & not subject to copyright in the US. | #
8 # |---------------------------------------------------------------------| #
9 # | Bruce Miller <bruce.miller@nist.gov> #_# | #
10 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
11 # \=========================================================ooo==U==ooo=/ #
12 package LaTeXML::Common::Model::RelaxNG;
13 use strict;
14 use warnings;
15 use LaTeXML::Util::Pathname;
16 use LaTeXML::Common::XML;
17 use LaTeXML::Global;
18 use LaTeXML::Common::Object;
19 use LaTeXML::Common::Error;
20 use Scalar::Util qw(weaken);
21  
22 my $XMLPARSER = LaTeXML::Common::XML::Parser->new(); # [CONSTANT]
23  
24 # $schema->documentModules;
25  
26 # NOTE: Pending problem;
27 # Once we've got multiple namespaces in the schema,
28 # we haven't provided a means to specify the namespace <=> prefix mapping!
29 # It may be that rnc supplies that info, however!
30 # Alternatively, we could extract a symbol from the url,
31 # but it needs a sanity/collision check!
32  
33 # NOTE: When a schema is composed from various modules,
34 # some elements may not be "reachable" and (perhaps) should be removed
35  
36 # Scan a RelaxNG schema into an internal summary of modules.
37 sub new {
38 my ($class, $model, $name) = @_;
39 my $self = { name => $name, model => $model,
40 modules => [], elementdefs => {}, defs => {}, elements => {},
41 internal_grammars => 0 };
42 weaken($$self{model}); # circular back ref; weaked so can be garbage collected.
43 bless $self, $class;
44 return $self; }
45  
46 sub addSchemaDeclaration {
47 my ($self, $document, $tag) = @_;
48 $document->insertPI('latexml', RelaxNGSchema => $$self{name});
49 return; }
50  
51 sub loadSchema {
52 my ($self) = @_;
53 ProgressSpinup("Loading RelaxNG $$self{name}");
54 # Scan the schema file(s), and extract the info
55 my @schema = $self->scanExternal($$self{name});
56 if ($LaTeXML::DEBUG{relaxng}) {
57 Debug("========================\nRaw Schema");
58 map { showSchema($_) } @schema; }
59 @schema = map { $self->simplify($_) } @schema;
60 if ($LaTeXML::DEBUG{relaxng}) {
61 Debug("========================\nSimplified Schema");
62 map { showSchema($_) } @schema;
63 Debug("========================\nElements");
64 foreach my $tag (sort keys %{ $$self{elements} }) {
65 showSchema(['element', $tag, @{ $$self{elements}{$tag} }]); }
66 Debug("========================\nModules");
67 foreach my $mod (@{ $$self{modules} }) {
68 showSchema($mod); } }
69  
70 # The resulting @schema should contain the "start" of the grammar.
71 my ($startcontent) = $self->extractContent('#Document', @schema);
72 $$self{model}->addTagContent('#Document', sort keys %$startcontent);
73 if ($LaTeXML::DEBUG{relaxng}) {
74 Debug("========================\nStart\n" . join(', ', sort keys %$startcontent)); }
75  
76 # NOTE: Do something automatic about this too!?!
77 # We'll need to generate namespace prefixes for all namespaces found in the doc!
78 $$self{model}->registerDocumentNamespace(undef, "http://dlmf.nist.gov/LaTeXML");
79  
80 # Distill the info into allowed children & attributes for each element.
81 foreach my $tag (sort keys %{ $$self{elements} }) {
82 if ($tag eq 'ANY') {
83 # Ignore any internal structure (side effect of restricted names)
84 $$self{model}->addTagContent($tag, 'ANY');
85 next; }
86 my @body = @{ $$self{elements}{$tag} };
87 my ($content, $attributes) = $self->extractContent($tag, @body);
88 $$self{model}->addTagContent($tag, sort keys %$content);
89 $$self{model}->addTagAttribute($tag, sort keys %$attributes); }
90 # Extract definitions of symbols that define Schema Classes, too
91 foreach my $symbol (sort keys %{ $$self{defs} }) {
92 if ($symbol =~ /^grammar\d+:(.+?)\.class$/) {
93 my $name = $1;
94 my ($content, $attributes) = $self->extractContent($symbol, $$self{defs}{$symbol});
95 $$self{model}->setSchemaClass($name, $content); } }
96 ProgressSpindown("Loading RelaxNG $$self{name}");
97 return; }
98  
99 # Return two hashrefs for content & attributes
100 sub extractContent {
101 my ($self, $tag, @body) = @_;
102 my (%attr, %child);
103 my @savebody = @body;
104 while (@body) {
105 my $item = shift(@body);
106 if (ref $item eq 'ARRAY') {
107 my ($op, $name, @args) = @$item;
108 if ($op eq 'attribute') { $attr{$name} = 1; }
109 elsif ($op eq 'elementref') { $child{$name} = 1; }
110 elsif ($op eq 'doc') { }
111 elsif ($op eq 'combination') { push(@body, @args); }
112 elsif ($op eq 'grammar') { push(@body, $self->extractStart(@args)); }
113 elsif ($op eq 'module') { push(@body, $self->extractStart(@args)); }
114 elsif (($op eq 'ref') || ($op eq 'parentref')) {
115  
116 if (my $el = $$self{elementdefs}{$name}) {
117 push(@body, ['elementref', $el]); }
118 elsif (my $expansion = $$self{defs}{$name}) {
119 push(@body, $expansion); }
120 }
121 elsif ($op eq 'element') {
122 $child{$name} = 1; } # ???
123 elsif (($op eq 'value') || ($op eq 'data')) {
124 $child{'#PCDATA'} = 1; }
125 else { Warn('unexpected', $name, undef,
126 "Unknown child $op [$name] of element $tag in extractContent\n"); } }
127 elsif ($item eq '#PCDATA') { $child{'#PCDATA'} = 1; } }
128 return ({%child}, {%attr}); }
129  
130 #======================================================================
131 # Internal Representation of a RelaxNG Schema
132  
133 # This should build a usable intermediate structure
134 # WITHOUT side effects so that an (eventual) rnc parser
135 # can create the same intermediate!
136  
137 # Intermediate structure is a list of
138 # strings (representing the raw leave data)
139 # and recursive items of the following form:
140 # [$op, $name, @forms]
141 # where $op is one of:
142 # ref : defines or references a symbol
143 # parentref : references a symbol in parent's context [converted to ref by simplify]
144 # def,defchoice,definterleave : defines $name to be @forms.
145 # the last 2 combine w/existing values.
146 # elementref : references an element [Added by expand]
147 # grammar : Collects the a grammar's specifications; defined names are scoped (to $name),
148 # and the start is the effective pattern.
149 # (due to <grammar> or <externalRef> [Replaced by it's start by simplify]
150 # override : The @forms consist of a module, and the rest are replacement rules.
151 # (due to <include>) [Reduced to 'module' by simplify]
152 # element : $name is the tag QName, @forms are the content/attribute patterns
153 # attribute : $name is the attribute's QName, @forms are the patterns for the value.
154 # start : the grammar's start pattern ($name is undef)
155 # value : a literal value (typically for attributes)
156 # data : a data type
157 # doc : An annotation ($name is undef), the @forms are documentation strings.
158 # combination: combines various other patterns in @forms,
159 # $name is one of group, interleave, choice, optional, zeroOrMore, oneOrMore, list
160 # module : collects the specifications coming from a separate schema file
161 # for documentation purposes; $name is the name of the file
162 # [Recored in the modules list and replaced by its content in simplify]
163  
164 # Tricky is getting the thing scanned and creating blocks
165 # that should be separately documentable.
166 # Each external schema (whether include or external)?
167  
168 #======================================================================
169 # SCAN: Walk through the XML Representation compiling information about
170 # modules, definitions and elements.
171 #
172 # The representation built here has minimal processing done,
173 # so that hopefully it will be feasable to generate the same structure
174 # from a parsed RelaxNG Compact, without duplicating the processing.
175 #======================================================================
176 my %RNGNSMAP = ( # [CONSTANT]
177 "http://relaxng.org/ns/structure/1.0" => 'rng',
178 "http://relaxng.org/ns/compatibility/annotations/1.0" => 'rnga');
179  
180 local @LaTeXML::Common::Model::RelaxNG::PATHS = ();
181  
182 sub scanExternal {
183 my ($self, $name, $inherit_ns) = @_;
184 my $modname = $name; $modname =~ s/\.rn(g|c)$//;
185 my $paths = [@LaTeXML::Common::Model::RelaxNG::PATHS, @{ $STATE->lookupValue('SEARCHPATHS') }];
186 if (my $schemadoc = LaTeXML::Common::XML::RelaxNG->new($name, searchpaths => $paths)) {
187 my $uri = $schemadoc->URI;
188 ProgressSpinup("Loading RelaxNG schema from $uri");
189 local @LaTeXML::Common::Model::RelaxNG::PATHS
190 = (pathname_directory($schemadoc->URI), @LaTeXML::Common::Model::RelaxNG::PATHS);
191 my $node = $schemadoc->documentElement;
192 # Fetch any additional namespaces
193 foreach my $ns ($node->getNamespaces) {
194 my ($prefix, $nsuri) = ($ns->getLocalName, $ns->getData);
195 next if $nsuri =~ m|^http://relaxng.org|; # Ignore RelaxNG namespaces(!!)
196 $$self{model}->registerDocumentNamespace($prefix, $nsuri); }
197 my $mod = (['module', $modname, $self->scanPattern($node, $inherit_ns)]);
198 ProgressSpindown("Loading RelaxNG schema from $uri");
199 return $mod; }
200 else {
201 Warn('expected', $name, undef, "Failed to find RelaxNG schema for name '$name'");
202 return (); } }
203  
204 sub getRelaxOp {
205 my ($node) = @_;
206 return unless $node->nodeType == XML_ELEMENT_NODE;
207 my $ns = $node->namespaceURI;
208 my $prefix = $ns && $RNGNSMAP{$ns};
209 return ($prefix ? $prefix : "{$ns}") . ":" . $node->localname; }
210  
211 sub getElements {
212 my ($node) = @_;
213 return grep { $_->nodeType == XML_ELEMENT_NODE } $node->childNodes; }
214  
215 my $COMBINER_re = # [CONSTANT]
216 qr/group|interleave|choice|optional|zeroOrMore|oneOrMore|list/;
217  
218 sub scanPattern {
219 my ($self, $node, $inherit_ns) = @_;
220 if (my $relaxop = getRelaxOp($node)) {
221 my $ns = $node->getAttribute('ns') || $inherit_ns; # Possibly bind new namespace
222 # Element description
223 if ($relaxop eq 'rng:element') {
224 return $self->scanPattern_element($ns, $node); }
225 # Attribute description
226 elsif ($relaxop eq 'rng:attribute') {
227 return $self->scanPattern_attribute($ns, $node); }
228 # Various combiners
229 elsif ($relaxop =~ /^rng:($COMBINER_re)$/) {
230 my $op = $1;
231 return (['combination', $op, $self->scanChildren($ns, getElements($node))]); }
232 # Mixed is a combiner but includes #PCDATA
233 elsif ($relaxop eq 'rng:mixed') {
234 return (['combination', 'interleave', '#PCDATA', $self->scanChildren($ns, getElements($node))]); }
235 # Reference to a defined symbol, or parent grammar's defined symbol
236 elsif ($relaxop =~ /^rng:(ref|parentRef)$/) {
237 my $op = lc($1);
238 return ([$op, $node->getAttribute('name')]); }
239 elsif ($relaxop =~ /^rng:(empty|notAllowed)$/) { # Ignorable here
240 return (); }
241 elsif ($relaxop eq 'rng:text') {
242 return ('#PCDATA'); }
243 elsif ($relaxop eq 'rng:value') { # Not interested in details here.
244 return (['value', undef, $node->textContent]); }
245 elsif ($relaxop eq 'rng:data') { # Not interested in details here.
246 return (['data', undef, $node->getAttribute('type')]); }
247 # Include an external grammar
248 elsif ($relaxop eq 'rng:externalRef') {
249 return $self->scanExternal($node->getAttribute('href'), $ns); }
250 # Include an internal grammar
251 elsif ($relaxop eq 'rng:grammar') {
252 return (['grammar', "grammar" . (++$$self{internal_grammars}),
253 $self->scanGrammarContent($ns, getElements($node))]); }
254 elsif ($relaxop =~ /^rnga:documentation$/) {
255 return (['doc', undef, $node->textContent]); }
256 else {
257 Warn('misdefined', $relaxop, undef, "Didn't expect '$relaxop' in RelaxNG Schema (scanPattern)");
258 return (); } }
259 else {
260 return (); } }
261  
262 sub scanPattern_element {
263 my ($self, $ns, $node) = @_;
264 my @children = getElements($node);
265 if (my $name = $node->getAttribute('name')) {
266 return (['element', $$self{model}->encodeQName($ns, $name),
267 $self->scanChildren($ns, @children)]); }
268 else {
269 my $namenode = shift(@children);
270 my @names = $self->scanNameClass($namenode, 0, $ns);
271 return map { ['element', $_, $self->scanChildren($ns, @children)] } @names; } }
272  
273 sub scanPattern_attribute {
274 my ($self, $ns, $node) = @_;
275 my $xns = $node->getAttribute('ns'); # explicit declaration!
276 my @children = getElements($node);
277 if (my $name = $node->getAttribute('name')) {
278 return (['attribute', $$self{model}->encodeQName($xns, $name),
279 $self->scanChildren($ns, @children)]); }
280 else {
281 my $namenode = shift(@children);
282 my @names = $self->scanNameClass($namenode, 1, $ns);
283 return map { ['attribute', $_, $self->scanChildren($ns, @children)] } @names; } }
284  
285 sub scanChildren {
286 my ($self, $ns, @children) = @_;
287 return grep { $_ } map { ($self->scanPattern($_, $ns)) } @children; }
288  
289 sub scanGrammarContent {
290 my ($self, $ns, @content) = @_;
291 return map { $self->scanGrammarItem($_, $ns) } @content; }
292  
293 sub scanGrammarItem {
294 my ($self, $node, $inherit_ns) = @_;
295 if (my $relaxop = getRelaxOp($node)) {
296 my @children = getElements($node);
297 my $ns = $node->getAttribute('ns') || $inherit_ns; # Possibly bind new namespace
298 # The start element's content is returned
299 if ($relaxop eq 'rng:start') {
300 return (['start', undef, $self->scanChildren($ns, @children)]); }
301 elsif ($relaxop eq 'rng:define') {
302 my $name = $node->getAttribute('name');
303 my $op = $node->getAttribute('combine') || '';
304 return (['def' . $op, $name, $self->scanChildren($ns, @children)]); }
305 elsif ($relaxop eq 'rng:div') {
306 return $self->scanGrammarContent($ns, @children); }
307 elsif ($relaxop eq 'rng:include') {
308 my $name = $node->getAttribute('href');
309 my $paths = [@LaTeXML::Common::Model::RelaxNG::PATHS, @{ $STATE->lookupValue('SEARCHPATHS') }];
310 if (my $schemadoc = LaTeXML::Common::XML::RelaxNG->new($name, searchpaths => $paths)) {
311 local @LaTeXML::Common::Model::RelaxNG::PATHS
312 = (pathname_directory($schemadoc->URI), @LaTeXML::Common::Model::RelaxNG::PATHS);
313 my @patterns;
314 # Hopefully, just a file, not a URL?
315 my $doc = $schemadoc->documentElement;
316 # Ignore the grammar level, if any, since we do NOT establish a binding with include
317 if (getRelaxOp($doc) eq 'rng:grammar') {
318 my $nns = $doc->getAttribute('ns') || $inherit_ns; # Possibly bind new namespace
319 @patterns = $self->scanGrammarContent($nns, getElements($doc)); }
320 else {
321 @patterns = $self->scanPattern($doc, undef); }
322 # The rule is "includeContent", same as grammarContent
323 # except that it shouldn't have nested rng:include;
324 # we'll just assume there aren't any.
325 my $mod = $name; $mod =~ s/\.rn(g|c)$//;
326 if (my @replacements = $self->scanGrammarContent($ns, @children)) {
327 return (['override', undef, ['module', $mod, @patterns], @replacements]); }
328 else {
329 return (['module', $mod, @patterns]); } }
330 else {
331 return (); } } }
332 else {
333 return (); } }
334  
335 sub scanNameClass {
336 my ($self, $node, $forattr, $ns) = @_;
337 my $relaxop = getRelaxOp($node);
338 if ($relaxop eq 'rng:name') {
339 my ($decns, $name) = $$self{model}->decodeQName($node->textContent);
340 $ns = $decns if $decns;
341 return ($$self{model}->encodeQName(($forattr ? undef : $ns), $name)); }
342 elsif ($relaxop eq 'rng:anyName') {
343 my @exceptions = (); # Check for exceptions!
344 if (my @children = getElements($node)) {
345 @exceptions = map { $self->scanNameClass($_, $forattr, $ns) } @children; }
346 return ('ANY', @exceptions); }
347 elsif ($relaxop eq 'rng:nsName') {
348 my @exceptions = (); # Check for exceptions!
349 if (my @children = getElements($node)) {
350 @exceptions = map { $self->scanNameClass($_, $forattr, $ns) } @children; }
351 return ($$self{model}->encodeQName($node->getAttribute('ns') || $ns, '*'), @exceptions); }
352 elsif ($relaxop eq 'rng:choice') {
353 my %names = ();
354 foreach my $choice ($node->childNodes) {
355 map { $names{$_} = 1 } $self->scanNameClass($choice, $forattr, $ns); }
356 return ($names{ANY} ? ('ANY') : sort keys %names); }
357 elsif ($relaxop eq 'rng:except') {
358 my %names = ();
359 foreach my $choice (getElements($node)) {
360 map { $names{$_} = 1 } $self->scanNameClass($choice, $forattr, $ns); }
361 return map { "!$_" } ($names{ANY} ? ('ANY') : sort keys %names); }
362 else {
363 my $op = $node->nodeName;
364 Fatal('misdefined', $op, undef,
365 "Expected a RelaxNG name element (rng:name|rng:anyName|rng:nsName|rng:choice|rng:except), got '$op'");
366 return; } }
367  
368 #======================================================================
369 # Simplify
370 # Various simplifications:
371 # grammar : the binding of the separate space of defines is applied.
372 # and the result is simplified, and replaced by the start.
373 # module : stored for any documentation purposes, and simplified content returned.
374 # ref, parentref : replaced by a ref of appropriately scoped symbol.
375 # def : store the combined (but unexpanded) definitions
376  
377 # and
378 # symbols, elements are recorded.
379  
380 sub eqOp {
381 my ($form, $op) = @_;
382 return (ref $form eq 'ARRAY') && ($$form[0] eq $op); }
383  
384 sub extractStart {
385 my ($self, @items) = @_;
386 my @starts = ();
387 foreach my $item (@items) {
388 if (ref $item eq 'ARRAY') {
389 my ($op, $name, @args) = @$item;
390 if ($op eq 'start') { push(@starts, @args); }
391 elsif ($op eq 'module') { push(@starts, $self->extractStart(@args)); }
392 elsif ($op eq 'grammar') { push(@starts, $self->extractStart(@args)); }
393 } }
394 return @starts; }
395  
396 # NOTE: Reconsider this process.
397 # In particular, how we're returning throwing away stuff (after it gets recorded).
398 # Mainly it's an issue for being able to document a schema,
399 # having separate sections for each "module".
400  
401 # What order should we be simplifing and expanding?
402 # For documentable modules we want:
403 # the content, grammars NOT yet replaced by start,
404 # elementdef's sorted out
405 # For model extraction we also want
406 # models flattened, grammars replaced by start, all symbols joined & expanded
407 #####
408 # In Simplify
409 # grammar: extract & return start
410 # [for doc of a module, shouldn't do this, but for doc of an element, should!]
411 # [Actually, I'm not even sure how to document an embedded grammar]
412 # override: make replacements in module, return module
413 # [this should always happen]
414 # element : store in elements table
415 # [OK]
416 # ref : adjust name
417 # [OK]
418 # parentref : adjust name, convert to ref
419 # [OK]
420 # defchoice, definterleave, def: add to defns table, possibly combining with existing
421 # [OK]
422 # module : store in modules list, return contents
423 # [for doc,we'd like to return nothing? but for getting grammar start we want content?]
424  
425 sub simplify {
426 my ($self, $form, $binding, $parentbinding, $container) = @_;
427 if (ref $form eq 'ARRAY') {
428 my ($op, $name, @args) = @$form;
429 if ($op eq 'grammar') {
430 return (['grammar', $name, $self->simplify_args($name, $binding, $container, @args)]); }
431 elsif ($op eq 'override') {
432 return $self->simplify_override($binding, $parentbinding, $container, @args); }
433 elsif ($op eq 'module') {
434 my $module = ['module', $name];
435 push(@{ $$self{modules} }, $module); # Keep in order: push first, then scan contents
436 push(@$module, $self->simplify_args($binding, $parentbinding, $container, @args));
437 return ($module); }
438 elsif ($op eq 'element') {
439 @args = $self->simplify_args($binding, $parentbinding, "element:$name", @args);
440 push(@{ $$self{elements}{$name} }, @args);
441 return (['element', $name, @args]); }
442 elsif ($op =~ /^(ref|parentref)$/) {
443 my $qname = ($1 eq 'parentref' ? $parentbinding : $binding) . ":" . $name;
444 @args = $self->simplify_args($binding, $parentbinding, $container, @args);
445 $$self{usesname}{$qname}{$container} = 1 if $container;
446 return (['ref', $qname]); }
447 elsif ($op =~ /^def(choice|interleave|)$/) {
448 my $combination = $1 || 'group';
449 my $qname = $binding . ":" . $name;
450 $$self{usesname}{$qname}{$container} = 1 if $container;
451 @args = $self->simplify_args($binding, $parentbinding, "pattern:$qname", @args);
452  
453 # Special case: simple definition of an element
454 if (($combination eq 'group') && (scalar(@args) == 1) && eqOp($args[0], 'element')) {
455 $$self{elementdefs}{$qname} = $args[0][1];
456 $$self{elementreversedefs}{ $args[0][1] } = $qname;
457 return @args; }
458 else {
459 my $prev = $$self{defs}{$qname};
460 my $prevc = $$self{def_combiner}{$qname};
461 my @xargs = grep { !eqOp($_, 'doc') } @args; # Remove annotations
462 if ($prev) { # Previoud definition?
463 if (($combination eq 'group') && ($prevc eq 'group')) { # apparently RE-defining $qname?
464 $prev = undef; }
465 elsif (($combination eq 'group') && ($prevc ne 'group')) { # Use old combination!?!?!?!?
466 $combination = $prevc; } }
467 $$self{defs}{$qname} = simplifyCombination(['combination', $combination,
468 ($prev ? @$prev : ()), @xargs]);
469 $$self{def_combiner}{$qname} = $combination;
470 return ([$op, $qname, @args]); } }
471 else {
472 return ([$op, $name, $self->simplify_args($binding, $parentbinding, $container, @args)]); } }
473 else {
474 return ($form); } }
475  
476 sub simplify_args {
477 my ($self, $binding, $parentbinding, $container, @forms) = @_;
478 return map { $self->simplify($_, $binding, $parentbinding, $container) } @forms; }
479  
480 sub simplify_override {
481 my ($self, $binding, $parentbinding, $container, @args) = @_;
482 # Note that we do NOT simplify till we've made the replacements!
483 my ($module, @replacements) = @args;
484 my ($modop, $modname, @patterns) = @$module;
485 # Replace any start from @patterns by that from @replacement, if any.
486 if (my @replacement_start = grep { eqOp($_, 'start') } @replacements) {
487 @patterns = grep { !eqOp($_, 'start') } @patterns; }
488 foreach my $def (grep { (ref $_ eq 'ARRAY') && ($$_[0] =~ /^def/) } @replacements) {
489 my ($defop, $symbol) = @$def;
490 @patterns = grep { !(eqOp($_, $defop) && ($$_[1] eq $symbol)) } @patterns; }
491 # Recurse on the overridden module
492 return $self->simplify(['module', "$modname (overridden)", @patterns, @replacements],
493 $binding, $parentbinding, $container); }
494  
495 sub simplifyCombination {
496 my ($combination) = @_;
497 if ((ref $combination) && ($$combination[0] eq 'combination')) {
498 my ($c, $op, @stuff) = @$combination;
499 @stuff = map { simplifyCombination($_) } @stuff;
500 if ($op =~ /^(group|choice)$/) { # These can be flattened.
501 @stuff = map { ((ref $_) && ($$_[0] eq 'combination') && ($$_[1] eq $op)
502 ? @$_[2 .. $#$_] : ($_)) }
503 @stuff; }
504 return [$c, $op, @stuff]; }
505 else {
506 return $combination; } }
507  
508 #======================================================================
509 # For debugging...
510 sub showSchema {
511 my ($item, $level) = @_;
512 $level = 0 unless defined $level;
513 if (ref $item eq 'ARRAY') {
514 my ($op, $name, @args) = @$item;
515 if ($op eq 'doc') { $name = "..."; @args = (); }
516 Debug("" . (' ' x (2 * $level)) . $op . ($name ? " " . $name : ''));
517  
518 foreach my $arg (@args) {
519 showSchema($arg, $level + 1); } }
520 else {
521 Debug("" . (' ' x (2 * $level)) . $item); }
522 return; }
523  
524 #======================================================================
525 # Generate TeX documentation for a Schema
526 #======================================================================
527 # The svg schema can only just barely be read in and recognized,
528 # but it is structured in a way that makes a joke of our attempt at automatic documentation
529 my $SKIP_SVG = 1; # [CONFIGURABLE?]
530  
531 sub documentModules {
532 my ($self) = @_;
533 my $docs = "";
534 $$self{defined_patterns} = {};
535 foreach my $module (@{ $$self{modules} }) {
536 my ($op, $name, @content) = @$module;
537 next if $SKIP_SVG && $name =~ /:svg:/; # !!!!
538 $name =~ s/^urn:x-LaTeXML:RelaxNG://; # Remove the urn part.
539 $docs = join("\n", $docs,
540 "\\begin{schemamodule}{$name}",
541 (map { $self->toTeX($_) } @content),
542 "\\end{schemamodule}"); }
543 foreach my $name (sort keys %{ $$self{defined_patterns} }) {
544 if ($$self{defined_patterns}{$name} < 0) {
545 $docs =~ s/\\patternadd\{$name\}/\\patterndefadd{$name}/s; } }
546 return $docs; }
547  
548 sub cleanTeX {
549 my ($string) = @_;
550 return '\typename{text}' if $string eq '#PCDATA';
551 $string =~ s/\#/\\#/g;
552 $string =~ s/<([^>]*)>/\\texttt{$1}/g; # An apparent convention <sometext> == ttfont?
553 $string =~ s/_/\\_/g;
554 $string =~ s/\*/any/g; # ????
555 return $string; }
556  
557 sub cleanTeXName {
558 my ($string) = @_;
559 $string = cleanTeX($string);
560 $string =~ s/^ltx://;
561 # $string =~ s/:/../;
562 return $string; }
563  
564 sub toTeX {
565 my ($self, $object) = @_;
566 if (ref $object eq 'HASH') {
567 return join(', ', map { "$_=" . $self->toTeX($$object{$_}) } sort keys %$object); }
568 elsif (ref $object eq 'ARRAY') { # an object?
569 my ($op, $name, @data) = @$object;
570 if ($op eq 'doc') {
571 return join(' ', map { cleanTeX($_) } @data) . "\n"; }
572 elsif ($op eq 'ref') {
573 return $self->toTeX_ref($op, $name); }
574 elsif ($op =~ /^def(choice|interleave|)$/) {
575 return $self->toTeX_def($1, $name, @data); }
576 elsif ($op eq 'element') {
577 return $self->toTeX_element($name, @data); }
578 elsif ($op eq 'attribute') {
579 return $self->toTeX_attribute($name, @data); }
580 elsif ($op eq 'combination') {
581 return $self->toTeX_combination($name, @data); }
582 elsif ($op eq 'data') {
583 return "\\typename{" . cleanTeX($data[0]) . "}"; }
584 elsif ($op eq 'value') {
585 return '\attrval{' . cleanTeX($data[0]) . "}"; }
586 elsif ($op eq 'start') {
587 my ($docs, @spec) = $self->toTeXExtractDocs(@data);
588 my $content = join(' ', map { $self->toTeX($_) } @spec);
589 return "\\item[\\textit{Start}]\\textbf{==}\\ $content" . ($docs ? " \\par$docs" : ''); }
590 elsif ($op eq 'grammar') { # Don't otherwise mention it?
591 ## join("\n",'\item[\textit{Grammar}:] '.$name,
592 return join("\n", map { $self->toTeX($_) } @data); }
593 elsif ($op eq 'module') {
594 $name =~ s/^urn:x-LaTeXML:RelaxNG://; # Remove the urn part.
595 if (($name =~ /^svg/) && $SKIP_SVG) {
596 return '\item[\textit{Module }' . cleanTeX($name) . '] included.'; }
597 else {
598 return '\item[\textit{Module }\moduleref{' . cleanTeX($name) . '}] included.'; } }
599 else {
600 Warn('unexpected', $op, undef, "RelaxNG->toTeX: Unrecognized item $op");
601 return "[$op: " . join(', ', map { $self->toTeX($_) } @data) . "]"; } }
602 else {
603 return cleanTeX($object); } }
604  
605 sub toTeX_ref {
606 my ($self, $op, $name) = @_;
607 if (my $el = $$self{elementdefs}{$name}) {
608 $el = cleanTeXName($el);
609 return "\\elementref{$el}"; }
610 else {
611 $name =~ s/^\w+://; # Strip off qualifier!!!! (watch for clash in docs?)
612 return "\\patternref{" . cleanTeX($name) . "}"; } }
613  
614 sub toTeX_def {
615 my ($self, $combiner, $name, @data) = @_;
616 my $qname = $name;
617 $name =~ s/^\w+://; # Strip off qualifier!!!! (watch for clash in docs?)
618 $name = cleanTeX($name);
619 my ($docs, @spec) = $self->toTeXExtractDocs(@data);
620 my ($attr, $content) = $self->toTeXBody(@spec);
621 if ($combiner) {
622 my $body = $attr;
623 $body .= '\item[' . ($combiner eq 'choice' ? '\textbar=' : '\&=') . '] ' . $content if $content;
624 $$self{defined_patterns}{$name} = -1 unless defined $$self{defined_patterns}{$name};
625 return "\\patternadd{$name}{$docs}{$body}\n"; }
626 # elsif((scalar(@data)==1) && (ref $data[0] eq 'ARRAY') && ($data[0][0] eq 'grammar')){
627 else {
628 $attr = '\item[\textit{Attributes:}] \textit{empty}' if !$attr && ($name =~ /\\_attributes/);
629 $content = '\textit{empty}' if !$content && ($name =~ /\\_model/);
630 my $body = $attr;
631 $body .= '\item[\textit{Content}:] ' . $content if $content;
632 my ($xattr, $xcontent) = $self->toTeXBody($$self{defs}{$qname});
633 $body .= '\item[\textit{Expansion}:] ' . $xcontent
634 if !$attr && !$xattr && $xcontent && ($xcontent ne $content);
635 if ($name !~ /_(?:attributes|model)$/) { # Skip the "used by" if element-specific attributes or moel.
636  
637 if (my $uses = $self->getSymbolUses($qname)) {
638 $body .= '\item[\textit{Used by}:] ' . $uses; } }
639 if ((defined $$self{defined_patterns}{$name}) && ($$self{defined_patterns}{$name} > 0)) { # Already been defined???
640 return ''; }
641 else {
642 $$self{defined_patterns}{$name} = 1;
643 return "\\patterndef{$name}{$docs}{$body}\n"; } } }
644  
645 sub toTeX_element {
646 my ($self, $name, @data) = @_;
647 my $qname = $name;
648 $name =~ s/^ltx://;
649 $name = cleanTeXName($name);
650 my ($docs, @spec) = $self->toTeXExtractDocs(@data);
651 my ($attr, $content) = $self->toTeXBody(@spec);
652 $content = "\\typename{empty}" unless $content;
653 # Shorten display for element-specific attributes & model, ASSUMING they immediately folllow!
654 $attr = '' if $attr eq '\item[\textit{Attributes}:] \patternref{' . $name . '\\_attributes}';
655 $content = '' if $content eq '\patternref{' . $name . '\\_model}';
656 my $body = $attr;
657 $body .= '\item[\textit{Content}:] ' . $content if $content;
658 if (my $ename = $$self{elementreversedefs}{$qname}) {
659 if (my $uses = $self->getSymbolUses($ename)) {
660 $body .= '\item[\textit{Used by}:] ' . $uses; } }
661 return "\\elementdef{$name}{$docs}{$body}\n"; }
662  
663 sub toTeX_attribute {
664 my ($self, $name, @data) = @_;
665 $name = cleanTeXName($name);
666 my ($docs, @spec) = $self->toTeXExtractDocs(@data);
667 my $content = join(' ', map { $self->toTeX($_) } @spec) || '\typename{text}';
668 return "\\attrdef{$name}{$docs}{$content}"; }
669  
670 sub toTeX_combination {
671 my ($self, $name, @data) = @_;
672 if ($name eq 'group') {
673 return "(" . join(', ', map { $self->toTeX($_) } @data) . ")"; }
674 elsif ($name eq 'interleave') {
675 return "(" . join(' ~\&~ ', map { $self->toTeX($_) } @data) . ")"; } # ?
676 elsif ($name eq 'choice') {
677 return "(" . join(' ~\textbar~ ', map { $self->toTeX($_) } @data) . ")"; }
678 elsif ($name eq 'optional') {
679 if ((@data == 1) && eqOp($data[0], 'attribute')) {
680 return $self->toTeX($data[0]); }
681 else {
682 return $self->toTeX($data[0]) . "?"; } }
683 elsif ($name eq 'zeroOrMore') {
684 return $self->toTeX($data[0]) . "*"; }
685 elsif ($name eq 'oneOrMore') {
686 return $self->toTeX($data[0]) . "+"; }
687 elsif ($name eq 'list') {
688 return "(" . join(', ', map { $self->toTeX($_) } @data) . ")"; } # ?
689 else {
690 Warn('unexpected', $name, undef, "RelaxNG->toTeX: Unrecognized combination $name");
691 return; } }
692  
693 sub getSymbolUses {
694 my ($self, $qname) = @_;
695 if (my $uses = $$self{usesname}{$qname}) {
696 my @uses = sort keys %$uses;
697 @uses = grep { !/\bSVG./ } @uses if $SKIP_SVG; # !!!
698 return join(', ',
699 (map { /^pattern:[^:]*:(.*)$/ ? ('\patternref{' . cleanTeX($1) . '}') : () } @uses),
700 (map { /^pattern:[^:]*:(.*)$/ ? ('\patternref{' . cleanTeX($1) . '}') : () } @uses),
701 (map { /^element:(.*)$/ ? ('\elementref{' . cleanTeXName($1) . '}') : () } @uses)); }
702 else {
703 return ''; } }
704  
705 # Extract any documentation nodes from @data
706 sub toTeXExtractDocs {
707 my ($self, @data) = @_;
708 my $docs = "";
709 my @rest = ();
710 while (my $item = shift(@data)) {
711 if ((ref $item eq 'ARRAY') && ($$item[0] eq 'doc')) {
712 $docs .= $self->toTeX($item); }
713 else {
714 push(@rest, $item); } }
715 return ($docs, @rest); }
716  
717 # Format the attributes & content model of a named pattern or element.
718 # This generates a sequence of \item's to be put in a definition list.
719 sub toTeXBody {
720 my ($self, @data) = @_;
721 my (@attributes, @content, @patterns);
722 while (my $item = shift(@data)) {
723 if (ref $item eq 'ARRAY') {
724 my ($op, $name, @args) = @$item;
725 # NOTE: W/o the simplification of optional(attribute), above,
726 # we've got to do some extra work here!
727 if ($op eq 'attribute') {
728 push(@attributes, $self->toTeX($item)); }
729 elsif (($op eq 'combination') && ($name eq 'optional')
730 && (@args == 1) && eqOp($args[0], 'attribute')) {
731 unshift(@data, $args[0]); }
732 # Note dubious assumption about naming convention!
733 elsif (($op eq 'ref') && ($name =~ /[^a-zA-Z]attributes$/)) {
734 push(@patterns, $self->toTeX($item)); }
735 else {
736 push(@content, $self->toTeX($item)); } }
737 else {
738 push(@content, $self->toTeX($item)); } }
739 return
740 (join('', (@patterns
741 ? '\item[\textit{'
742 . ((grep { $_ !~ /[^a-zA-Z]attributes\}*?$/ } @patterns) ? 'Includes' : 'Attributes')
743 . '}:] '
744 . join(', ', @patterns)
745 : ''),
746 @attributes),
747 join(', ', @content)); }
748  
749 #======================================================================
750 1;
751  
752 __END__