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

Last change on this file since 25 was 25, checked in by zeiss, 14 years ago
  • Property svn:mime-type set to text/plain
File size: 13.0 KB
Line 
1package de.ugoe.cs.swe.bnftools.ui.formatter;
2
3import java.util.ArrayList;
4
5import org.eclipse.emf.ecore.EObject;
6import org.eclipse.xtext.parsetree.AbstractNode;
7import org.eclipse.xtext.parsetree.CompositeNode;
8import org.eclipse.xtext.parsetree.LeafNode;
9import org.eclipse.xtext.parsetree.NodeUtil;
10
11import de.ugoe.cs.swe.bnftools.ebnf.Atom;
12import de.ugoe.cs.swe.bnftools.ebnf.BnfEntry;
13import de.ugoe.cs.swe.bnftools.ebnf.DefinitionList;
14import de.ugoe.cs.swe.bnftools.ebnf.DeltaEntry;
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;
20import de.ugoe.cs.swe.bnftools.ebnf.Import;
21import de.ugoe.cs.swe.bnftools.ebnf.ImportSection;
22import de.ugoe.cs.swe.bnftools.ebnf.MergeEntry;
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;
38        private int bufferPositionFormattedTextNoWhitespaces = 0;
39        private int bufferPositionOriginalText = 0;
40        private int allCommentsPosition = 0;
41        private ArrayList<LeafNode> allComments = new ArrayList<LeafNode>();
42       
43        private boolean lastWasSectionHeading=false;
44        private CompositeNode parserEtsiBnfNode;
45        private String originalText;
46        private int bufferPositionFormattedText;
47        private String formattedText;
48        private String formattedTextNoWhitespaces;
49        private String originalTextNoWhitespaces;
50       
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
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() {
107                while (bufferPositionOriginalText < originalText.length() && isWhitespace(originalText.charAt(bufferPositionOriginalText))) {
108                        bufferPositionOriginalText++;
109                }
110        }
111
112        private void skipWhitespacesFormattedText(StringBuffer result) {
113                while (bufferPositionFormattedText < formattedText.length() && isWhitespace(formattedText.charAt(bufferPositionFormattedText))) {
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       
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       
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       
176        private void weaveComments() {
177//              if (true) {
178//                      StringBuffer result = new StringBuffer();
179//                      result.append(buf.toString());
180//                      buf = result;
181//                      return;
182//              }
183               
184                bufferPositionOriginalText = 0;
185                bufferPositionFormattedTextNoWhitespaces = 0;
186                bufferPositionFormattedText = 0;
187               
188                StringBuffer result = new StringBuffer();
189                formattedTextNoWhitespaces = buf.toString().replaceAll("[ \t\n\r]", "");
190                formattedText = buf.toString();
191               
192                while (bufferPositionFormattedTextNoWhitespaces < formattedTextNoWhitespaces.length()) {
193                        skipWhitespacesOriginalText();
194                        skipWhitespacesFormattedText(result);
195                       
196                        if (!(bufferPositionOriginalText < originalText.length()))
197                                break;
198                       
199                        char formattedPositionNoWhitespaces = formattedTextNoWhitespaces.charAt(bufferPositionFormattedTextNoWhitespaces);
200                        char originalPosition = originalText.charAt(bufferPositionOriginalText);
201
202                        if (formattedPositionNoWhitespaces != originalPosition) {
203                                if (formattedPositionNoWhitespaces == ';') { // formatted text always outputs the optional semicolon, skip it if necessary
204                                        bufferPositionFormattedTextNoWhitespaces++;
205                                        bufferPositionFormattedText++;
206                                } else if (isCommentNext(originalText, bufferPositionOriginalText)) {
207                                        LeafNode currentComment = allComments.get(allCommentsPosition);
208                                        if (currentComment.getTotalOffset() == bufferPositionOriginalText) {
209                                                if (isMultiLineComment(currentComment.getText())) {
210                                                        int newLinesCount = scanBackNewlinesCount(originalText, bufferPositionOriginalText-1);
211                                                        if (newLinesCount > 0) {
212                                                                if (scanBackNewlinesCount(result.toString(), result.toString().length()-1) == 0) {
213                                                                        result.append("\n\n");
214                                                                }
215                                                               
216                                                                result.append(currentComment.getText());
217                                                                result.append("\n");
218                                                        } else {
219                                                                String lastWhiteSpaces = scanBackWhitespaces(result.toString(), result.toString().length()-1);
220                                                                result.delete(result.toString().length() - lastWhiteSpaces.length(), result.toString().length());
221                                                                result.append(" " + stripEndingNewline(currentComment.getText()));
222                                                                result.append(lastWhiteSpaces);
223                                                        }
224                                                } else if (isSingleLineComment(currentComment.getText())) {
225                                                        int newLinesCount = scanBackNewlinesCount(originalText, bufferPositionOriginalText-1);
226                                                        String lastWhiteSpaces = scanBackWhitespaces(result.toString(), result.toString().length()-1);
227                                                        result.delete(result.toString().length() - lastWhiteSpaces.length(), result.toString().length());
228                                                        if (newLinesCount > 0) {
229                                                                result.append("\n\n" + stripEndingNewline(currentComment.getText()));
230                                                        } else {
231                                                                result.append(" " + stripEndingNewline(currentComment.getText()));
232                                                        }
233                                                        result.append(lastWhiteSpaces);
234                                                }
235                                                bufferPositionOriginalText+=currentComment.getLength();
236                                                allCommentsPosition++;
237                                        }
238                                } else { // disaster handling: return original unformatted text!
239                                        buf = new StringBuffer();
240                                        buf.append(originalText);
241                                        return;
242                                }
243                        } else {
244                                result.append(formattedText.substring(bufferPositionFormattedText, bufferPositionFormattedText+1));
245                                bufferPositionOriginalText++;
246                                bufferPositionFormattedText++;
247                                bufferPositionFormattedTextNoWhitespaces++;
248                        }
249                }
250                buf = result;
251               
252        }
253
254       
255        // -----------------------------------------------------------------------------
256
257        protected void visitBefore(EtsiBnf node) {
258                parserEtsiBnfNode = NodeUtil.getNodeAdapter(node).getParserNode();
259                collectAllComments(parserEtsiBnfNode);
260                originalText = NodeUtil.getNodeAdapter(node).getParserNode().serialize();
261                originalTextNoWhitespaces = originalText.replaceAll("[ \t\n\r]", "");
262               
263                //System.out.println(allComments.toString());
264                buf.append("grammar " + node.getName());
265                if (node.getType() != null)
266                        buf.append(node.getType());
267                buf.append(";");
268
269                buf.append("\n\n");
270        }
271
272        protected void visitAfter(EtsiBnf node) {
273                weaveComments();
274        }
275
276        protected void visitBefore(ImportSection node) {
277        }
278
279        protected void visitAfter(ImportSection node) {
280                buf.append("\n");
281        }
282
283        protected void visitBefore(BnfEntry node) {
284        }
285
286        protected void visitAfter(BnfEntry node) {
287        }
288       
289        protected void visitBefore(DeltaEntry node) {
290        }
291
292        protected void visitAfter(DeltaEntry node) {
293        }
294       
295        protected void visitBefore(MergeEntry node) {
296        }
297
298        protected void visitAfter(MergeEntry node) {
299        }
300       
301        protected void visitBefore(Atom node) {
302        }
303
304        protected void visitAfter(Atom node) {
305        }
306
307        protected void visitBefore(Term node) {
308        }
309
310        protected void visitAfter(Term node) {
311                if (!isLastElement())
312                        buf.append(" ");
313        }
314
315        protected void visitBefore(DefinitionList node) {
316        }
317
318        protected void visitAfter(DefinitionList node) {
319        }
320
321        protected void visitBefore(ExtRule node) {
322        }
323
324        protected void visitAfter(ExtRule node) {
325        }
326
327        protected void visitBefore(GlobalCombinator node) {
328        }
329
330        protected void visitAfter(GlobalCombinator node) {
331        }
332
333        protected void visitBefore(GroupedSequence node) {
334                buf.append("(");
335        }
336
337        protected void visitAfter(GroupedSequence node) {
338                buf.append(")");
339        }
340
341        protected void visitBefore(HookCombinator node) {
342        }
343
344        protected void visitAfter(HookCombinator node) {
345        }
346
347        protected void visitBefore(Import node) {
348                buf.append("import \"" + node.getImportURI() + "\";");
349                buf.append("\n");
350        }
351
352        protected void visitAfter(Import node) {
353        }
354
355        protected void visitBefore(MergeRule node) {
356        }
357
358        protected void visitAfter(MergeRule node) {
359        }
360
361        protected void visitBefore(OptionalSequence node) {
362                buf.append("[");
363        }
364
365        protected void visitAfter(OptionalSequence node) {
366                buf.append("]");
367        }
368
369        protected void visitBefore(RepeatedSequence node) {
370                buf.append("{");
371        }
372
373        protected void visitAfter(RepeatedSequence node) {
374                buf.append("}");
375                if (node.isMorethanonce())
376                        buf.append("+");
377        }
378
379        protected void visitBefore(Rule node) {
380                if (lastWasSectionHeading)
381                        buf.append("\n");
382               
383                lastWasSectionHeading=false;
384
385                if (node.getRulenumber() > 0)
386                        buf.append(node.getRulenumber() + ". ");
387               
388                buf.append(node.getName() + " ::= ");
389        }
390
391        protected void visitAfter(Rule node) {
392                buf.append(";");
393//              appendComments(node);
394                buf.append("\n");
395        }
396
397        protected void visitBefore(RuleCombinator node) {
398        }
399
400        protected void visitAfter(RuleCombinator node) {
401        }
402
403        protected void visitBefore(RuleReference node) {
404                buf.append(node.getRuleref().getName());
405        }
406
407        protected void visitAfter(RuleReference node) {
408        }
409
410        protected void visitBefore(SectionHeading node) {
411                if (!lastWasSectionHeading && !buf.substring(buf.length()-2).equals("\n\n"))
412                        buf.append("\n");
413               
414                lastWasSectionHeading=true;
415//              if (!lastWasSectionHeading || !buf.substring(buf.length()-2).equals("\n\n"))
416//              if (!buf.substring(buf.length()-2).equals("\n\n"))
417//                      buf.append("\n");
418               
419                buf.append(node.getSectionHeader());
420        }
421
422        protected void visitAfter(SectionHeading node) {
423//              buf.append("\n");
424        }
425
426        protected void visitBefore(SingleDefinition node) {
427        }
428
429        protected void visitAfter(SingleDefinition node) {
430                if (!isLastElement())
431                        buf.append(" | ");
432               
433        }
434
435        protected void visitBefore(StringRule node) {
436                if (node.getLiteral() != null)
437                        buf.append("\"" + node.getLiteral() + "\"");
438                else if (node.getColon() != null)
439                        buf.append("\"\"\"");
440        }
441
442        protected void visitAfter(StringRule node) {
443        }
444
445       
446       
447}
Note: See TracBrowser for help on using the repository browser.