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

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