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      private final StringBuilder strb = new StringBuilder();
29      private int indent = 0;
30  
31      private void indent() {
32          for (int i = 0; i < indent; ++i) {
33              strb.append("  ");
34          }
35      }
36  
37      private void dump(final JexlNode node, final Object data) {
38          final int num = node.jjtGetNumChildren();
39          indent();
40          strb.append(node.getClass().getSimpleName());
41          if (node instanceof ASTIdentifier) {
42              strb.append("@");
43              strb.append(node.toString());
44          } else if (node instanceof ASTIdentifierAccess) {
45              strb.append("@");
46              strb.append(node.toString());
47          }
48          strb.append('(');
49          indent += 1;
50          for (int c = 0; c < num; ++c) {
51              final JexlNode child = node.jjtGetChild(c);
52              if (c > 0) {
53                  strb.append(',');
54              }
55              strb.append('\n');
56              dump(child, data);
57          }
58          indent -= 1;
59          if (num > 0) {
60              strb.append('\n');
61              indent();
62          }
63          strb.append(')');
64      }
65  
66      private Dumper(final JexlScript script) {
67          dump(((Script) script).script, null);
68      }
69  
70      @Override
71      public String toString() {
72          return strb.toString();
73      }
74  
75      public static String toString(final JexlScript script) {
76          return new Dumper(script).toString();
77      }
78  }