001package jtb.cparser.customvisitor;
002
003import jtb.cparser.syntaxtree.*;
004import jtb.cparser.visitor.*;
005import java.util.*;
006import java.io.*;
007
008public class Printer extends DepthFirstVisitor {
009
010  private PrintWriter out;
011  private StringBuffer buffer;
012  private ArrayList<String> filter;
013  public static List<String> badExpressions;
014  private File file;
015
016  static {
017    ArrayList<String> temp = new ArrayList<String>();
018    temp.add("(unsigned)");
019    temp.add("(unsignedshortint)");
020    temp.add("(__ctype)");
021    temp.add("fgets");
022    badExpressions = Collections.unmodifiableList(temp);
023  }
024
025  public Printer(String fileName) throws IOException {
026    buffer = new StringBuffer();
027    out = new PrintWriter(new FileOutputStream(fileName));
028  }
029
030  public void visit(NodeToken n) {
031    buffer.append(n.tokenImage);
032  }
033
034  public void close() throws IOException {
035    out.close();
036  }
037
038  public void println() {
039    out.println();
040  }
041
042  public void print(Object o) {
043    out.print(o.toString());
044  }
045
046  public boolean shouldPrint(String curr, int index) {
047    return (index >= 0 &&
048            ((index+curr.length() == buffer.length()) ||
049             (index >=1 && !Character.isLetterOrDigit(buffer.charAt(index-1)))
050             ||
051             !Character.isLetterOrDigit(buffer.charAt(index+curr.length())))
052            );
053
054  }
055
056  public void commit() {
057    boolean okToPrint = true;
058    // if the expression contains any of the
059    // strings that should be filtered, don't
060    // print it
061    for (int i = 0; i < filter.size(); i++) {
062      String curr = filter.get(i);
063      int index = buffer.toString().indexOf(curr);
064      if (shouldPrint(curr, index)) {
065        okToPrint = false;
066        break;
067      }
068    }
069    if (okToPrint) {
070      // replaceNulls();
071      out.println(buffer);
072    }
073    buffer = new StringBuffer();
074  }
075
076  public void setFilter(ArrayList<String> filter) {
077    this.filter = filter;
078    this.filter.addAll(badExpressions);
079  }
080
081
082  public void visit(LogicalANDExpression n) {
083    if (n.f0 !=null) {
084      n.f0.accept(this);
085    }
086    n.f1.accept(this);
087  }
088
089  public void visit(LogicalORExpression n) {
090    if (n.f0 !=null) {
091      n.f0.accept(this);
092    }
093    n.f1.accept(this);
094  }
095
096  public void visit(EqualityExpression n) {
097    if (n.f0 != null) {
098      n.f0.accept(this);
099    }
100    n.f1.accept(this);
101  }
102
103  public void visit(RelationalExpression n) {
104    if (n.f0 != null) {
105      n.f0.accept(this);
106    }
107    n.f1.accept(this);
108  }
109
110}