1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.Sequence.Position;
4 import edu.berkeley.sbp.GSS.Phase;
5 import edu.berkeley.sbp.GSS.Phase.Node;
6 import edu.berkeley.sbp.util.*;
10 /** thrown when the parser arrives at a state from which it is clear that no valid parse can result */
11 public class ParseFailed extends RuntimeException {
12 private final Input.Location location;
13 private final String message;
14 public ParseFailed() { this("", null); }
15 public ParseFailed(String message, Input.Location loc) { this.location = loc; this.message = message; }
16 public Input.Location getLocation() { return location; }
17 public String toString() { return message/* + (location==null ? "" : (" at " + location))*/; }
20 private static HashSet<GSS.Phase.Node> touched = new HashSet<GSS.Phase.Node>();
21 public static <Tok> void complain(GSS.Phase<Tok>.Node n, HashMap<String,HashSet<String>> errors, boolean force) {
22 if (touched.contains(n)) return;
24 for(Position p : n.state) {
25 if (((p.isFirst() || p.isLast()) && !force) || p.owner().name==null) {
26 for(Node n2 : n.parents())
27 complain(n2, errors, force | p.isFirst());
29 String seqname = p.owner().name;
30 HashSet<String> hs = errors.get(seqname);
31 if (hs==null) errors.put(seqname, hs = new HashSet<String>());
32 hs.add(p.element()+"");
37 public static String el(Object e) {
38 String s = e.toString();
39 if (s.length()==0 || s.charAt(0)!='\"' || s.charAt(s.length()-1)!='\"') return ANSI.yellow(s);
41 s = s.substring(0, s.length()-1);
42 StringBuffer ret = new StringBuffer();
43 for(int i=0; i<s.length(); i++) {
44 if (s.charAt(i)=='\\' && i<s.length()-1) ret.append(s.charAt(++i));
47 return ANSI.purple(ret.toString());
49 public static String error(String message, Object token, Iterable<Node> nodes) {
50 String lookAhead = token==null ? "<EOF>" : token.toString();
51 StringBuffer ret = new StringBuffer();
54 HashMap<String,HashSet<String>> errors = new HashMap<String,HashSet<String>>();
56 //System.out.println(n.state);
57 complain(n, errors, false);
59 for(String s : errors.keySet()) {
60 ret.append(" while parsing " + ANSI.yellow(s));
61 HashSet<String> hs = errors.get(s);
62 if (hs.size()==1) ret.append(" expected " + ANSI.yellow(el(hs.iterator().next())) + "\n");
64 ret.append(" expected ");
67 if (!first) ret.append(" or ");
69 ret.append(ANSI.yellow(el(s2)));
74 return ret.toString();