001/* 002 * Copyright (C) 2009-2011 Mathias Doenitz 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.parboiled.support; 018 019import org.parboiled.Node; 020import org.parboiled.buffers.InputBuffer; 021import org.parboiled.common.Formatter; 022import org.parboiled.common.StringUtils; 023 024import static org.parboiled.common.Preconditions.checkArgNotNull; 025 026/** 027 * A simple {@literal Formatter<Node>} that provides String representation for parse tree nodes. 028 */ 029public class NodeFormatter<V> implements Formatter<Node<V>> { 030 031 private final InputBuffer inputBuffer; 032 033 /** 034 * Creates a new NodeFormatter. 035 * 036 * @param inputBuffer the input buffer underlying the parse tree whose nodes are to be formatted. 037 */ 038 public NodeFormatter(InputBuffer inputBuffer) { 039 this.inputBuffer = checkArgNotNull(inputBuffer, "inputBuffer"); 040 } 041 042 public String format(Node<V> node) { 043 String nodeLabel = node.toString(); 044 String nodeText = StringUtils.escape(ParseTreeUtils.getNodeText(node, inputBuffer)); 045 return StringUtils.isEmpty(nodeText) ? nodeLabel : nodeLabel + " '" + nodeText + '\''; 046 } 047 048}