Code Completion inserts the brackets after functions now
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / PHPSyntaxRdr.java
1 package net.sourceforge.phpeclipse.phpeditor;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9 import java.io.UnsupportedEncodingException;
10 import java.util.ArrayList;
11
12
13 import javax.xml.parsers.DocumentBuilder;
14 import javax.xml.parsers.DocumentBuilderFactory;
15 import javax.xml.parsers.ParserConfigurationException;
16
17 import net.sourceforge.phpeclipse.IPreferenceConstants;
18 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
19 import net.sourceforge.phpeclipse.phpeditor.php.PHPConstant;
20 import net.sourceforge.phpeclipse.phpeditor.php.PHPElement;
21 import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction;
22 import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword;
23 import net.sourceforge.phpeclipse.phpeditor.php.PHPType;
24
25 import org.apache.xml.serialize.OutputFormat;
26 import org.apache.xml.serialize.Serializer;
27 import org.apache.xml.serialize.SerializerFactory;
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.IPath;
30 import org.eclipse.jface.preference.IPreferenceStore;
31 import org.w3c.dom.Attr;
32 import org.w3c.dom.Document;
33 import org.w3c.dom.NamedNodeMap;
34 import org.w3c.dom.Node;
35 import org.w3c.dom.NodeList;
36 import org.w3c.dom.Text;
37 import org.xml.sax.InputSource;
38 import org.xml.sax.SAXException;
39
40 /**
41  * <code>PHPSyntaxRdr</code> reads PHP specifics from an XML file (eg. keywords) 
42  */
43
44 public class PHPSyntaxRdr {
45         private static final String PHPDEFAULT_FILE = "default-phpsyntax.xml"; //$NON-NLS-1$
46         private static final String PHPSYNTAX_FILE = "phpsyntax.xml"; //$NON-NLS-1$
47         private static final String USERSYNTAX_FILE = "usersyntax.xml"; //$NON-NLS-1$
48         private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; //$NON-NLS-1$
49         private static final String PHPSYNTAX_TAG = "phpsyntax"; //$NON-NLS-1$
50         private static final String KEYWORD_ATTR = "keyword"; //$NON-NLS-1$
51         private static final String TYPE_ATTR = "type"; //$NON-NLS-1$
52         private static final String CONSTANT_ATTR = "constant"; //$NON-NLS-1$
53         private static final String FN_ATTR = "function"; //$NON-NLS-1$
54         private static final String USAGE_ATTR = "usage"; //$NON-NLS-1$
55         private static final String TOKENVAL_ATTR = "tokenval"; //$NON-NLS-1$
56         private static IPreferenceStore store;
57         private static boolean hasXMLFileBeenRead = true;
58
59         //The following variable is used to hold the syntax from
60         //the suers custom file - if that file should be changed,
61         //then all entries in this variable should be removed from
62         //the word list, reread from the file and then reinserted.
63         private static ArrayList userdefsyntaxdata;
64
65         private static ArrayList syntaxdata;
66
67         public PHPSyntaxRdr() {
68                 // see getSyntaxData()
69                 syntaxdata = null;
70                 store = PHPeclipsePlugin.getDefault().getPreferenceStore();
71         }
72
73         public static void readInSyntax() {
74                 try {
75                         hasXMLFileBeenRead = true;
76                         /*Attempt to read the syntax file from the metadata
77                          * if this does not work, create metadata from default*/
78                         File syntaxFile = getSyntaxFile();
79                         if (syntaxFile.exists()) {
80                                 readFromFile(syntaxFile);
81                         } else {
82                                 readFromStream(
83                                         PHPSyntaxRdr.class.getResourceAsStream(PHPSYNTAX_FILE));
84                                 saveToFile(syntaxFile);
85                         }
86                         /*Read the user-defined syntax file if it exists*/
87                         //String buffer = new String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE));
88                         if (store == null)
89                                 store = PHPeclipsePlugin.getDefault().getPreferenceStore();
90                         String buffer =
91                                 new String(
92                                         store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE));
93                         if (!(buffer.equals("") || buffer == null)) {
94                                 readFromFile(buffer);
95                         }
96                 } catch (CoreException ce) {
97                         ce.printStackTrace();
98                 }
99         }
100
101         public static void readFromFile(String filename) {
102                 try {
103                         readFromFile(new File(filename));
104                 } catch (CoreException e) {
105                 }
106         }
107
108         public static void readFromFile(File file) throws CoreException {
109                 InputStream stream = null;
110
111                 if (file.exists()) {
112                         try {
113                                 stream = new FileInputStream(file);
114                                 readFromStream(stream);
115                         } catch (IOException e) {
116                                 throwReadException(e);
117                         } finally {
118                                 try {
119                                         if (stream != null) {
120                                                 stream.close();
121                                         }
122                                 } catch (IOException e) {
123                                 }
124                         }
125                 }
126         }
127         public static void readFromStream(InputStream stream)
128                 throws CoreException {
129                 try {
130                         DocumentBuilderFactory factory =
131                                 DocumentBuilderFactory.newInstance();
132                         DocumentBuilder parser = factory.newDocumentBuilder();
133                         Document document = parser.parse(new InputSource(stream));
134                         //Read in the Standard PHPSyntax "stuff"
135                         NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG);
136
137                         int count = elements.getLength();
138                         for (int i = 0; i != count; i++) {
139                                 Node node = elements.item(i);
140                                 NamedNodeMap attributes = node.getAttributes();
141
142                                 if (attributes == null)
143                                         continue;
144
145                                 String Keyword = getAttributeValue(attributes, KEYWORD_ATTR);
146                                 String Type = getAttributeValue(attributes, TYPE_ATTR);
147                                 String Function = getAttributeValue(attributes, FN_ATTR);
148                                 String Constant = getAttributeValue(attributes, CONSTANT_ATTR);
149                                 String usage = getAttributeValue(attributes, USAGE_ATTR);
150                                 String Tokenval = getAttributeValue(attributes, TOKENVAL_ATTR);
151
152                                 StringBuffer buffer = new StringBuffer();
153                                 NodeList children = node.getChildNodes();
154                                 for (int j = 0; j != children.getLength(); j++) {
155                                         String value = children.item(j).getNodeValue();
156                                         if (value != null)
157                                                 buffer.append(value);
158                                 }
159                                 String description = buffer.toString().trim();
160
161                                 if (Keyword == null
162                                         && Type == null
163                                         && Function == null
164                                         && Constant == null) {
165                                         //ignore as it is not a valid phpsyntax tag
166                                 } else {
167                                         if (Keyword != null) {
168                                                 syntaxdata.add(
169                                                         new PHPKeyword(Keyword, usage, Tokenval));
170                                         } else if (Type != null) {
171                                                 syntaxdata.add(new PHPType(Type, usage));
172                                         } else if (Function != null) {
173                                                 syntaxdata.add(
174                                                         new PHPFunction(Function, usage, description));
175                                         } else if (Constant != null) {
176                                                 syntaxdata.add(new PHPConstant(Constant, usage));
177                                         }
178                                 }
179                         }
180                 } catch (ParserConfigurationException e) {
181                         throwReadException(e);
182                 } catch (IOException e) {
183                         throwReadException(e);
184                 } catch (SAXException e) {
185                         throwReadException(e);
186                 }
187         }
188
189         public static ArrayList getSyntaxData() {
190                 if (syntaxdata==null) {
191                         syntaxdata = new ArrayList();
192                         readInSyntax();
193                 }
194                 return syntaxdata;
195         }
196
197         public static void replaceUserDefFile() {
198                 /*Replace the user-defined syntax file if it exists*/
199                 String buffer =
200                         new String(
201                                 store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE));
202                 if (!buffer.equals("") || buffer == null) {
203                         readFromFile(buffer);
204                 }
205         }
206
207         public static ArrayList getUserSyntaxData() {
208                 return userdefsyntaxdata;
209         }
210
211         private static File getSyntaxFile() {
212                 IPath path = PHPeclipsePlugin.getDefault().getStateLocation();
213                 path = path.append(PHPSYNTAX_FILE);
214                 return path.toFile();
215         }
216
217         private static String getAttributeValue(
218                 NamedNodeMap attributes,
219                 String name) {
220                 Node node = attributes.getNamedItem(name);
221                 return node == null ? null : node.getNodeValue();
222         }
223
224         public static void saveToFile(File file) throws CoreException {
225                 OutputStream stream = null;
226                 try {
227                         stream = new FileOutputStream(file);
228                         saveToStream(stream);
229                 } catch (IOException e) {
230                         throwWriteException(e);
231                 } finally {
232                         try {
233                                 if (stream != null)
234                                         stream.close();
235                         } catch (IOException e) {
236                         }
237                 }
238         }
239
240         public static void saveToStream(OutputStream stream) throws CoreException {
241                 try {
242                         DocumentBuilderFactory factory =
243                                 DocumentBuilderFactory.newInstance();
244                         DocumentBuilder builder = factory.newDocumentBuilder();
245                         Document document = builder.newDocument();
246                         Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ //$NON-NLS-1$
247                         document.appendChild(root);
248                         for (int i = 0; i != syntaxdata.size(); i++) {
249                                 Object bufferobj = (Object) syntaxdata.get(i);
250                                 Attr name = null;
251                                 Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ //$NON-NLS-1$
252                                 root.appendChild(node);
253                                 NamedNodeMap attributes = node.getAttributes();
254                                 if (bufferobj instanceof PHPType)
255                                         name = document.createAttribute(TYPE_ATTR);
256                                 if (bufferobj instanceof PHPKeyword)
257                                         name = document.createAttribute(KEYWORD_ATTR);
258                                 if (bufferobj instanceof PHPFunction)
259                                         name = document.createAttribute(FN_ATTR);
260                                 if (bufferobj instanceof PHPConstant)
261                                         name = document.createAttribute(CONSTANT_ATTR);
262                                 name.setValue(((PHPElement) bufferobj).getName());
263                                 attributes.setNamedItem(name);
264                                 Attr description = document.createAttribute(USAGE_ATTR);
265                                 description.setValue(((PHPElement) bufferobj).getUsage());
266                                 attributes.setNamedItem(description);
267                                 if (bufferobj instanceof PHPKeyword) {
268                                         Attr tokenval = document.createAttribute(TOKENVAL_ATTR);
269                                         tokenval.setValue(
270                                                 (new Integer(((PHPKeyword) bufferobj).gettokenval()))
271                                                         .toString());
272                                         attributes.setNamedItem(tokenval);
273                                 }
274                                 if (bufferobj instanceof PHPFunction) {
275                                         //      Attr usage = document.createAttribute(USAGE_ATTR);
276                                         Text usage =
277                                                 document.createTextNode(
278                                                         ((PHPFunction) bufferobj).getDescription());
279                                         node.appendChild(usage);
280                                         //          usage.setValue(((PHPFunction) bufferobj).getUsage());
281                                         //          attributes.setNamedItem(usage);
282                                 }
283                         }
284                         OutputFormat format = new OutputFormat();
285                         format.setPreserveSpace(true);
286                         try {
287                                 Serializer serializer =
288                                         SerializerFactory.getSerializerFactory(
289                                                 "xml").makeSerializer(
290                                                 stream,
291                                                 format);
292                                 serializer.asDOMSerializer().serialize(document);
293                         } catch (UnsupportedEncodingException e) {
294                         } catch (IOException e) {
295                         } //$NON-NLS-1$
296                         //                      Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$
297                 } catch (ParserConfigurationException e) {
298                         throwWriteException(e);
299                         //        } catch (IOException e) {
300                         //            throwWriteException(e);
301                 }
302         }
303
304         private static void throwReadException(Throwable t) throws CoreException {
305                 PHPeclipsePlugin.log(t);
306                 //              IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
307                 //                      ObfuscatorMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
308                 //              throw new JavaUIException(status);
309         }
310
311         private static void throwWriteException(Throwable t) throws CoreException {
312                 PHPeclipsePlugin.log(t);
313                 //              IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION,
314                 //                      ObfuscatorMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
315                 //              throw new JavaUIException(status);
316         }
317
318 }