View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.jexl3.internal;
18  
19  import org.apache.commons.jexl3.JexlScript;
20  import org.apache.commons.jexl3.parser.ASTIdentifier;
21  import org.apache.commons.jexl3.parser.ASTIdentifierAccess;
22  import org.apache.commons.jexl3.parser.JexlNode;
23  
24  /**
25   * Utility to dump AST, useful in debug sessions.
26   */
27  public class Dumper {
28      public static String toString(final JexlScript script) {
29          return new Dumper(script).toString();
30      }
31      private final StringBuilder strb = new StringBuilder();
32  
33      private int indent;
34  
35      private Dumper(final JexlScript script) {
36          dump(((Script) script).script, null);
37      }
38  
39      private void dump(final JexlNode node, final Object data) {
40          final int num = node.jjtGetNumChildren();
41          indent();
42          strb.append(node.getClass().getSimpleName());
43          if (node instanceof ASTIdentifier || node instanceof ASTIdentifierAccess) {
44              strb.append("@");
45              strb.append(node.toString());
46          }
47          strb.append('(');
48          indent += 1;
49          for (int c = 0; c < num; ++c) {
50              final JexlNode child = node.jjtGetChild(c);
51              if (c > 0) {
52                  strb.append(',');
53              }
54              strb.append('\n');
55              dump(child, data);
56          }
57          indent -= 1;
58          if (num > 0) {
59              strb.append('\n');
60              indent();
61          }
62          strb.append(')');
63      }
64  
65      private void indent() {
66          for (int i = 0; i < indent; ++i) {
67              strb.append("  ");
68          }
69      }
70  
71      @Override
72      public String toString() {
73          return strb.toString();
74      }
75  }