1 // Copyright 2006-2007 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp.misc;
6 import java.lang.reflect.*;
7 import java.lang.ref.*;
8 import edu.berkeley.sbp.*;
9 import edu.berkeley.sbp.Input.Location;
10 import edu.berkeley.sbp.util.*;
12 public class Cartesian {
14 public static abstract class Input<Token> implements edu.berkeley.sbp.Input<Token> {
16 public abstract Token _next() throws IOException;
17 public abstract boolean isCR();
20 private Cartesian.Location location = new Cartesian.Location();
21 public edu.berkeley.sbp.Input.Location getLocation() { return location; }
23 public Token next() throws IOException {
24 int line = location.getRow();
25 int col = location.getCol();
26 int scalar = location.getScalar();
28 if (t==null) return null;
35 location.next = new Cartesian.Location(col, line, scalar+1);
36 location.next.prev = location;
37 location = location.next;
41 public String showRegion(Input.Region<Token> region) {
46 /** an implementation of Location for a cartesian grid (row, col) */
47 public static class Location<Tok> implements Input.Location<Tok>, Comparable<Input.Location> {
48 protected final int row;
49 protected final int col;
50 protected final int scalar;
51 Location<Tok> next = null;
52 Location<Tok> prev = null;
53 public Location<Tok> next() { return next; }
54 public Location<Tok> prev() { return prev; }
55 public String toString() { return row+":"+col; }
56 public int getCol() { return col; }
57 public int getRow() { return row; }
58 public int getScalar() { return scalar; }
59 public Location() { this(-1, 1, 0); }
60 public Location(int col, int row, int scalar) { this.row = row; this.col = col; this.scalar = scalar; }
61 public int compareTo(Input.Location loc) throws ClassCastException {
62 if (!(loc instanceof Cartesian.Location)) throw new ClassCastException(loc.getClass().getName());
63 Location<Tok> c = (Location<Tok>)loc;
64 if (row < c.row) return -1;
65 if (row > c.row) return 1;
66 if (col < c.col) return -1;
67 if (col > c.col) return 1;
70 public Input.Region<Tok> createRegion(Input.Location<Tok> loc) {
71 return new Region<Tok>(this, (Cartesian.Location<Tok>)loc); }
74 public static class Region<Tok> implements Input.Region<Tok> {
75 public final Location<Tok> start;
76 public final Location<Tok> end;
77 public Location<Tok> getStart() { return start; }
78 public Location<Tok> getEnd() { return end; }
79 public String toString() {
80 if (start.row==end.row && start.col==end.col) return start+"";
81 if (start.row==end.row) return start.row+":"+(start.col+"-"+end.col);
84 public Region(Location<Tok> a, Location<Tok> b) {
85 switch(a.compareTo(b)) {
87 case 0: start=a; end=b; return;
88 case 1: start=b; end=a; return;
89 default: throw new Error("impossible");