1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.*;
5 import edu.berkeley.sbp.Sequence.Position;
6 import edu.berkeley.sbp.GSS.Phase;
7 import edu.berkeley.sbp.GSS.Phase.Node;
8 import edu.berkeley.sbp.util.*;
12 /** thrown when the parser arrives at a state from which it is clear that no valid parse can result */
13 public class ParseFailed extends Exception {
15 private final Input.Location location;
16 private final String message;
17 ParseFailed() { this("", null); }
18 ParseFailed(String message, Input.Location loc) { this.location = loc; this.message = message; }
19 public Input.Location getLocation() { return location; }
20 public String toString() { return message/* + (location==null ? "" : (" at " + location))*/; }
23 private static HashSet<GSS.Phase.Node> touched = new HashSet<GSS.Phase.Node>();
24 static <Tok> void complain(GSS.Phase<Tok>.Node n, HashMap<String,HashSet<String>> errors, boolean force) {
25 if (touched.contains(n)) return;
27 for(Position p : n.state) {
28 if (((p.isFirst() || p.isLast()) && !force)/* || p.owner().name==null*/) {
29 for(Node n2 : n.parents())
30 complain(n2, errors, force | p.isFirst());
32 String seqname = p.owner()/*.name*/+"";
33 HashSet<String> hs = errors.get(seqname);
34 if (hs==null) errors.put(seqname, hs = new HashSet<String>());
35 hs.add(p.element()+"");
40 static String el(Object e) {
41 String s = e.toString();
42 if (s.length()==0 || s.charAt(0)!='\"' || s.charAt(s.length()-1)!='\"') return /*ANSI.yellow(s)*/s;
44 s = s.substring(0, s.length()-1);
45 StringBuffer ret = new StringBuffer();
46 for(int i=0; i<s.length(); i++) {
47 if (s.charAt(i)=='\\' && i<s.length()-1) ret.append(s.charAt(++i));
50 return /*ANSI.purple(ret.toString())*/ret.toString();
52 static String error(String message, Object token, Iterable<Node> nodes) {
53 String lookAhead = token==null ? "<EOF>" : token.toString();
54 StringBuffer ret = new StringBuffer();
58 HashMap<String,HashSet<String>> errors = new HashMap<String,HashSet<String>>();
60 //System.out.println(n.state);
61 complain(n, errors, false);
63 for(String s : errors.keySet()) {
64 ret.append(" while parsing " + ANSI.yellow(s));
65 HashSet<String> hs = errors.get(s);
66 if (hs.size()==1) ret.append(" expected " + ANSI.yellow(el(hs.iterator().next())) + "\n");
68 ret.append(" expected ");
71 if (!first) ret.append(" or ");
73 ret.append(ANSI.yellow(el(s2)));
79 return ret.toString();