1 8 13 package jfun.parsec; 14 import java.util.Arrays ; 15 import java.util.TreeSet ; 16 17 18 24 final class DefaultShowError implements java.io.Serializable { 25 26 29 static String show(final ParseError err, final Pos pos) { 30 return toErrorStr(err, pos); 31 } 32 private static String toErrorStr(final ParseError err, final Pos pos){ 33 final StringBuffer buf = new StringBuffer (); 34 if(pos != null) 35 buf.append("line " + pos.getLineNo() + ", column " + pos.getColumnNo()); 36 if(err!=null){ 37 buf.append(":\n"); 38 showExpecting(buf, err.getExpecting()); 39 showUnexpected(buf, err.getUnexpected()); 40 showMessages(buf, err.getMessages()); 41 showEncountered(buf, err.getEncountered()); 42 } 43 return buf.toString(); 44 } 45 private static void showEncountered(final StringBuffer buf, final String s){ 46 if(s==null) return; 47 buf.append(s).append(" encountered.\n"); 48 } 49 private static String [] unique(final String [] msgs){ 50 if(msgs.length <= 1) return msgs; 51 final TreeSet set = new TreeSet (Arrays.asList(msgs)); 52 final String [] umsgs = new String [set.size()]; 53 set.toArray(umsgs); 54 return umsgs; 55 } 56 private static void showList(final StringBuffer buf, final String [] msgs){ 57 if(msgs.length==0) return; 58 for(int i=0; i<msgs.length-1; i++){ 59 buf.append(msgs[i]).append(' '); 60 } 61 if(msgs.length > 1) buf.append("or "); 62 buf.append(msgs[msgs.length-1]); 63 } 64 private static void showExpecting(final StringBuffer buf, final String [] msgs) { 65 if(msgs==null || msgs.length == 0) return; 66 final String [] umsgs = unique(msgs); 67 buf.append("expecting "); 68 showList(buf, umsgs); 69 buf.append(".\n"); 70 } 71 private static void showUnexpected(final StringBuffer buf, final String [] msgs) { 72 if(msgs==null || msgs.length == 0) return; 73 showList(buf, unique(msgs)); 74 buf.append(" unexpected.\n"); 75 } 76 private static void showMessages(final StringBuffer buf, final String [] msgs){ 77 if(msgs==null || msgs.length == 0) return; 78 buf.append(msgs[0]); 79 for(int i=1; i<msgs.length; i++){ 80 buf.append(" or \n").append(msgs[i]); 81 } 82 buf.append("\n"); 83 } 84 private DefaultShowError(){} 85 } 86 | Popular Tags |