ProcessFiles.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import java.io.*;
  2. import java.util.*;
  3. // Process command-line arguments (flags, filenames) from the given args
  4. // Read programs from named files and then from standard input.
  5. // If the '-n' flag is given, don't prompt for standard input,
  6. // otherwise prompt with "--> "
  7. // If the '-t' command line argument is given, toggle the trace feature
  8. // (defaults to no trace)
  9. // For each input program, use 'action' to parse the input
  10. // and act on the resulting parse tree
  11. public abstract class ProcessFiles {
  12. // build a parse tree and act on it
  13. abstract void action(Scan scn, Trace trace);
  14. public void processFile(Scan scn, Trace trace, String prompt, String prog) {
  15. try {
  16. // read and process programs from this
  17. while(true) {
  18. System.out.print(prompt);
  19. if (scn.isEOF())
  20. break;
  21. if (trace != null)
  22. trace.reset();
  23. if (prog != null) {
  24. System.out.print(prog);
  25. if (trace != null)
  26. System.out.println(); // format the trace better
  27. }
  28. action(scn, trace);
  29. }
  30. } catch (Exception e) {
  31. System.err.println(e.getMessage());
  32. } catch (Error e) {
  33. System.err.println(e);
  34. System.exit(1);
  35. }
  36. }
  37. public void processFiles(String [] args) {
  38. Trace trace = null;
  39. // first read and process any input files from the command line
  40. Scan scn = null;
  41. String prog = null;
  42. String prompt = "--> ";
  43. for (int i=0 ; i<args.length ; i++) {
  44. String s = args[i];
  45. if (s.equals("-n")) {
  46. // turns off prompts when reading from stdin
  47. prompt = "";
  48. continue;
  49. }
  50. if (s.equals("-t")) {
  51. // toggle traces
  52. trace = (trace == null ? new Trace() : null);
  53. continue;
  54. }
  55. if (s.equals("-v")) {
  56. // toggle verbose cmd line name output
  57. prog = (prog == null ? "" : null);
  58. continue;
  59. }
  60. try {
  61. scn = new Scan(new BufferedReader(new FileReader(s)));
  62. } catch (FileNotFoundException e) {
  63. System.err.println(s + ": no such file ... exiting");
  64. System.exit(1);
  65. }
  66. if (prog != null)
  67. prog = "[" + s + "]";
  68. processFile(scn, trace, "", prog);
  69. }
  70. // finally read and process programs from standard input
  71. BufferedReader rdr =
  72. new BufferedReader(new InputStreamReader(System.in));
  73. scn = new Scan(rdr);
  74. if (prog != null)
  75. prog = "[stdin]";
  76. processFile(scn, trace, prompt, prog);
  77. }
  78. }