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

Last change on this file since 31 was 31, checked in by zeiss, 14 years ago
  • Property svn:mime-type set to text/plain
File size: 16.6 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        private StringBuffer buf;
38        private FormatterConfig config;
39        private int bufferPositionFormattedTextNoWhitespaces = 0;
40        private int bufferPositionOriginalText = 0;
41        private int allCommentsPosition = 0;
42        private ArrayList<LeafNode> allComments = new ArrayList<LeafNode>();
43       
44        private boolean lastWasSectionHeading=false;
45        private CompositeNode parserEtsiBnfNode;
46        private String originalText;
47        private int bufferPositionFormattedText;
48        private String formattedText;
49        private String formattedTextNoWhitespaces;
50        private String originalTextNoWhitespaces;
51        private int newLineOffsetCounter = 0;
52        private int rightHandSideRuleOffset = 0;
53        private Stack<Integer> ruleSpacingStack = new Stack<Integer>();
54        private 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                        newLine();
292                        if (ruleSpacingStack.size() > 1)
293                                spaces(ruleSpacingStack.peek() + 1);
294                        else
295                                spaces(ruleSpacingStack.peek());
296                }
297        }
298
299        // -----------------------------------------------------------------------------
300
301        protected void visitBefore(EtsiBnf node) {
302                parserEtsiBnfNode = NodeUtil.getNodeAdapter(node).getParserNode();
303                collectAllComments(parserEtsiBnfNode);
304                originalText = NodeUtil.getNodeAdapter(node).getParserNode().serialize();
305                originalTextNoWhitespaces = originalText.replaceAll("[ \t\n\r]", "");
306               
307                text("grammar " + node.getName());
308                if (node.getType() != null)
309                        text(node.getType());
310                text(";");
311
312                newLine();
313                newLine();
314        }
315
316        protected void visitAfter(EtsiBnf node) {
317                weaveComments();
318        }
319
320        protected void visitBefore(ImportSection node) {
321        }
322
323        protected void visitAfter(ImportSection node) {
324                newLine();
325        }
326
327        protected void visitBefore(BnfEntry node) {
328        }
329
330        protected void visitAfter(BnfEntry node) {
331        }
332       
333        protected void visitBefore(DeltaEntry node) {
334        }
335
336        protected void visitAfter(DeltaEntry node) {
337        }
338       
339        protected void visitBefore(MergeEntry node) {
340        }
341
342        protected void visitAfter(MergeEntry node) {
343        }
344       
345        protected void visitBefore(Atom node) {
346        }
347
348        protected void visitAfter(Atom node) {
349        }
350
351        protected void visitBefore(Term node) {
352        }
353
354        protected void visitAfter(Term node) {
355                if (!isLastElement())
356                        space();
357        }
358
359        protected void visitBefore(DefinitionList node) {
360                averageSingleDefinitionLength = null;
361                int totalLength = 0;
362                for (int i=0; i < node.eContents().size(); i++) {
363                        CompositeNode parseNode = NodeUtil.getNodeAdapter(node.eContents().get(i)).getParserNode();
364                        totalLength += parseNode.serialize().trim().length();
365                }
366                averageSingleDefinitionLength = (double) totalLength / (double) node.eContents().size();
367        }
368
369        protected void visitAfter(DefinitionList node) {
370        }
371
372        protected void visitBefore(ExtRule node) {
373        }
374
375        protected void visitAfter(ExtRule node) {
376        }
377
378        protected void visitBefore(GlobalCombinator node) {
379        }
380
381        protected void visitAfter(GlobalCombinator node) {
382        }
383
384        protected void visitBefore(HookCombinator node) {
385        }
386
387        protected void visitAfter(HookCombinator node) {
388        }
389
390        protected void visitBefore(Import node) {
391                text("import \"" + node.getImportURI() + "\";");
392                newLine();
393        }
394
395        protected void visitAfter(Import node) {
396        }
397
398        protected void visitBefore(MergeRule node) {
399        }
400
401        protected void visitAfter(MergeRule node) {
402        }
403
404        protected void visitBefore(GroupedSequence node) {
405                wrap();
406                text("(");
407                ruleSpacingStack.push(newLineOffsetCounter-1);
408        }
409
410        protected void visitAfter(GroupedSequence node) {
411//              if ((config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) || (lastIsClosingParentheses())) {
412                if (config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) {
413                        newLine();
414                        spaces(ruleSpacingStack.peek());
415                }
416               
417                text(")");
418                ruleSpacingStack.pop();
419        }
420
421        protected void visitBefore(OptionalSequence node) {
422                wrap();
423                text("[");
424                ruleSpacingStack.push(newLineOffsetCounter-1);
425        }
426
427        protected void visitAfter(OptionalSequence node) {
428//              if ((config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) || (lastIsClosingParentheses())) {
429                if (config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) {
430                        newLine();
431                        spaces(ruleSpacingStack.peek());
432                }
433
434                text("]");
435                ruleSpacingStack.pop();
436        }
437
438        protected void visitBefore(RepeatedSequence node) {
439                wrap();
440                text("{");
441                ruleSpacingStack.push(newLineOffsetCounter-1);
442        }
443
444        protected void visitAfter(RepeatedSequence node) {
445//              if ((config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) || (lastIsClosingParentheses())) {
446                if (config.isAlignParentheses() && (node.eContents().get(0).eContents().size() >= config.getAlignParenthesesElementCountThreshold())) {
447                        newLine();
448                        spaces(ruleSpacingStack.peek());
449                }
450
451                text("}");
452                if (node.isMorethanonce())
453                        text("+");
454                ruleSpacingStack.pop();
455        }
456
457        protected void visitBefore(Rule node) {
458                if (lastWasSectionHeading)
459                        newLine();
460               
461                lastWasSectionHeading=false;
462
463                newLineOffsetCounter = 0;
464
465                if (node.getRulenumber() > 0)
466                        text(node.getRulenumber() + ". ");
467               
468                text(node.getName() + " ::= ");
469               
470                rightHandSideRuleOffset = newLineOffsetCounter;
471                ruleSpacingStack.push(newLineOffsetCounter);
472        }
473
474        protected void visitAfter(Rule node) {
475                text(";");
476                newLine();
477                ruleSpacingStack.pop();
478        }
479
480        protected void visitBefore(RuleCombinator node) {
481        }
482
483        protected void visitAfter(RuleCombinator node) {
484        }
485
486        protected void visitBefore(RuleReference node) {
487                wrap();
488                text(node.getRuleref().getName());
489        }
490
491        protected void visitAfter(RuleReference node) {
492        }
493
494        protected void visitBefore(SectionHeading node) {
495                if (!lastWasSectionHeading && !buf.substring(buf.length()-2).equals("\n\n"))
496                        newLine();
497               
498                lastWasSectionHeading=true;
499               
500                text(node.getSectionHeader());
501        }
502
503        protected void visitAfter(SectionHeading node) {
504        }
505
506        protected void visitBefore(SingleDefinition node) {
507        }
508
509        protected void visitAfter(SingleDefinition node) {
510                boolean preventAlternativeBreakShortAlternatives = config.isPreventNewLineAfterAlternativeOnShortAlternatives() && (averageSingleDefinitionLength <= config.getShortAlternativeThreshold());
511                if (!isLastElement()) {
512                        text(" | ");
513                        if (config.isNewLineAfterAlternative()) {
514                                if (config.isPreventNewLineAfterAlternativeOnLessThanThreeElements()) {
515                                        DefinitionList definitionList = (DefinitionList) node.eContainer();
516                                        if ((definitionList.eContents().size() > 2) && (!preventAlternativeBreakShortAlternatives)) {
517                                                newLine();
518                                                if (ruleSpacingStack.size() > 1)
519                                                        spaces(ruleSpacingStack.peek() + 1);
520                                                else
521                                                        spaces(ruleSpacingStack.peek());
522                                        }
523                                } else {
524                                        if (!preventAlternativeBreakShortAlternatives) {
525                                                newLine();
526                                                if (ruleSpacingStack.size() > 1)
527                                                        spaces(ruleSpacingStack.peek() + 1);
528                                                else
529                                                        spaces(ruleSpacingStack.peek());
530                                        }
531                                }
532                        }
533                }
534        }
535
536        protected void visitBefore(StringRule node) {
537                wrap();
538                if (node.getLiteral() != null)
539                        text("\"" + node.getLiteral() + "\"");
540                else if (node.getColon() != null)
541                        text("\"\"\"");
542        }
543
544        protected void visitAfter(StringRule node) {
545        }
546       
547}
Note: See TracBrowser for help on using the repository browser.