1 package jfun.parsec.trace; 2 3 import java.io.PrintWriter ; 4 5 12 public class Traces { 13 private static final int LDEADING = 32; 14 private static String getLeadingChars (CharSequence src, int ind, int n) { 15 int len = src.length(); 16 if (ind >= len) { 17 return "<EOF>"; 18 } 19 if (n + ind >= len) { 20 n = len - ind; 21 return src.subSequence(ind, ind+n).toString(); 22 } 23 return src.subSequence (ind, ind+n).toString() + "..."; 24 } 25 private static void printStatus(final PrintWriter out, CharSequence src, int ind, int steps, int offset){ 26 out.print('['); 27 out.print(getLeadingChars (src, ind, LDEADING)); 28 out.println(']'); 29 out.println("steps="+steps+", offset="+offset); 30 } 31 private static void printErrorTrace( 32 final int min_steps, final String name, final PrintWriter out, Object exception, CharSequence src, int ind, int steps, int offset) { 33 if(steps < min_steps) return; 34 out.print(name); 35 out.print(": "); 36 if(exception != null){ 37 out.println("exception raised."); 38 } 39 printStatus(out, src, ind, steps, offset); 40 out.flush(); 41 } 42 private static void printResultTrace(final String name, final PrintWriter out, Object result, CharSequence src, int ind, int steps, int offset) { 43 out.println(name + " => "+ result); 44 printStatus(out, src, ind, steps, offset); 45 out.flush(); 46 } 47 54 public static Trace<Object > printError (final String name, final PrintWriter out, final int min_steps) { 55 return new EmptyTrace<Object >(){ 56 @Override 57 public void onError(Object exception, CharSequence src, int ind, int steps, int offset){ 58 printErrorTrace(min_steps, name, out, exception, src, ind, steps, offset); 59 } 60 }; 61 } 62 68 public static Trace<Object > printResult(final String name, final PrintWriter out){ 69 return new EmptyTrace<Object >(){ 70 @Override 71 public void onSuccess(Object result, CharSequence src, int ind, int steps, int offset){ 72 printResultTrace(name, out, result, src, ind, steps, offset); 73 } 74 }; 75 } 76 83 public static Trace<Object > printTrace(final String name, final PrintWriter out){ 84 return new Trace<Object >(){ 85 public void onError(Object exception, CharSequence src, int ind, int steps, int offset){ 86 printErrorTrace(1, name, out, exception, src, ind, steps, offset); 87 } 88 public void onSuccess(Object result, CharSequence src, int ind, int steps, int offset){ 89 printResultTrace(name, out, result, src, ind, steps, offset); 90 } 91 }; 92 } 93 } 94 | Popular Tags |