Debian Codegraph @

mod/convert-to-dtd/src/main/com/thaiopensource/relaxng/output/dtd/DtdOutput.java

raw
1 package com.thaiopensource.relaxng.output.dtd;
2
3 import com.thaiopensource.relaxng.edit.AbstractPatternVisitor;
4 import com.thaiopensource.relaxng.edit.AbstractVisitor;
5 import com.thaiopensource.relaxng.edit.Annotated;
6 import com.thaiopensource.relaxng.edit.AnnotationChild;
7 import com.thaiopensource.relaxng.edit.AttributeAnnotation;
8 import com.thaiopensource.relaxng.edit.AttributePattern;
9 import com.thaiopensource.relaxng.edit.ChoiceNameClass;
10 import com.thaiopensource.relaxng.edit.ChoicePattern;
11 import com.thaiopensource.relaxng.edit.Comment;
12 import com.thaiopensource.relaxng.edit.Component;
13 import com.thaiopensource.relaxng.edit.ComponentVisitor;
14 import com.thaiopensource.relaxng.edit.CompositePattern;
15 import com.thaiopensource.relaxng.edit.Container;
16 import com.thaiopensource.relaxng.edit.DataPattern;
17 import com.thaiopensource.relaxng.edit.DefineComponent;
18 import com.thaiopensource.relaxng.edit.DivComponent;
19 import com.thaiopensource.relaxng.edit.ElementPattern;
20 import com.thaiopensource.relaxng.edit.GrammarPattern;
21 import com.thaiopensource.relaxng.edit.GroupPattern;
22 import com.thaiopensource.relaxng.edit.IncludeComponent;
23 import com.thaiopensource.relaxng.edit.InterleavePattern;
24 import com.thaiopensource.relaxng.edit.ListPattern;
25 import com.thaiopensource.relaxng.edit.MixedPattern;
26 import com.thaiopensource.relaxng.edit.NameClass;
27 import com.thaiopensource.relaxng.edit.NameNameClass;
28 import com.thaiopensource.relaxng.edit.OneOrMorePattern;
29 import com.thaiopensource.relaxng.edit.OptionalPattern;
30 import com.thaiopensource.relaxng.edit.Param;
31 import com.thaiopensource.relaxng.edit.Pattern;
32 import com.thaiopensource.relaxng.edit.PatternVisitor;
33 import com.thaiopensource.relaxng.edit.RefPattern;
34 import com.thaiopensource.relaxng.edit.TextPattern;
35 import com.thaiopensource.relaxng.edit.ValuePattern;
36 import com.thaiopensource.relaxng.edit.ZeroOrMorePattern;
37 import com.thaiopensource.relaxng.output.OutputDirectory;
38 import com.thaiopensource.relaxng.output.common.ErrorReporter;
39 import com.thaiopensource.relaxng.output.common.NameClassSplitter;
40 import com.thaiopensource.util.VoidValue;
41 import com.thaiopensource.xml.out.CharRepertoire;
42 import com.thaiopensource.xml.util.Naming;
43 import com.thaiopensource.xml.util.WellKnownNamespaces;
44
45 import java.io.IOException;
46 import java.io.Writer;
47 import java.util.HashSet;
48 import java.util.List;
49 import java.util.Set;
50 import java.util.Vector;
51
52 class DtdOutput {
53 private final boolean warnDatatypes;
54 private final String sourceUri;
55 private Writer writer;
56 private String encoding;
57 private CharRepertoire charRepertoire;
58 private final int indent;
59 private final int lineLength;
60 private final String lineSep;
61 private final StringBuffer buf = new StringBuffer();
62 private final List<ElementPattern> elementQueue = new Vector<ElementPattern>();
63 private final List<String> requiredParamEntities = new Vector<String>();
64 private final List<String> externallyRequiredParamEntities = new Vector<String>();
65 private final Set<String> doneParamEntities = new HashSet<String>();
66 private final Set<String> doneIncludes = new HashSet<String>();
67 private final Set<String> pendingIncludes = new HashSet<String>();
68 private final Analysis analysis;
69 private final GrammarPart part;
70 private final OutputDirectory od;
71 private final ErrorReporter er;
72 private final Set<String> reservedEntityNames;
73
74 private final PatternVisitor<VoidValue> topLevelContentModelOutput = new TopLevelContentModelOutput();
75 private final AbstractVisitor nestedContentModelOutput = new ContentModelOutput();
76 private final PatternVisitor<VoidValue> expandedContentModelOutput = new ExpandedContentModelOutput();
77 private final PatternVisitor<VoidValue> groupContentModelOutput = new GroupContentModelOutput();
78 private final PatternVisitor<VoidValue> choiceContentModelOutput = new ChoiceContentModelOutput();
79 private final PatternVisitor<VoidValue> occurContentModelOutput = new ParenthesizedContentModelOutput();
80 private final PatternVisitor<VoidValue> innerElementClassOutput = new InnerElementClassOutput();
81 private final PatternVisitor<VoidValue> expandedInnerElementClassOutput = new ExpandedInnerElementClassOutput();
82 private final AttributeOutput attributeOutput = new AttributeOutput();
83 private final AttributeOutput optionalAttributeOutput = new OptionalAttributeOutput();
84 private final PatternVisitor<VoidValue> topLevelSimpleTypeOutput = new TopLevelSimpleTypeOutput();
85 private final PatternVisitor<VoidValue> nestedSimpleTypeOutput = new SimpleTypeOutput();
86 private final PatternVisitor<VoidValue> valueOutput = new ValueOutput();
87 private final GrammarOutput grammarOutput = new GrammarOutput();
88
89 static private final String DTD_URI = "http://www.thaiopensource.com/ns/relaxng/dtd";
90
91 private DtdOutput(boolean warnDatatypes, String sourceUri, Analysis analysis, Set<String> reservedEntityNames, OutputDirectory od, ErrorReporter er) {
92 this.warnDatatypes = warnDatatypes;
93 this.sourceUri = sourceUri;
94 this.analysis = analysis;
95 this.reservedEntityNames = reservedEntityNames;
96 this.od = od;
97 this.er = er;
98 this.part = analysis.getGrammarPart(sourceUri);
99 try {
100 OutputDirectory.Stream stream = od.open(sourceUri, analysis.getEncoding(sourceUri));
101 this.encoding = stream.getEncoding();
102 this.writer = stream.getWriter();
103 this.charRepertoire = stream.getCharRepertoire();
104 }
105 catch (IOException e) {
106 throw new WrappedIOException(e);
107 }
108 this.lineSep = od.getLineSeparator();
109 this.indent = od.getIndent();
110 this.lineLength = od.getLineLength();
111 }
112
113 class ParenthesizedContentModelOutput extends AbstractPatternVisitor<VoidValue> {
114 public VoidValue visitPattern(Pattern p) {
115 buf.append('(');
116 p.accept(nestedContentModelOutput);
117 buf.append(')');
118 return VoidValue.VOID;
119 }
120
121 public VoidValue visitRef(RefPattern p) {
122 Pattern def = getBody(p.getName());
123 if (getContentType(def) == ContentType.DIRECT_SINGLE_ELEMENT)
124 ((ElementPattern)def).getNameClass().accept(nestedContentModelOutput);
125 else
126 visitPattern(p);
127 return VoidValue.VOID;
128 }
129
130 public VoidValue visitElement(ElementPattern p) {
131 if (getContentType(p) == ContentType.DIRECT_SINGLE_ELEMENT) {
132 p.getNameClass().accept(nestedContentModelOutput);
133 elementQueue.add(p);
134 }
135 else
136 visitPattern(p);
137 return VoidValue.VOID;
138 }
139 }
140
141 class ChoiceContentModelOutput extends ParenthesizedContentModelOutput {
142 public VoidValue visitOptional(OptionalPattern p) {
143 p.accept(nestedContentModelOutput);
144 return VoidValue.VOID;
145 }
146
147 public VoidValue visitOneOrMore(OneOrMorePattern p) {
148 p.accept(nestedContentModelOutput);
149 return VoidValue.VOID;
150 }
151
152 public VoidValue visitZeroOrMore(ZeroOrMorePattern p) {
153 p.accept(nestedContentModelOutput);
154 return VoidValue.VOID;
155 }
156 }
157
158 private class GroupContentModelOutput extends ChoiceContentModelOutput {
159 public VoidValue visitGroup(GroupPattern p) {
160 p.accept(nestedContentModelOutput);
161 return VoidValue.VOID;
162 }
163 }
164
165 class ContentModelOutput extends AbstractVisitor {
166 public VoidValue visitName(NameNameClass nc) {
167 String prefix = analysis.getElementPrefixForNamespaceUri(nc.getNamespaceUri());
168 if (prefix != null)
169 buf.append(prefix).append(':');
170 buf.append(nc.getLocalName());
171 return VoidValue.VOID;
172 }
173
174 public VoidValue visitChoice(ChoiceNameClass nc) {
175 List<NameClass> list = nc.getChildren();
176 boolean needSep = false;
177 for (int i = 0, len = list.size(); i < len; i++) {
178 if (needSep)
179 buf.append('|');
180 else
181 needSep = true;
182 list.get(i).accept(this);
183 }
184 return VoidValue.VOID;
185 }
186
187 public VoidValue visitElement(ElementPattern p) {
188 p.getNameClass().accept(this);
189 elementQueue.add(p);
190 return VoidValue.VOID;
191 }
192
193 public VoidValue visitRef(RefPattern p) {
194 Pattern def = getBody(p.getName());
195 if (getContentType(def) == ContentType.DIRECT_SINGLE_ELEMENT)
196 ((ElementPattern)def).getNameClass().accept(this);
197 else
198 paramEntityRef(p);
199 return VoidValue.VOID;
200 }
201
202 public VoidValue visitZeroOrMore(ZeroOrMorePattern p) {
203 p.getChild().accept(occurContentModelOutput);
204 buf.append('*');
205 return VoidValue.VOID;
206 }
207
208 public VoidValue visitOneOrMore(OneOrMorePattern p) {
209 p.getChild().accept(occurContentModelOutput);
210 ContentType t = getContentType(p);
211 if (t.isA(ContentType.MIXED_MODEL))
212 buf.append('*');
213 else
214 buf.append('+');
215 return VoidValue.VOID;
216 }
217
218 public VoidValue visitOptional(OptionalPattern p) {
219 p.getChild().accept(occurContentModelOutput);
220 buf.append('?');
221 return VoidValue.VOID;
222 }
223
224 public VoidValue visitText(TextPattern p) {
225 buf.append("#PCDATA");
226 return VoidValue.VOID;
227 }
228
229 public VoidValue visitMixed(MixedPattern p) {
230 buf.append("#PCDATA");
231 return VoidValue.VOID;
232 }
233
234 public VoidValue visitGroup(GroupPattern p) {
235 List<Pattern> list = p.getChildren();
236 boolean needSep = false;
237 final int len = list.size();
238 for (int i = 0; i < len; i++) {
239 Pattern member = list.get(i);
240 ContentType t = getContentType(member);
241 if (!t.isA(ContentType.EMPTY)) {
242 if (needSep)
243 buf.append(',');
244 else
245 needSep = true;
246 member.accept(groupContentModelOutput);
247 }
248 }
249 return VoidValue.VOID;
250 }
251
252 public VoidValue visitInterleave(InterleavePattern p) {
253 ContentType ct = getContentType(p);
254 if (ct == ContentType.INTERLEAVE_ZERO_OR_MORE_ELEMENT_CLASS || ct == ContentType.INTERLEAVE_MIXED_MODEL) {
255 buf.append('(');
256 p.accept(innerElementClassOutput);
257 buf.append(')');
258 buf.append('*');
259 }
260 else {
261 final List<Pattern> list = p.getChildren();
262 for (int i = 0, len = list.size(); i < len; i++) {
263 Pattern member = list.get(i);
264 ContentType t = getContentType(member);
265 if (!t.isA(ContentType.EMPTY))
266 member.accept(this);
267 }
268 }
269 return VoidValue.VOID;
270 }
271
272 public VoidValue visitChoice(ChoicePattern p) {
273 List<Pattern> list = p.getChildren();
274 boolean needSep = false;
275 final int len = list.size();
276 if (getContentType(p).isA(ContentType.MIXED_ELEMENT_CLASS)) {
277 for (int i = 0; i < len; i++) {
278 Pattern member = list.get(i);
279 if (getContentType(member).isA(ContentType.MIXED_ELEMENT_CLASS)) {
280 member.accept(nestedContentModelOutput);
281 needSep = true;
282 break;
283 }
284 }
285 }
286 for (int i = 0; i < len; i++) {
287 Pattern member = list.get(i);
288 ContentType t = getContentType(member);
289 if (t != ContentType.NOT_ALLOWED && t != ContentType.EMPTY && !t.isA(ContentType.MIXED_ELEMENT_CLASS)) {
290 if (needSep)
291 buf.append('|');
292 else
293 needSep = true;
294 member.accept(!t.isA(ContentType.ELEMENT_CLASS) ? choiceContentModelOutput : nestedContentModelOutput);
295 }
296 }
297 for (int i = 0; i < len; i++) {
298 Pattern member = list.get(i);
299 ContentType t = getContentType(member);
300 if (t == ContentType.NOT_ALLOWED) {
301 if (needSep)
302 buf.append(' ');
303 else
304 needSep = true;
305 member.accept(nestedContentModelOutput);
306 }
307 }
308 return VoidValue.VOID;
309 }
310
311 public VoidValue visitGrammar(GrammarPattern p) {
312 return getBody(DefineComponent.START).accept(this);
313 }
314 }
315
316 class TopLevelContentModelOutput extends ContentModelOutput {
317 public VoidValue visitZeroOrMore(ZeroOrMorePattern p) {
318 buf.append('(');
319 p.getChild().accept(nestedContentModelOutput);
320 buf.append(')');
321 buf.append('*');
322 return VoidValue.VOID;
323 }
324
325 public VoidValue visitOneOrMore(OneOrMorePattern p) {
326 buf.append('(');
327 p.getChild().accept(nestedContentModelOutput);
328 buf.append(')');
329 ContentType t = getContentType(p);
330 if (t.isA(ContentType.MIXED_MODEL))
331 buf.append('*');
332 else
333 buf.append('+');
334 return VoidValue.VOID;
335 }
336
337 public VoidValue visitOptional(OptionalPattern p) {
338 buf.append('(');
339 p.getChild().accept(nestedContentModelOutput);
340 buf.append(')');
341 buf.append('?');
342 return VoidValue.VOID;
343 }
344
345 public VoidValue visitElement(ElementPattern p) {
346 buf.append('(');
347 super.visitElement(p);
348 buf.append(')');
349 return VoidValue.VOID;
350 }
351
352 public VoidValue visitRef(RefPattern p) {
353 ContentType t = getContentType(p);
354 if (t.isA(ContentType.MIXED_MODEL))
355 super.visitRef(p);
356 else {
357 buf.append('(');
358 super.visitRef(p);
359 buf.append(')');
360 }
361 return VoidValue.VOID;
362 }
363
364 public VoidValue visitChoice(ChoicePattern p) {
365 buf.append('(');
366 p.accept(nestedContentModelOutput);
367 buf.append(')');
368 return VoidValue.VOID;
369 }
370
371 public VoidValue visitText(TextPattern p) {
372 buf.append('(');
373 p.accept(nestedContentModelOutput);
374 buf.append(')');
375 return VoidValue.VOID;
376 }
377
378 public VoidValue visitMixed(MixedPattern p) {
379 buf.append('(');
380 if (getContentType(p.getChild()) == ContentType.EMPTY)
381 buf.append("#PCDATA)");
382 else {
383 buf.append("#PCDATA|");
384 p.getChild().accept(innerElementClassOutput);
385 buf.append(')');
386 buf.append('*');
387 }
388 return VoidValue.VOID;
389 }
390
391 public VoidValue visitGroup(GroupPattern p) {
392 List<Pattern> list = p.getChildren();
393 Pattern main = null;
394 for (int i = 0, len = list.size(); i < len; i++) {
395 Pattern member = list.get(i);
396 if (!getContentType(member).isA(ContentType.EMPTY)) {
397 if (main == null)
398 main = member;
399 else {
400 buf.append('(');
401 nestedContentModelOutput.visitGroup(p);
402 buf.append(')');
403 return VoidValue.VOID;
404 }
405 }
406 }
407 if (main != null)
408 main.accept(this);
409 return VoidValue.VOID;
410 }
411 }
412
413 class ExpandedContentModelOutput extends ContentModelOutput {
414 public VoidValue visitElement(ElementPattern p) {
415 p.getNameClass().accept(this);
416 return VoidValue.VOID;
417 }
418 }
419
420 class PatternOutput extends AbstractPatternVisitor<VoidValue> {
421 public VoidValue visitPattern(Pattern p) {
422 return VoidValue.VOID;
423 }
424 }
425
426 class InnerElementClassOutput extends PatternOutput {
427 public VoidValue visitRef(RefPattern p) {
428 getBody(p.getName()).accept(expandedInnerElementClassOutput);
429 return VoidValue.VOID;
430 }
431
432 public VoidValue visitComposite(CompositePattern p) {
433 List<Pattern> list = p.getChildren();
434 boolean needSep = false;
435 int doneIndex = -1;
436 for (int i = 0, len = list.size(); i < len; i++) {
437 Pattern member = list.get(i);
438 ContentType ct = getContentType(member);
439 if (ct.isA(ContentType.MIXED_MODEL) || ct == ContentType.TEXT) {
440 member.accept(this);
441 needSep = true;
442 doneIndex = i;
443 break;
444 }
445 }
446 for (int i = 0, len = list.size(); i < len; i++) {
447 if (i != doneIndex) {
448 Pattern member = list.get(i);
449 if (getContentType(member) != ContentType.EMPTY) {
450 if (needSep)
451 buf.append('|');
452 else
453 needSep = true;
454 member.accept(this);
455 }
456 }
457 }
458 return VoidValue.VOID;
459 }
460
461 public VoidValue visitZeroOrMore(ZeroOrMorePattern p) {
462 p.getChild().accept(nestedContentModelOutput);
463 return VoidValue.VOID;
464 }
465
466 public VoidValue visitOneOrMore(OneOrMorePattern p) {
467 p.getChild().accept(nestedContentModelOutput);
468 return VoidValue.VOID;
469 }
470
471 public VoidValue visitMixed(MixedPattern p) {
472 if (getContentType(p.getChild()) == ContentType.EMPTY)
473 buf.append("#PCDATA");
474 else {
475 buf.append("#PCDATA|");
476 p.getChild().accept(this);
477 }
478 return VoidValue.VOID;
479 }
480
481 public VoidValue visitText(TextPattern p) {
482 buf.append("#PCDATA");
483 return VoidValue.VOID;
484 }
485 }
486
487 class ExpandedInnerElementClassOutput extends InnerElementClassOutput {
488 public VoidValue visitZeroOrMore(ZeroOrMorePattern p) {
489 p.getChild().accept(expandedContentModelOutput);
490 return VoidValue.VOID;
491 }
492 public VoidValue visitOneOrMore(OneOrMorePattern p) {
493 p.getChild().accept(expandedContentModelOutput);
494 return VoidValue.VOID;
495 }
496 }
497
498 class AttributeOutput extends PatternOutput {
499 void output(Pattern p) {
500 if (getAttributeType(p) != AttributeType.EMPTY)
501 p.accept(this);
502 }
503
504 void newlineIndent() {
505 buf.append(lineSep);
506 for (int i = 0; i < indent; i++)
507 buf.append(' ');
508 }
509
510 public VoidValue visitComposite(CompositePattern p) {
511 List<Pattern> list = p.getChildren();
512 for (int i = 0, len = list.size(); i < len; i++)
513 output(list.get(i));
514 return VoidValue.VOID;
515 }
516
517 public VoidValue visitMixed(MixedPattern p) {
518 output(p.getChild());
519 return VoidValue.VOID;
520 }
521
522 public VoidValue visitOneOrMore(OneOrMorePattern p) {
523 output(p.getChild());
524 return VoidValue.VOID;
525 }
526
527 public VoidValue visitZeroOrMore(ZeroOrMorePattern p) {
528 if (getAttributeType(p) != AttributeType.SINGLE)
529 er.warning("attribute_occur_approx", p.getSourceLocation());
530 optionalAttributeOutput.output(p.getChild());
531 return VoidValue.VOID;
532 }
533
534 public VoidValue visitRef(RefPattern p) {
535 ContentType t = getContentType(p);
536 if (t.isA(ContentType.EMPTY) && isRequired()) {
537 if (analysis.getParamEntityElementName(p.getName()) == null) {
538 newlineIndent();
539 paramEntityRef(p);
540 }
541 }
542 else
543 output(getBody(p.getName()));
544 return VoidValue.VOID;
545 }
546
547 public VoidValue visitAttribute(AttributePattern p) {
548 ContentType ct = getContentType(p.getChild());
549 if (ct == ContentType.NOT_ALLOWED)
550 return VoidValue.VOID;
551 List<NameNameClass> names = NameClassSplitter.split(p.getNameClass());
552 int len = names.size();
553 if (len > 1)
554 er.warning("attribute_occur_approx", p.getSourceLocation());
555 for (int i = 0; i < len; i++) {
556 int start = buf.length();
557 newlineIndent();
558 NameNameClass nnc = names.get(i);
559 String ns = nnc.getNamespaceUri();
560
561 if (!ns.equals("") && ns != NameClass.INHERIT_NS) {
562 String prefix = analysis.getPrefixForNamespaceUri(ns);
563 buf.append(prefix);
564 buf.append(':');
565 }
566 buf.append(nnc.getLocalName());
567 buf.append(' ');
568 if (ct == ContentType.VALUE)
569 p.getChild().accept(valueOutput);
570 else {
571 int typeStart = buf.length();
572 if (ct.isA(ContentType.SIMPLE_TYPE) || ct == ContentType.TEXT)
573 p.getChild().accept(topLevelSimpleTypeOutput);
574 else if (ct == ContentType.EMPTY) {
575 er.warning("empty_attribute_approx", p.getSourceLocation());
576 buf.append("CDATA");
577 }
578 int typeEnd = buf.length();
579 if (isRequired() && len == 1)
580 buf.append(" #REQUIRED");
581 else {
582 String dv = getDefaultValue(p);
583 if (dv == null)
584 buf.append(" #IMPLIED");
585 else {
586 buf.append(' ');
587 attributeValueLiteral(dv);
588 }
589 }
590 int lineStart = start + lineSep.length();
591 if (buf.length() - lineStart > lineLength && ct.isA(ContentType.ENUM)) {
592 ModelBreaker breaker = new ModelBreaker(buf.substring(lineStart, typeStart),
593 buf.substring(typeStart, typeEnd),
594 buf.substring(typeEnd),
595 lineLength);
596 buf.setLength(start);
597 while (breaker.hasNextLine()) {
598 buf.append(lineSep);
599 buf.append(breaker.nextLine());
600 }
601 }
602 }
603 }
604 return VoidValue.VOID;
605 }
606
607 boolean isRequired() {
608 return true;
609 }
610
611 public VoidValue visitChoice(ChoicePattern p) {
612 if (getAttributeType(p) != AttributeType.EMPTY)
613 er.warning("attribute_occur_approx", p.getSourceLocation());
614 optionalAttributeOutput.visitComposite(p);
615 return VoidValue.VOID;
616 }
617
618 public VoidValue visitOptional(OptionalPattern p) {
619 if (getAttributeType(p) != AttributeType.SINGLE)
620 er.warning("attribute_occur_approx", p.getSourceLocation());
621 optionalAttributeOutput.output(p.getChild());
622 return VoidValue.VOID;
623 }
624 }
625
626 class OptionalAttributeOutput extends AttributeOutput {
627 boolean isRequired() {
628 return false;
629 }
630 }
631
632 class SimpleTypeOutput extends PatternOutput {
633 public VoidValue visitText(TextPattern p) {
634 buf.append("CDATA");
635 return VoidValue.VOID;
636 }
637
638 public VoidValue visitValue(ValuePattern p) {
639 buf.append(p.getValue());
640 return VoidValue.VOID;
641 }
642
643 public VoidValue visitRef(RefPattern p) {
644 paramEntityRef(p);
645 return VoidValue.VOID;
646 }
647
648 public VoidValue visitData(DataPattern p) {
649 Datatypes.Info info = Datatypes.getInfo(p.getDatatypeLibrary(), p.getType());
650 if (info == null) {
651 er.warning("unrecognized_datatype", p.getSourceLocation());
652 buf.append("CDATA");
653 }
654 else {
655 if (warnDatatypes) {
656 if (!info.isExact())
657 er.warning("datatype_approx", p.getType(), info.closestType(), p.getSourceLocation());
658 else {
659 for (Param param : p.getParams())
660 er.warning("ignore_param", param.getName(), p.getType(), p.getSourceLocation());
661 if (p.getExcept() != null)
662 er.warning("ignore_except", p.getType(), p.getSourceLocation());
663 }
664 }
665 buf.append(info.closestType());
666 }
667 return VoidValue.VOID;
668 }
669
670 public VoidValue visitChoice(ChoicePattern p) {
671 List<Pattern> list = p.getChildren();
672 boolean needSep = false;
673 final int len = list.size();
674 for (int i = 0; i < len; i++) {
675 Pattern member = list.get(i);
676 ContentType t = getContentType(member);
677 if (t != ContentType.NOT_ALLOWED) {
678 if (needSep)
679 buf.append('|');
680 else
681 needSep = true;
682 member.accept(this);
683 }
684 }
685 for (int i = 0; i < len; i++) {
686 Pattern member = list.get(i);
687 ContentType t = getContentType(member);
688 if (t == ContentType.NOT_ALLOWED) {
689 if (needSep)
690 buf.append(' ');
691 else
692 needSep = true;
693 member.accept(this);
694 }
695 }
696 return VoidValue.VOID;
697 }
698 }
699
700 class TopLevelSimpleTypeOutput extends SimpleTypeOutput {
701 public VoidValue visitList(ListPattern p) {
702 if (warnDatatypes)
703 er.warning("list_approx", p.getSourceLocation());
704 buf.append("CDATA");
705 return VoidValue.VOID;
706 }
707
708 public VoidValue visitValue(ValuePattern p) {
709 if (getContentType(p) == ContentType.ENUM) {
710 buf.append('(');
711 super.visitValue(p);
712 buf.append(')');
713 }
714 else {
715 Datatypes.Info info = Datatypes.getInfo(p.getDatatypeLibrary(), p.getType());
716 if (info == null) {
717 er.warning("unrecognized_datatype", p.getSourceLocation());
718 buf.append("CDATA");
719 }
720 else {
721 String type = info.closestType();
722 if (warnDatatypes)
723 er.warning("value_approx", type, p.getSourceLocation());
724 buf.append(type);
725 }
726 }
727 return VoidValue.VOID;
728 }
729
730 public VoidValue visitChoice(ChoicePattern p) {
731 ContentType t = getContentType(p);
732 if (t == ContentType.ENUM) {
733 buf.append('(');
734 nestedSimpleTypeOutput.visitChoice(p);
735 buf.append(')');
736 }
737 else if (t == ContentType.SIMPLE_TYPE_CHOICE) {
738 if (warnDatatypes)
739 er.warning("datatype_choice_approx", p.getSourceLocation());
740 buf.append("CDATA");
741 }
742 else
743 super.visitChoice(p);
744 return VoidValue.VOID;
745 }
746
747 public VoidValue visitRef(RefPattern p) {
748 ContentType t = getContentType(p);
749 if (t == ContentType.ENUM) {
750 buf.append('(');
751 super.visitRef(p);
752 buf.append(')');
753 }
754 else if (t == ContentType.TEXT)
755 buf.append("CDATA");
756 else
757 super.visitRef(p);
758 return VoidValue.VOID;
759 }
760
761 }
762
763 private class ValueOutput extends PatternOutput {
764 public VoidValue visitValue(ValuePattern p) {
765 buf.append("CDATA #FIXED ");
766 attributeValueLiteral(p.getValue());
767 return VoidValue.VOID;
768 }
769
770 public VoidValue visitRef(RefPattern p) {
771 paramEntityRef(p);
772 return VoidValue.VOID;
773 }
774 }
775
776 class GrammarOutput implements ComponentVisitor<VoidValue> {
777 public void visitContainer(Container c) {
778 final List<Component> list = c.getComponents();
779 for (int i = 0, len = list.size(); i < len; i++)
780 (list.get(i)).accept(this);
781 }
782
783 public VoidValue visitDiv(DivComponent c) {
784 outputLeadingComments(c);
785 outputInitialChildComments(c);
786 visitContainer(c);
787 outputFollowingComments(c);
788 return VoidValue.VOID;
789 }
790
791 public VoidValue visitDefine(DefineComponent c) {
792 if (c.getName() == DefineComponent.START) {
793 outputLeadingComments(c);
794 outputFollowingComments(c);
795 if (analysis.getPattern() == analysis.getGrammarPattern())
796 c.getBody().accept(nestedContentModelOutput);
797 }
798 else {
799 if (getContentType(c.getBody()) == ContentType.DIRECT_SINGLE_ELEMENT)
800 outputElement((ElementPattern)c.getBody(), c);
801 else if (!doneParamEntities.contains(c.getName())) {
802 doneParamEntities.add(c.getName());
803 outputParamEntity(c);
804 }
805 }
806 outputQueuedElements();
807 return VoidValue.VOID;
808 }
809
810 public VoidValue visitInclude(IncludeComponent c) {
811 outputInclude(c);
812 return VoidValue.VOID;
813 }
814 }
815
816 void outputQueuedElements() {
817 for (int i = 0; i < elementQueue.size(); i++)
818 outputElement(elementQueue.get(i), null);
819 elementQueue.clear();
820 }
821
822 static void output(boolean warnDatatypes, Analysis analysis, OutputDirectory od, ErrorReporter er) throws IOException {
823 try {
824 new DtdOutput(warnDatatypes, analysis.getMainUri(), analysis, new HashSet<String>(), od, er).topLevelOutput();
825 }
826 catch (WrappedIOException e) {
827 throw e.cause;
828 }
829 }
830
831 void topLevelOutput() {
832 GrammarPattern grammarPattern = analysis.getGrammarPattern();
833 xmlDecl();
834 Pattern p = analysis.getPattern();
835 if (p != grammarPattern) {
836 outputLeadingComments(p);
837 p.accept(nestedContentModelOutput);
838 outputQueuedElements();
839 }
840 if (grammarPattern != null) {
841 outputLeadingComments(grammarPattern);
842 outputInitialChildComments(grammarPattern);
843 grammarOutput.visitContainer(grammarPattern);
844
845 outputFollowingComments(grammarPattern);
846 }
847 close();
848 }
849
850 void subOutput(GrammarPattern grammarPattern) {
851 xmlDecl();
852 outputLeadingComments(grammarPattern);
853 outputInitialChildComments(grammarPattern);
854 grammarOutput.visitContainer(grammarPattern);
855 outputFollowingComments(grammarPattern);
856 close();
857 }
858
859 void xmlDecl() {
860 write("<?xml encoding=\"");
861 write(encoding);
862 write("\"?>");
863 outputNewline();
864 }
865
866 ContentType getContentType(Pattern p) {
867 return analysis.getContentType(p);
868 }
869
870 AttributeType getAttributeType(Pattern p) {
871 return analysis.getAttributeType(p);
872 }
873
874 Pattern getBody(String name) {
875 return analysis.getBody(name);
876 }
877
878 void paramEntityRef(RefPattern p) {
879 String name = p.getName();
880 buf.append('%');
881 buf.append(name);
882 buf.append(';');
883 requiredParamEntities.add(name);
884 }
885
886 void attributeValueLiteral(String value) {
887 buf.append('\'');
888 for (int i = 0, len = value.length(); i < len; i++) {
889 char c = value.charAt(i);
890 switch (c) {
891 case '<':
892 buf.append("&lt;");
893 break;
894 case '&':
895 buf.append("&amp;");
896 break;
897 case '\'':
898 buf.append("&apos;");
899 break;
900 case '"':
901 buf.append("&quot;");
902 break;
903 case '\r':
904 buf.append("&#xD;");
905 break;
906 case '\n':
907 buf.append("&#xA;");
908 break;
909 case '\t':
910 buf.append("&#9;");
911 break;
912 default:
913 buf.append(c);
914 break;
915 }
916 }
917 buf.append('\'');
918 }
919
920 void outputRequiredComponents() {
921 for (int i=0; i < requiredParamEntities.size(); i++) {
922 String name = requiredParamEntities.get(i);
923 Component c = part.getWhereProvided(name);
924 if (c == null)
925 externallyRequiredParamEntities.add(name);
926 else if (c instanceof DefineComponent) {
927 if (!doneParamEntities.contains(name)) {
928 doneParamEntities.add(name);
929 outputParamEntity((DefineComponent)c);
930 }
931 }
932 else
933 outputInclude((IncludeComponent)c);
934 }
935 requiredParamEntities.clear();
936 }
937
938 void outputInclude(IncludeComponent inc) {
939 String href = inc.getUri();
940 if (doneIncludes.contains(href))
941 return;
942 if (pendingIncludes.contains(href)) {
943 er.error("sorry_include_depend", inc.getSourceLocation());
944 return;
945 }
946 pendingIncludes.add(href);
947 DtdOutput sub = new DtdOutput(warnDatatypes, href, analysis, reservedEntityNames, od, er);
948 GrammarPattern g = (GrammarPattern)analysis.getSchema(href);
949 sub.subOutput(g);
950 requiredParamEntities.addAll(sub.externallyRequiredParamEntities);
951 outputRequiredComponents();
952 outputLeadingComments(inc);
953 String entityName = genEntityName(inc);
954 outputNewline();
955 write("<!ENTITY % ");
956 write(entityName);
957 write(" SYSTEM ");
958 write('"');
959 // XXX deal with " in filename (is it allowed by URI syntax?)
960 write(od.reference(sourceUri, href));
961 write('"');
962 write('>');
963 outputNewline();
964 write('%');
965 write(entityName);
966 write(';');
967 outputNewline();
968 outputFollowingComments(inc);
969 doneIncludes.add(href);
970 pendingIncludes.remove(href);
971 }
972
973 String genEntityName(IncludeComponent inc) {
974 String entityName = getAttributeAnnotation(inc, DTD_URI, "entityName");
975 if (entityName != null) {
976 entityName = entityName.trim();
977 if (!Naming.isNcname(entityName)) {
978 er.warning("entity_name_not_ncname", entityName, inc.getSourceLocation());
979 entityName = null;
980 }
981 }
982 if (entityName == null) {
983 String uri = inc.getUri();
984 int slash = uri.lastIndexOf('/');
985 if (slash >= 0)
986 uri = uri.substring(slash + 1);
987 int dot = uri.lastIndexOf('.');
988 if (dot > 0)
989 uri = uri.substring(0, dot);
990 if (Naming.isNcname(uri))
991 entityName = uri;
992 }
993 if (entityName == null)
994 entityName = "ent";
995 if (!reserveEntityName(entityName)) {
996 for (int i = 1;; i++) {
997 String tem = entityName + Integer.toString(i);
998 if (reserveEntityName(tem)) {
999 entityName = tem;
1000 break;
1001 }
1002 }
1003 }
1004 return entityName;
1005 }
1006
1007 private boolean reserveEntityName(String name) {
1008 if (reservedEntityNames.contains(name))
1009 return false;
1010 reservedEntityNames.add(name);
1011 return true;
1012 }
1013
1014 void outputParamEntity(DefineComponent def) {
1015 String name = def.getName();
1016 Pattern body = def.getBody();
1017 ContentType t = getContentType(body);
1018 buf.setLength(0);
1019 boolean wrap = true;
1020 if (t.isA(ContentType.MODEL_GROUP) || t.isA(ContentType.NOT_ALLOWED) || t.isA(ContentType.MIXED_ELEMENT_CLASS))
1021 body.accept(nestedContentModelOutput);
1022 else if (t.isA(ContentType.MIXED_MODEL))
1023 body.accept(topLevelContentModelOutput);
1024 else if (t.isA(ContentType.EMPTY)) {
1025 attributeOutput.output(body);
1026 wrap = false;
1027 }
1028 else if (t.isA(ContentType.ENUM))
1029 body.accept(nestedSimpleTypeOutput);
1030 else if (t.isA(ContentType.VALUE)) {
1031 body.accept(valueOutput);
1032 wrap = false;
1033 }
1034 else if (t.isA(ContentType.SIMPLE_TYPE))
1035 body.accept(topLevelSimpleTypeOutput);
1036 String replacement = buf.toString();
1037 outputRequiredComponents();
1038 outputLeadingComments(def);
1039 String elementName = analysis.getParamEntityElementName(name);
1040 if (elementName != null) {
1041 if (replacement.length() > 0) {
1042 outputNewline();
1043 write("<!ATTLIST ");
1044 write(elementName);
1045 outputAttributeNamespaces(body);
1046 write(replacement);
1047 write('>');
1048 outputNewline();
1049 }
1050 }
1051 else {
1052 doneParamEntities.add(name);
1053 outputNewline();
1054 String prefix = "<!ENTITY % " + name + " \"";
1055 String suffix = "\">";
1056 if (!wrap) {
1057 write(prefix);
1058 write(replacement);
1059 write(suffix);
1060 outputNewline();
1061 }
1062 else
1063 outputModelBreak(prefix, replacement, suffix);
1064 }
1065 outputFollowingComments(def);
1066 }
1067
1068 private void outputModelBreak(String prefix, String replacement, String suffix) {
1069 for (ModelBreaker breaker = new ModelBreaker(prefix, replacement, suffix, lineLength); breaker.hasNextLine();) {
1070 write(breaker.nextLine());
1071 outputNewline();
1072 }
1073 }
1074
1075 void outputElement(ElementPattern p, Annotated def) {
1076 buf.setLength(0);
1077 Pattern content = p.getChild();
1078 ContentType ct = getContentType(content);
1079 if (ct == ContentType.EMPTY)
1080 ;
1081 else if (ct == ContentType.MIXED_ELEMENT_CLASS) {
1082 er.warning("mixed_choice_approx", p.getSourceLocation());
1083 buf.append("(");
1084 content.accept(nestedContentModelOutput);
1085 buf.append(")*");
1086 }
1087 else if (ct.isA(ContentType.SIMPLE_TYPE)) {
1088 if (warnDatatypes)
1089 er.warning("data_content_approx", p.getSourceLocation());
1090 buf.append("(#PCDATA)");
1091 }
1092 else if (ct == ContentType.NOT_ALLOWED)
1093 return; // leave it undefined
1094 else
1095 content.accept(topLevelContentModelOutput);
1096 String contentModel = buf.length() == 0 ? "EMPTY" : buf.toString();
1097 buf.setLength(0);
1098 attributeOutput.output(content);
1099 String atts = buf.toString();
1100 outputRequiredComponents();
1101 if (def != null)
1102 outputLeadingComments(def);
1103 outputLeadingComments(p);
1104 List<NameNameClass> names = NameClassSplitter.split(p.getNameClass());
1105 for (NameNameClass name : names) {
1106 final String ns = name.getNamespaceUri();
1107 String qName = name.getLocalName();
1108 final String prefix = analysis.getElementPrefixForNamespaceUri(ns);
1109 if (prefix != null)
1110 qName = prefix + ":" + qName;
1111 outputNewline();
1112 outputModelBreak("<!ELEMENT " + qName + " ", contentModel, ">");
1113 boolean needXmlns;
1114 if (ns == NameClass.INHERIT_NS)
1115 needXmlns = false;
1116 else if (prefix == null)
1117 needXmlns = true;
1118 else
1119 needXmlns = !analysis.getAttributeNamespaces(content).contains(ns);
1120 if (atts.length() != 0 || needXmlns) {
1121 write("<!ATTLIST ");
1122 write(qName);
1123 if (needXmlns) {
1124 outputNewline();
1125 outputIndent();
1126 if (prefix != null) {
1127 write("xmlns:");
1128 write(prefix);
1129 }
1130 else
1131 write("xmlns");
1132 write(" CDATA #FIXED ");
1133 buf.setLength(0);
1134 attributeValueLiteral(ns);
1135 write(buf.toString());
1136 }
1137 if (atts.length() != 0)
1138 outputAttributeNamespaces(content);
1139 write(atts);
1140 write('>');
1141 outputNewline();
1142 }
1143 }
1144 if (def != null)
1145 outputFollowingComments(def);
1146 }
1147
1148 void outputAttributeNamespaces(Pattern p) {
1149 Set<String> namespaces = analysis.getAttributeNamespaces(p);
1150 for (String ns : namespaces) {
1151 String prefix = analysis.getPrefixForNamespaceUri(ns);
1152 outputNewline();
1153 outputIndent();
1154 write("xmlns:");
1155 write(prefix);
1156 write(" CDATA #FIXED ");
1157 buf.setLength(0);
1158 attributeValueLiteral(ns);
1159 write(buf.toString());
1160 }
1161 }
1162
1163 void outputLeadingComments(Annotated a) {
1164 outputComments(a.getLeadingComments());
1165 }
1166
1167 void outputInitialChildComments(Annotated a) {
1168 outputComments(a.getChildElementAnnotations());
1169 }
1170
1171 void outputFollowingComments(Annotated a) {
1172 outputComments(a.getFollowingElementAnnotations());
1173 }
1174
1175 void outputComments(List<? extends AnnotationChild> list) {
1176 for (AnnotationChild child : list)
1177 if (child instanceof Comment)
1178 outputComment(((Comment)child).getValue());
1179 }
1180
1181 void outputComment(String value) {
1182 outputNewline();
1183 write("<!--");
1184 int start = 0;
1185 for (;;) {
1186 int i = value.indexOf('\n', start);
1187 if (i < 0) {
1188 if (start == 0) {
1189 write(' ');
1190 write(value);
1191 write(' ');
1192 }
1193 else {
1194 outputNewline();
1195 write(value.substring(start));
1196 outputNewline();
1197 }
1198 break;
1199 }
1200 outputNewline();
1201 write(value.substring(start, i));
1202 start = i + 1;
1203 }
1204 write("-->");
1205 outputNewline();
1206 }
1207
1208 void outputIndent() {
1209 for (int i = 0; i < indent; i++)
1210 write(' ');
1211 }
1212
1213 void outputNewline() {
1214 write(lineSep);
1215 }
1216
1217 static class WrappedIOException extends RuntimeException {
1218 final IOException cause;
1219
1220 WrappedIOException(IOException cause) {
1221 this.cause = cause;
1222 }
1223
1224 public Throwable getCause() {
1225 return cause;
1226 }
1227 }
1228
1229 void write(String s) {
1230 try {
1231 writer.write(s);
1232 }
1233 catch (IOException e) {
1234 throw new WrappedIOException(e);
1235 }
1236 }
1237
1238 void write(char c) {
1239 try {
1240 writer.write(c);
1241 }
1242 catch (IOException e) {
1243 throw new WrappedIOException(e);
1244 }
1245 }
1246
1247 void close() {
1248 try {
1249 writer.close();
1250 }
1251 catch (IOException e) {
1252 throw new WrappedIOException(e);
1253 }
1254 }
1255
1256 private static String getDefaultValue(AttributePattern p) {
1257 return getAttributeAnnotation(p, WellKnownNamespaces.RELAX_NG_COMPATIBILITY_ANNOTATIONS, "defaultValue");
1258 }
1259
1260 private static String getAttributeAnnotation(Annotated p, String ns, String localName) {
1261 List<AttributeAnnotation> list = p.getAttributeAnnotations();
1262 for (int i = 0, len = list.size(); i < len; i++) {
1263 AttributeAnnotation att = list.get(i);
1264 if (att.getLocalName().equals(localName)
1265 && att.getNamespaceUri().equals(ns))
1266 return att.getValue();
1267 }
1268 return null;
1269 }
1270 }