OSDN Git Service

imported from subversion repository
[xerial/xerial-core.git] / src / main / java / org / xerial / util / antlr / ANTLRUtil.java
1 /*--------------------------------------------------------------------------\r
2  *  Copyright 2008 Taro L. Saito\r
3  *\r
4  *  Licensed under the Apache License, Version 2.0 (the "License");\r
5  *  you may not use this file except in compliance with the License.\r
6  *  You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  *  Unless required by applicable law or agreed to in writing, software\r
11  *  distributed under the License is distributed on an "AS IS" BASIS,\r
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  *  See the License for the specific language governing permissions and\r
14  *  limitations under the License.\r
15  *--------------------------------------------------------------------------*/\r
16 //--------------------------------------\r
17 // XerialJ\r
18 //\r
19 // ANTLRUtil.java\r
20 // Since: Nov 4, 2008 9:51:27 AM\r
21 //\r
22 // $URL: http://www.xerial.org/svn/project/XerialJ/trunk/xerial-core/src/main/java/org/xerial/util/antlr/ANTLRUtil.java $\r
23 // $Author: leo $\r
24 //--------------------------------------\r
25 package org.xerial.util.antlr;\r
26 \r
27 import java.io.IOException;\r
28 import java.net.URL;\r
29 import java.util.ArrayList;\r
30 import java.util.Iterator;\r
31 import java.util.List;\r
32 import java.util.Map;\r
33 import java.util.Properties;\r
34 import java.util.TreeMap;\r
35 \r
36 import org.antlr.runtime.Token;\r
37 import org.antlr.runtime.tree.Tree;\r
38 import org.xerial.core.XerialError;\r
39 import org.xerial.core.XerialErrorCode;\r
40 import org.xerial.util.FileResource;\r
41 import org.xerial.util.StringUtil;\r
42 import org.xerial.util.log.Logger;\r
43 \r
44 public class ANTLRUtil {\r
45     private static Logger _logger = Logger.getLogger(ANTLRUtil.class);\r
46 \r
47     public static String toVisibleString(String text) {\r
48         text = text.replaceAll("\n", "\\\\n");\r
49         text = text.replaceAll("\r", "\\\\r");\r
50         text = text.replaceAll("\t", "\\\\t");\r
51         return String.format("\"%s\"", text);\r
52     }\r
53 \r
54     /**\r
55      * Generates a string representation of the parse tree.\r
56      * \r
57      * @param t\r
58      *            parse tree\r
59      * @param parserTokenNames\r
60      *            pass the ANTLR Parser.tokenNames\r
61      * @return a string representation of the parse tree\r
62      */\r
63     public static String parseTree(Tree t, String[] parserTokenNames) {\r
64         StringBuilder sb = new StringBuilder();\r
65         parseTree(sb, t, 0, parserTokenNames);\r
66         return sb.toString();\r
67     }\r
68 \r
69     private static void parseTree(StringBuilder sb, Tree t, int depth, String[] parserTokenNames) {\r
70         if (t == null)\r
71             return;\r
72 \r
73         // input node itself\r
74         for (int i = 0; i < depth; i++) {\r
75             sb.append(" ");\r
76         }\r
77         String tokenName = parserTokenNames[t.getType()];\r
78         sb.append("[");\r
79         sb.append(tokenName);\r
80         sb.append("]\t");\r
81         if (t.getText() != null && !t.getText().equals(tokenName))\r
82             sb.append(toVisibleString(t.getText()));\r
83         sb.append(StringUtil.newline());\r
84 \r
85         // child nodes\r
86         for (int i = 0; i < t.getChildCount(); i++) {\r
87             parseTree(sb, t.getChild(i), depth + 1, parserTokenNames);\r
88         }\r
89     }\r
90 \r
91     @SuppressWarnings("unchecked")\r
92     public static Map<Integer, String> getTokenTable(Class< ? > packageBaseClass,\r
93             String tokenFileName) {\r
94         Properties p = new Properties();\r
95         TreeMap<Integer, String> tokenTable = new TreeMap<Integer, String>();\r
96 \r
97         URL wikiTokenFileURL = FileResource.find(packageBaseClass, tokenFileName);\r
98         try {\r
99             if (wikiTokenFileURL != null)\r
100                 p.load(wikiTokenFileURL.openStream());\r
101         }\r
102         catch (IOException e) {\r
103             throw new XerialError(XerialErrorCode.IO_EXCEPTION, e);\r
104         }\r
105 \r
106         for (Iterator it = p.keySet().iterator(); it.hasNext();) {\r
107             String tokenName = (String) it.next();\r
108             try {\r
109                 int tokenType = Integer.parseInt(p.get(tokenName).toString());\r
110                 tokenTable.put(tokenType, tokenName);\r
111             }\r
112             catch (NumberFormatException e) {\r
113                 _logger.warn(e);\r
114             }\r
115 \r
116         }\r
117 \r
118         return tokenTable;\r
119     }\r
120 \r
121     @SuppressWarnings("unchecked")\r
122     public static List<String> prettyPrintTokenList(List tokenList, Map<Integer, String> tokenTable) {\r
123         ArrayList<String> result = new ArrayList<String>();\r
124         for (Iterator it = tokenList.iterator(); it.hasNext();) {\r
125             Token t = (Token) it.next();\r
126             result.add(prettyPrint(t, tokenTable));\r
127         }\r
128         return result;\r
129     }\r
130 \r
131     public static String prettyPrint(Token t, Map<Integer, String> tokenTable) {\r
132 \r
133         int charStart = t.getCharPositionInLine();\r
134         int charEnd = charStart + t.getText().length();\r
135         return String.format("[%2d[%2d,%2d)] %12s: %s", t.getLine(), charStart, charEnd, tokenTable\r
136                 .get(t.getType()), ANTLRUtil.toVisibleString(t.getText()));\r
137     }\r
138 \r
139 }\r