improved PHP parser
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / corext / util / CodeFormatterUtil.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials 
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  * 
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  *******************************************************************************/
11 package net.sourceforge.phpdt.internal.corext.util;
12
13 import java.util.Map;
14
15 import net.sourceforge.phpdt.core.ToolFactory;
16 import net.sourceforge.phpdt.core.formatter.DefaultCodeFormatterConstants;
17 import net.sourceforge.phpdt.internal.corext.Assert;
18 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
19
20 import org.eclipse.core.runtime.Preferences;
21 import org.eclipse.jface.text.BadLocationException;
22 import org.eclipse.jface.text.BadPositionCategoryException;
23 import org.eclipse.jface.text.DefaultPositionUpdater;
24 import org.eclipse.jface.text.Document;
25 import org.eclipse.jface.text.Position;
26 import org.eclipse.text.edits.DeleteEdit;
27 import org.eclipse.text.edits.InsertEdit;
28 import org.eclipse.text.edits.MultiTextEdit;
29 import org.eclipse.text.edits.ReplaceEdit;
30 import org.eclipse.text.edits.TextEdit;
31
32 public class CodeFormatterUtil {
33                         
34         /**
35          * Creates a string that represents the given number of indents (can be spaces or tabs..)
36          */
37         public static String createIndentString(int indent) {
38           // axelcl change start
39 //              String str= format(CodeFormatter.K_EXPRESSION, "x", indent, null, "", (Map) null); //$NON-NLS-1$ //$NON-NLS-2$
40                 String str = ToolFactory.createCodeFormatter().format("x", indent, null, ""); 
41                 return str.substring(0, str.indexOf('x'));
42                 // axelcl change end
43         } 
44                 
45         public static int getTabWidth() {
46                 Preferences preferences= PHPeclipsePlugin.getDefault().getPluginPreferences();
47                 return preferences.getInt(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
48         }
49
50         // transition code
51
52         /**
53          * Old API. Consider to use format2 (TextEdit)
54          */     
55 //      public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) {
56 //              return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options);
57 //      }
58 //      
59 //      public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, IJavaProject project) {
60 //              Map options= project != null ? project.getOptions(true) : null;
61 //              return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options);
62 //      }
63         
64
65         /**
66          * Old API. Consider to use format2 (TextEdit)
67          */     
68 //      public static String format(int kind, String string, int offset, int length, int indentationLevel, int[] positions, String lineSeparator, Map options) {
69 //              TextEdit edit= format2(kind, string, offset, length, indentationLevel, lineSeparator, options);
70 //              if (edit == null) {
71 //                      //JavaPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. kind: " + kind + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$
72 //                      return string.substring(offset, offset + length);
73 //              }
74 //              String formatted= getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options);
75 //              return formatted.substring(offset, formatted.length() - (string.length() - (offset + length)));
76 //      }
77         
78         /**
79          * Old API. Consider to use format2 (TextEdit)
80          */     
81 //      public static String format(ASTNode node, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) {
82 //              
83 //              TextEdit edit= format2(node, string, indentationLevel, lineSeparator, options);
84 //              if (edit == null) {
85 //                      //JavaPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. node: " + node.getNodeType() + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$
86 //                      return string;
87 //              }
88 //              return getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options);
89 //      }
90         
91         private static String getOldAPICompatibleResult(String string, TextEdit edit, int indentationLevel, int[] positions, String lineSeparator, Map options) {
92                 Position[] p= null;
93                 
94                 if (positions != null) {
95                         p= new Position[positions.length];
96                         for (int i= 0; i < positions.length; i++) {
97                                 p[i]= new Position(positions[i], 0);
98                         }
99                 }
100                 String res= evaluateFormatterEdit(string, edit, p);
101                 
102                 if (positions != null) {
103                         for (int i= 0; i < positions.length; i++) {
104                                 Position curr= p[i];
105                                 positions[i]= curr.getOffset();
106                         }
107                 }                       
108                 return res;
109         }
110         
111         /**
112          * Evaluates the edit on the given string.
113          * @throws IllegalArgumentException If the positions are not inside the string, a
114          *  IllegalArgumentException is thrown.
115          */
116         public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) {
117                 try {
118                         Document doc= createDocument(string, positions);
119                         edit.apply(doc, 0);
120                         if (positions != null) {
121                                 for (int i= 0; i < positions.length; i++) {
122                                         Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$
123                                 }
124                         }
125                         return doc.get();
126                 } catch (BadLocationException e) {
127                         PHPeclipsePlugin.log(e); // bug in the formatter
128                         Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
129                 }
130                 return null;
131         }
132         
133         /**
134          * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind.
135          * @throws IllegalArgumentException If the offset and length are not inside the string, a
136          *  IllegalArgumentException is thrown.
137          */
138 //      public static TextEdit format2(int kind, String string, int offset, int length, int indentationLevel, String lineSeparator, Map options) {
139 //              if (offset < 0 || length < 0 || offset + length > string.length()) {
140 //                      throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + string.length());   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
141 //              }
142 //              
143 //              return createCodeFormatter(options).format(kind, string, offset, length, indentationLevel, lineSeparator);
144 //              
145 //      }
146         
147 //      public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) {
148 //              return format2(kind, string, 0, string.length(), indentationLevel, lineSeparator, options);
149 //      }
150         
151         /**
152          * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind.
153          * @throws IllegalArgumentException If the offset and length are not inside the string, a
154          *  IllegalArgumentException is thrown.
155          */
156 //      public static TextEdit format2(ASTNode node, String str, int indentationLevel, String lineSeparator, Map options) {
157 //              int code;
158 //              String prefix= ""; //$NON-NLS-1$
159 //              String suffix= ""; //$NON-NLS-1$
160 //              if (node instanceof Statement) {
161 //                      code= CodeFormatter.K_STATEMENTS;
162 //                      if (node.getNodeType() == ASTNode.SWITCH_CASE) {
163 //                              prefix= "switch(1) {"; //$NON-NLS-1$
164 //                              suffix= "}"; //$NON-NLS-1$
165 //                              code= CodeFormatter.K_STATEMENTS;
166 //                      }
167 //              } else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
168 //                      code= CodeFormatter.K_EXPRESSION;
169 //              } else {
170 //                      switch (node.getNodeType()) {
171 //                              case ASTNode.METHOD_DECLARATION:
172 //                              case ASTNode.TYPE_DECLARATION:
173 //                              case ASTNode.FIELD_DECLARATION:
174 //                              case ASTNode.INITIALIZER:
175 //                                      code= CodeFormatter.K_CLASS_BODY_DECLARATIONS;
176 //                                      break;
177 //                              case ASTNode.ARRAY_TYPE:
178 //                              case ASTNode.PRIMITIVE_TYPE:
179 //                              case ASTNode.SIMPLE_TYPE:
180 //                                      suffix= " x;"; //$NON-NLS-1$
181 //                                      code= CodeFormatter.K_EXPRESSION;
182 //                                      break;
183 //                              case ASTNode.COMPILATION_UNIT:
184 //                                      code= CodeFormatter.K_COMPILATION_UNIT;
185 //                                      break;
186 //                              case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
187 //                              case ASTNode.SINGLE_VARIABLE_DECLARATION:
188 //                                      suffix= ";"; //$NON-NLS-1$
189 //                                      code= CodeFormatter.K_STATEMENTS;
190 //                                      break;
191 //                              case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
192 //                                      prefix= "A "; //$NON-NLS-1$
193 //                                      suffix= ";"; //$NON-NLS-1$
194 //                                      code= CodeFormatter.K_STATEMENTS;
195 //                                      break;                  
196 //                              case ASTNode.PACKAGE_DECLARATION:
197 //                              case ASTNode.IMPORT_DECLARATION:
198 //                                      suffix= "\nclass A {}"; //$NON-NLS-1$
199 //                                      code= CodeFormatter.K_COMPILATION_UNIT;
200 //                                      break;
201 //                              case ASTNode.JAVADOC:
202 //                                      suffix= "void foo();"; //$NON-NLS-1$
203 //                                      code= CodeFormatter.K_CLASS_BODY_DECLARATIONS;
204 //                                      break;
205 //                              case ASTNode.CATCH_CLAUSE:
206 //                                      prefix= "try {}"; //$NON-NLS-1$
207 //                                      code= CodeFormatter.K_STATEMENTS;
208 //                                      break;
209 //                              case ASTNode.ANONYMOUS_CLASS_DECLARATION:
210 //                                      prefix= "new A()"; //$NON-NLS-1$
211 //                                      suffix= ";"; //$NON-NLS-1$
212 //                                      code= CodeFormatter.K_STATEMENTS;
213 //                                      break;
214 //                              case ASTNode.MEMBER_REF:
215 //                              case ASTNode.METHOD_REF:
216 //                              case ASTNode.METHOD_REF_PARAMETER:
217 //                              case ASTNode.TAG_ELEMENT:
218 //                              case ASTNode.TEXT_ELEMENT:
219 //                                      // not yet supported
220 //                                      return null;
221 //                              default:
222 //                                      Assert.isTrue(false, "Node type not covered: " + node.getClass().getName()); //$NON-NLS-1$
223 //                                      return null;
224 //                      }
225 //              }
226 //              
227 //              String concatStr= prefix + str + suffix;
228 //              TextEdit edit= format2(code, concatStr, prefix.length(), str.length(), indentationLevel, lineSeparator, options);
229 //              if (prefix.length() > 0) {
230 //                      edit= shifEdit(edit, prefix.length());
231 //              }               
232 //              return edit;
233 //      }       
234                         
235         private static TextEdit shifEdit(TextEdit oldEdit, int diff) {
236                 TextEdit newEdit;
237                 if (oldEdit instanceof ReplaceEdit) {
238                         ReplaceEdit edit= (ReplaceEdit) oldEdit;
239                         newEdit= new ReplaceEdit(edit.getOffset() - diff, edit.getLength(), edit.getText());
240                 } else if (oldEdit instanceof InsertEdit) {
241                         InsertEdit edit= (InsertEdit) oldEdit;
242                         newEdit= new InsertEdit(edit.getOffset() - diff,  edit.getText());
243                 } else if (oldEdit instanceof DeleteEdit) {
244                         DeleteEdit edit= (DeleteEdit) oldEdit;
245                         newEdit= new DeleteEdit(edit.getOffset() - diff,  edit.getLength());
246                 } else if (oldEdit instanceof MultiTextEdit) {
247                         newEdit= new MultiTextEdit();                   
248                 } else {
249                         return null; // not supported
250                 }
251                 TextEdit[] children= oldEdit.getChildren();
252                 for (int i= 0; i < children.length; i++) {
253                         TextEdit shifted= shifEdit(children[i], diff);
254                         if (shifted != null) {
255                                 newEdit.addChild(shifted);
256                         }
257                 }
258                 return newEdit;
259         }
260                 
261         private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException {
262                 Document doc= new Document(string);
263                 try {
264                         if (positions != null) {
265                                 final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$
266                                 
267                                 doc.addPositionCategory(POS_CATEGORY);
268                                 doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) {
269                                         protected boolean notDeleted() {
270                                                 if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) {
271                                                         fPosition.offset= fOffset + fLength; // deleted positions: set to end of remove
272                                                         return false;
273                                                 }
274                                                 return true;
275                                         }
276                                 });
277                                 for (int i= 0; i < positions.length; i++) {
278                                         try {
279                                                 doc.addPosition(POS_CATEGORY, positions[i]);
280                                         } catch (BadLocationException e) {
281                                                 throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length());   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
282                                         }
283                                 }
284                         }
285                 } catch (BadPositionCategoryException cannotHappen) {
286                         // can not happen: category is correctly set up
287                 }
288                 return doc;
289         }
290         
291 }