-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrinter.java
More file actions
87 lines (79 loc) · 1.75 KB
/
Printer.java
File metadata and controls
87 lines (79 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* A class for printing a parse tree.
*/
public class Printer {
/** The current indentation depth */
private int depth = 0;
/** If <code>true</code> the printer won't print anything. */
private boolean silent = false;
/**
* Construct a new Printer.
*
* @param silent If <code>true</code> the printer won't print
* anything.
*/
public Printer(boolean silent) {
this.silent = silent;
}
/**
* Increase the indentation depth.
*/
private void incDepth() {
depth++;
if (!silent) {
System.out.print("(");
}
}
/**
* Decrease the indentation depth.
*/
private void decDepth() {
println(")");
depth--;
indent();
}
/**
* Indent the next line.
*/
private void indent() {
if (!silent) {
for(int i = 0; i < depth; i++) {
System.out.print(" ");
}
}
}
/**
* Print a string on its own line.
* @param s the string to be printed
*/
private void println(String s) {
if (!silent)
System.out.println(s);
}
/**
* Print a string and indent.
* @param s the string to be printed.
*/
public void print(String s) {
println(s);
indent();
}
/**
* Open the parse tree node by printing "(<name>\n" and increasing
* indentation.
*
* @param name the name of the nonterminal.
*/
public void startProduction(String name) {
incDepth();
println(name);
indent();
}
/**
* Close the parse tree node by printing ")" and decreasing
* indentation.
*/
public void endProduction() {
decDepth();
}
}