com.github.basking2.sdsai.itrex.SimpleExpressionGenerator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sdsai-itrex Show documentation
Show all versions of sdsai-itrex Show documentation
An S-Expression inspiried library focused on iterators.
package com.github.basking2.sdsai.itrex;
import com.github.basking2.sdsai.itrex.iterators.Iterators;
import java.util.Iterator;
/**
* This generator will convert objects that represent expressions into a textual form.
*
* If Objects are encountered that are not primitives, lists, or iterables, the will be converted to strings.
*/
public class SimpleExpressionGenerator {
final private Object expression;
final StringBuilder sb = new StringBuilder();
/**
* A prefix for pretty printing.
*/
final String prefix;
public SimpleExpressionGenerator(final Object expression, final String prefix) {
this.expression = expression;
this.prefix = prefix;
}
public SimpleExpressionGenerator(final Object expression) {
this(expression, null);
}
public String generate() {
emit(expression, 0);
return sb.toString();
}
private void emit(final Object o, final int depth) {
if (o == null) {
emit("", depth);
}
else if (o instanceof Integer) {
emitPrefix(depth);
sb.append((Integer)o);
}
else if (o instanceof Long) {
emitPrefix(depth);
sb.append((Long)o).append("l");
}
else if (o instanceof Double) {
emitPrefix(depth);
sb.append((Double)o).append("d");
}
else if (o instanceof Float) {
// Treat floats as doubles.
emit(((Float)o).doubleValue(), depth);
}
else if (o instanceof CommentBlock) {
emitPrefix(depth);
sb.append("[* ").append(((CommentBlock)o).getContents()).append(" *]");
}
else if (o instanceof String) {
final String s = o.toString();
emitPrefix(depth);
// If a word is all "safe" characters, no need to quote it.
if (SimpleExpressionParser.WORD.matcher(s).matches()) {
sb.append(s);
}
else {
sb.append(
"\""
+ s
.replaceAll("\\\\", "\\\\\\\\")
.replaceAll("\"", "\\\"")
+ "\"");
}
}
else {
final Iterator
© 2015 - 2024 Weber Informatics LLC | Privacy Policy