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

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