source: default/trunk/de.ugoe.cs.swe.bnftools.ebnf.ui/src/de/ugoe/cs/swe/bnftools/ui/formatter/EbnfFormatterVisitor.java @ 34

Last change on this file since 34 was 34, checked in by zeiss, 14 years ago
  • Property svn:mime-type set to text/plain
File size: 17.0 KB
Line 
1package de.ugoe.cs.swe.bnftools.ui.formatter;
2
3import java.util.ArrayList;
4import java.util.Stack;
5
6import org.eclipse.emf.ecore.EObject;
7import org.eclipse.xtext.parsetree.AbstractNode;
8import org.eclipse.xtext.parsetree.CompositeNode;
9import org.eclipse.xtext.parsetree.LeafNode;
10import org.eclipse.xtext.parsetree.NodeUtil;
11
12import de.ugoe.cs.swe.bnftools.ebnf.Atom;
13import de.ugoe.cs.swe.bnftools.ebnf.BnfEntry;
14import de.ugoe.cs.swe.bnftools.ebnf.DefinitionList;
15import de.ugoe.cs.swe.bnftools.ebnf.DeltaEntry;
16import de.ugoe.cs.swe.bnftools.ebnf.EtsiBnf;
17import de.ugoe.cs.swe.bnftools.ebnf.ExtRule;
18import de.ugoe.cs.swe.bnftools.ebnf.GlobalCombinator;
19import de.ugoe.cs.swe.bnftools.ebnf.GroupedSequence;
20import de.ugoe.cs.swe.bnftools.ebnf.HookCombinator;
21import de.ugoe.cs.swe.bnftools.ebnf.Import;
22import de.ugoe.cs.swe.bnftools.ebnf.ImportSection;
23import de.ugoe.cs.swe.bnftools.ebnf.MergeEntry;
24import de.ugoe.cs.swe.bnftools.ebnf.MergeRule;
25import de.ugoe.cs.swe.bnftools.ebnf.OptionalSequence;
26import de.ugoe.cs.swe.bnftools.ebnf.RepeatedSequence;
27import de.ugoe.cs.swe.bnftools.ebnf.Rule;
28import de.ugoe.cs.swe.bnftools.ebnf.RuleCombinator;
29import de.ugoe.cs.swe.bnftools.ebnf.RuleReference;
30import de.ugoe.cs.swe.bnftools.ebnf.SectionHeading;
31import de.ugoe.cs.swe.bnftools.ebnf.SingleDefinition;
32import de.ugoe.cs.swe.bnftools.ebnf.StringRule;
33import de.ugoe.cs.swe.bnftools.ebnf.Term;
34import de.ugoe.cs.swe.bnftools.visitor.EbnfVisitor;
35
36public class EbnfFormatterVisitor extends EbnfVisitor {
37        protected StringBuffer buf;
38        protected FormatterConfig config;
39        protected int bufferPositionFormattedTextNoWhitespaces = 0;
40        protected int bufferPositionOriginalText = 0;
41        protected int allCommentsPosition = 0;
42        protected ArrayList<LeafNode> allComments = new ArrayList<LeafNode>();
43       
44        protected boolean lastWasSectionHeading=false;
45        protected CompositeNode parserEtsiBnfNode;
46        protected String originalText;
47        protected int bufferPositionFormattedText;
48        protected String formattedText;
49        protected String formattedTextNoWhitespaces;
50        protected String originalTextNoWhitespaces;
51        protected int newLineOffsetCounter = 0;
52        protected int rightHandSideRuleOffset = 0;
53        protected Stack<Integer> ruleSpacingStack = new Stack<Integer>();
54        protected Double averageSingleDefinitionLength;
55       
56        public EbnfFormatterVisitor(EObject rootNode, FormatterConfig config) {
57                super(rootNode);
58                this.config = config;
59                buf = new StringBuffer();
60        }
61
62        public EbnfFormatterVisitor(FormatterConfig config) {
63                this.config = config;
64                buf = new StringBuffer();
65        }
66
67        public StringBuffer getBuf() {
68                return buf;
69        }
70
71        private boolean isCommentNode(LeafNode node) {
72                if ((node.getText().trim().startsWith("//") || node.getText().trim().startsWith("/*")) && (node.isHidden()))
73                        return true;
74                return false;
75        }
76       
77        private void collectAllComments(CompositeNode node) {
78                for (int i=0; i < node.getChildren().size(); i++) {
79                        AbstractNode currentNode = node.getChildren().get(i);
80                        if (currentNode instanceof LeafNode) {
81                                LeafNode leafNode = (LeafNode) currentNode;
82                                if (isCommentNode(leafNode)) {
83                                        allComments.add(leafNode);
84                                }
85                        }
86                       
87                        if (currentNode instanceof CompositeNode) {
88                                collectAllComments((CompositeNode) currentNode);
89                        }
90                }
91        }
92
93        private boolean isSingleLineComment(String str) {
94                if (str.startsWith("//"))
95                        return true;
96                return false;
97        }
98       
99        private boolean isMultiLineComment(String str) {
100                if (str.startsWith("/*"))
101                        return true;
102                return false;
103        }
104
105        private boolean isWhitespace(char ch) {
106                if ((ch==' ') || (ch == '\t') || (ch == '\n') || (ch == '\r'))
107                        return true;
108                return false;
109        }
110       
111        private void skipWhitespacesOriginalText() {
112                while (bufferPositionOriginalText < originalText.length() && isWhitespace(originalText.charAt(bufferPositionOriginalText))) {
113                        bufferPositionOriginalText++;
114                }
115        }
116
117        private void skipWhitespacesFormattedText(StringBuffer result) {
118                while (bufferPositionFormattedText < formattedText.length() && isWhitespace(formattedText.charAt(bufferPositionFormattedText))) {
119                        result.append(formattedText.substring(bufferPositionFormattedText, bufferPositionFormattedText+1));
120                        bufferPositionFormattedText++;
121                }
122        }
123
124        private boolean isSingleLineCommentNext(String str, int position) {
125                if ((str.charAt(position) == '/') && (str.charAt(position) == '/'))
126                        return true;
127                return false;
128        }
129       
130        private boolean isMultiLineCommentNext(String str, int position) {
131                if ((str.charAt(position) == '/') && (str.charAt(position) == '*'))
132                        return true;
133                return false;
134        }
135               
136        private boolean isCommentNext(String str, int position) {
137                if (isSingleLineCommentNext(str, position) || isMultiLineCommentNext(str, position))
138                        return true;
139                else
140                        return false;
141        }
142       
143        private String scanBackWhitespaces(String str, int position) {
144                StringBuffer whiteSpaces = new StringBuffer();
145                int currentPosition = position;
146                while (isWhitespace(str.charAt(currentPosition))) {
147                        whiteSpaces.append(str.charAt(currentPosition));
148                        currentPosition--;
149                }
150                return whiteSpaces.toString();
151        }
152       
153        private String stripEndingNewline(String str) {
154                int position = str.length() - 1;
155                while ((str.charAt(position) == '\n') || (str.charAt(position) == '\r')) {
156                        position--;
157                }
158                return str.substring(0, position + 1);
159        }
160       
161        private int scanBackNewlinesCount(String str, int position) {
162                int newLinesCount = 0;
163                int currentPosition = position;
164                while ((str.charAt(currentPosition) == '\n') || (str.charAt(currentPosition) == '\r')) {
165                        if (str.charAt(currentPosition) == '\n') {
166                                if (str.charAt(currentPosition - 1) == '\r') {
167                                        currentPosition -= 2;
168                                } else {
169                                        currentPosition -= 1;
170                                }
171                                newLinesCount++;
172                        } else if (str.charAt(currentPosition) == '\r') {
173                                currentPosition -= 1;
174                                newLinesCount++;
175                        }
176                }
177               
178                return newLinesCount;
179        }
180       
181        private void weaveComments() {
182                bufferPositionOriginalText = 0;
183                bufferPositionFormattedTextNoWhitespaces = 0;
184                bufferPositionFormattedText = 0;
185               
186                StringBuffer result = new StringBuffer();
187                formattedTextNoWhitespaces = buf.toString().replaceAll("[ \t\n\r]", "");
188                formattedText = buf.toString();
189               
190                while (bufferPositionFormattedTextNoWhitespaces <= formattedTextNoWhitespaces.length()) {
191                        skipWhitespacesOriginalText();
192                        skipWhitespacesFormattedText(result);
193                       
194                        if (!(bufferPositionOriginalText < originalText.length()))
195                                break;
196                       
197                        char formattedPositionNoWhitespaces;
198                        if (bufferPositionFormattedTextNoWhitespaces == formattedTextNoWhitespaces.length()) {
199                                formattedPositionNoWhitespaces = ' ';
200                        } else {
201                                formattedPositionNoWhitespaces = formattedTextNoWhitespaces.charAt(bufferPositionFormattedTextNoWhitespaces);
202                        }
203                        char originalPosition = originalText.charAt(bufferPositionOriginalText);
204
205                        if (formattedPositionNoWhitespaces != originalPosition) {
206                                if (formattedPositionNoWhitespaces == ';') { // formatted text always outputs the optional semicolon, skip it if necessary
207                                        bufferPositionFormattedTextNoWhitespaces++;
208                                        bufferPositionFormattedText++;
209                                } else if (isCommentNext(originalText, bufferPositionOriginalText)) {
210                                        LeafNode currentComment = allComments.get(allCommentsPosition);
211                                        if (currentComment.getTotalOffset() == bufferPositionOriginalText) {
212                                                if (isMultiLineComment(currentComment.getText())) {
213                                                        int newLinesCount = scanBackNewlinesCount(originalText, bufferPositionOriginalText-1);
214                                                        if (newLinesCount > 0) {
215                                                                if (scanBackNewlinesCount(result.toString(), result.toString().length()-1) == 0) {
216                                                                        result.append("\n\n");
217                                                                }
218                                                               
219                                                                result.append(currentComment.getText());
220                                                                result.append("\n");
221                                                        } else {
222                                                                String lastWhiteSpaces = scanBackWhitespaces(result.toString(), result.toString().length()-1);
223                                                                result.delete(result.toString().length() - lastWhiteSpaces.length(), result.toString().length());
224                                                                result.append(" " + stripEndingNewline(currentComment.getText()));
225                                                                result.append(lastWhiteSpaces);
226                                                        }
227                                                } else if (isSingleLineComment(currentComment.getText())) {
228                                                        int newLinesCount = scanBackNewlinesCount(originalText, bufferPositionOriginalText-1);
229                                                        String lastWhiteSpaces = scanBackWhitespaces(result.toString(), result.toString().length()-1);
230                                                        result.delete(result.toString().length() - lastWhiteSpaces.length(), result.toString().length());
231                                                        if (newLinesCount > 0) {
232                                                                result.append("\n\n" + stripEndingNewline(currentComment.getText()));
233                                                        } else {
234                                                                result.append(" " + stripEndingNewline(currentComment.getText()));
235                                                        }
236                                                        result.append(lastWhiteSpaces);
237                                                }
238                                                bufferPositionOriginalText+=currentComment.getLength();
239                                                allCommentsPosition++;
240                                        }
241                                } else { // disaster handling: return original unformatted text!
242                                        System.err.println("Disaster Recovery: returning original text!!");
243                                        buf = new StringBuffer();
244                                        buf.append(originalText);
245                                        return;
246                                }
247                        } else {
248                                result.append(formattedText.substring(bufferPositionFormattedText, bufferPositionFormattedText+1));
249                                bufferPositionOriginalText++;
250                                bufferPositionFormattedText++;
251                                bufferPositionFormattedTextNoWhitespaces++;
252                        }
253                }
254                buf = result;
255        }
256
257        private void newLine() {
258                buf.append("\n");
259                if ((ruleSpacingStack != null) && (!ruleSpacingStack.empty())) {
260                        newLineOffsetCounter = ruleSpacingStack.peek();
261                } else {
262                        newLineOffsetCounter = 0;
263                }
264        }
265       
266        private void text(String str) {
267                buf.append(str);
268                newLineOffsetCounter += str.length();
269        }
270
271        private void space() {
272                buf.append(" ");
273                newLineOffsetCounter++;
274        }
275       
276        private void spaces(int count) {
277                for (int i=0; i < count; i++) {
278                        buf.append(" ");
279                }
280        }
281
282        private boolean lastIsClosingParentheses() {
283                char ch = buf.toString().charAt(buf.toString().length()-1);
284                if ((ch == ')') || (ch == ']') || (ch == '}'))
285                        return true;
286                return false;
287        }
288
289        private void wrap() {
290                if ((config.isWrapAfterThreshold()) && (newLineOffsetCounter > config.getWrapThreshold())) {
291                        char last = buf.toString().charAt(buf.toString().length()-1);
292                        if (!((last == '(' || last == '[' || last == '{' ))) {
293                                newLine();
294                                if (ruleSpacingStack.size() > 1)
295                                        spaces(ruleSpacingStack.peek() + 1);
296                                else
297                                        spaces(ruleSpacingStack.peek());
298                        }
299                }
300        }
301
302        // -----------------------------------------------------------------------------
303
304        protected void visitBefore(EtsiBnf node) {
305                parserEtsiBnfNode = NodeUtil.getNodeAdapter(node).getParserNode();
306                collectAllComments(parserEtsiBnfNode);
307                originalText = NodeUtil.getNodeAdapter(node).getParserNode().serialize();
308                originalTextNoWhitespaces = originalText.replaceAll("[ \t\n\r]", "");
309               
310                text("grammar " + node.getName());
311                if (node.getType() != null)
312                        text(node.getType());
313                text(";");
314
315                newLine();
316                newLine();
317        }
318
319        protected void visitAfter(EtsiBnf node) {
320                weaveComments();
321        }
322
323        protected void visitBefore(ImportSection node) {
324        }
325
326        protected void visitAfter(ImportSection node) {
327                newLine();
328        }
329
330        protected void visitBefore(BnfEntry node) {
331        }
332
333        protected void visitAfter(BnfEntry node) {
334        }
335       
336        protected void visitBefore(DeltaEntry node) {
337        }
338
339        protected void visitAfter(DeltaEntry node) {
340        }
341       
342        protected void visitBefore(MergeEntry node) {
343        }
344
345        protected void visitAfter(MergeEntry node) {
346        }
347       
348        protected void visitBefore(Atom node) {
349        }
350
351        protected void visitAfter(Atom node) {
352        }
353
354        protected void visitBefore(Term node) {
355        }
356
357        protected void visitAfter(Term node) {
358                if (!isLastElement())
359                        space();
360        }
361
362        protected void visitBefore(DefinitionList node) {
363                averageSingleDefinitionLength = null;
364                int totalLength = 0;
365                for (int i=0; i < node.eContents().size(); i++) {
366                        CompositeNode parseNode = NodeUtil.getNodeAdapter(node.eContents().get(i)).getParserNode();
367                        totalLength += parseNode.serialize().trim().length();
368                }
369                averageSingleDefinitionLength = (double) totalLength / (double) node.eContents().size();
370        }
371
372        protected void visitAfter(DefinitionList node) {
373        }
374
375        protected void visitBefore(ExtRule node) {
376        }
377
378        protected void visitAfter(ExtRule node) {
379        }
380
381        protected void visitBefore(GlobalCombinator node) {
382        }
383
384        protected void visitAfter(GlobalCombinator node) {
385        }
386
387        protected void visitBefore(HookCombinator node) {
388        }
389
390        protected void visitAfter(HookCombinator node) {
391        }
392
393        protected void visitBefore(Import node) {
394                text("import \"" + node.getImportURI() + "\"");
395                if (node.getGrammarType() != null) {
396                        text("/" + node.getGrammarType());
397                }
398                if (node.getLabel() != null) {
399                        space();
400                        text("label: " + node.getLabel());
401                }
402                text(";");
403                newLine();
404        }
405
406        protected void visitAfter(Import node) {
407        }
408
409        protected void visitBefore(MergeRule node) {
410        }
411
412        protected void visitAfter(MergeRule node) {
413        }
414
415        protected void visitBefore(GroupedSequence node) {
416                wrap();
417                text("(");
418                ruleSpacingStack.push(newLineOffsetCounter-1);
419        }
420
421        protected void visitAfter(GroupedSequence node) {
422//              if ((config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) || (lastIsClosingParentheses())) {
423                if (config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) {
424                        newLine();
425                        spaces(ruleSpacingStack.peek());
426                }
427               
428                text(")");
429                ruleSpacingStack.pop();
430        }
431
432        protected void visitBefore(OptionalSequence node) {
433                wrap();
434                text("[");
435                ruleSpacingStack.push(newLineOffsetCounter-1);
436        }
437
438        protected void visitAfter(OptionalSequence node) {
439//              if ((config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) || (lastIsClosingParentheses())) {
440                if (config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) {
441                        newLine();
442                        spaces(ruleSpacingStack.peek());
443                }
444
445                text("]");
446                ruleSpacingStack.pop();
447        }
448
449        protected void visitBefore(RepeatedSequence node) {
450                wrap();
451                text("{");
452                ruleSpacingStack.push(newLineOffsetCounter-1);
453        }
454
455        protected void visitAfter(RepeatedSequence node) {
456//              if ((config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) || (lastIsClosingParentheses())) {
457                if (config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) {
458                        newLine();
459                        spaces(ruleSpacingStack.peek());
460                }
461
462                text("}");
463                if (node.isMorethanonce())
464                        text("+");
465                ruleSpacingStack.pop();
466        }
467
468        protected void visitBefore(Rule node) {
469                if (lastWasSectionHeading)
470                        newLine();
471               
472                lastWasSectionHeading=false;
473
474                newLineOffsetCounter = 0;
475
476                if (node.getRulenumber() > 0)
477                        text(node.getRulenumber() + ". ");
478               
479                text(node.getName() + " ::= ");
480               
481                rightHandSideRuleOffset = newLineOffsetCounter;
482                ruleSpacingStack.push(newLineOffsetCounter);
483        }
484
485        protected void visitAfter(Rule node) {
486                text(";");
487                newLine();
488                ruleSpacingStack.pop();
489        }
490
491        protected void visitBefore(RuleCombinator node) {
492        }
493
494        protected void visitAfter(RuleCombinator node) {
495        }
496
497        protected void visitBefore(RuleReference node) {
498                wrap();
499                text(node.getRuleref().getName());
500        }
501
502        protected void visitAfter(RuleReference node) {
503        }
504
505        protected void visitBefore(SectionHeading node) {
506                if (!lastWasSectionHeading && !buf.substring(buf.length()-2).equals("\n\n"))
507                        newLine();
508               
509                lastWasSectionHeading=true;
510               
511                text(node.getSectionHeader());
512        }
513
514        protected void visitAfter(SectionHeading node) {
515        }
516
517        protected void visitBefore(SingleDefinition node) {
518        }
519
520        protected void visitAfter(SingleDefinition node) {
521                boolean preventAlternativeBreakShortAlternatives = config.isPreventNewLineAfterAlternativeOnShortAlternatives() && (averageSingleDefinitionLength <= config.getShortAlternativeThreshold());
522                if (!isLastElement()) {
523                        text(" | ");
524                        if (config.isNewLineAfterAlternative()) {
525                                if (config.isPreventNewLineAfterAlternativeOnLessThanThreeElements()) {
526                                        DefinitionList definitionList = (DefinitionList) node.eContainer();
527                                        if ((definitionList.eContents().size() > 2) && (!preventAlternativeBreakShortAlternatives)) {
528                                                newLine();
529                                                if (ruleSpacingStack.size() > 1)
530                                                        spaces(ruleSpacingStack.peek() + 1);
531                                                else
532                                                        spaces(ruleSpacingStack.peek());
533                                        }
534                                } else {
535                                        if (!preventAlternativeBreakShortAlternatives) {
536                                                newLine();
537                                                if (ruleSpacingStack.size() > 1)
538                                                        spaces(ruleSpacingStack.peek() + 1);
539                                                else
540                                                        spaces(ruleSpacingStack.peek());
541                                        }
542                                }
543                        }
544                }
545        }
546
547        protected void visitBefore(StringRule node) {
548                wrap();
549                if (node.getLiteral() != null)
550                        text("\"" + node.getLiteral() + "\"");
551                else if (node.getColon() != null)
552                        text("\"\"\"");
553        }
554
555        protected void visitAfter(StringRule node) {
556        }
557       
558}
Note: See TracBrowser for help on using the repository browser.