Skip to content

Commit 308f10c

Browse files
committed
Rollup merge of rust-lang#33309 - birkenfeld:pp, r=nrc
Make libsyntax::print::pp more idiomatic Minor cleanup, and using VecDeque as a ring buffer instead of a vector.
2 parents 40199f6 + 4186169 commit 308f10c

File tree

1 file changed

+44
-85
lines changed

1 file changed

+44
-85
lines changed

src/libsyntax/print/pp.rs

+44-85
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,9 @@
6161
//! line (which it can't) and so naturally place the content on its own line to
6262
//! avoid combining it with other lines and making matters even worse.
6363
64+
use std::collections::VecDeque;
65+
use std::fmt;
6466
use std::io;
65-
use std::string;
6667

6768
#[derive(Clone, Copy, PartialEq)]
6869
pub enum Breaks {
@@ -112,35 +113,30 @@ impl Token {
112113
}
113114
}
114115

115-
pub fn tok_str(token: &Token) -> String {
116-
match *token {
117-
Token::String(ref s, len) => format!("STR({},{})", s, len),
118-
Token::Break(_) => "BREAK".to_string(),
119-
Token::Begin(_) => "BEGIN".to_string(),
120-
Token::End => "END".to_string(),
121-
Token::Eof => "EOF".to_string()
116+
impl fmt::Display for Token {
117+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
118+
match *self {
119+
Token::String(ref s, len) => write!(f, "STR({},{})", s, len),
120+
Token::Break(_) => f.write_str("BREAK"),
121+
Token::Begin(_) => f.write_str("BEGIN"),
122+
Token::End => f.write_str("END"),
123+
Token::Eof => f.write_str("EOF"),
124+
}
122125
}
123126
}
124127

125-
pub fn buf_str(toks: &[Token],
126-
szs: &[isize],
127-
left: usize,
128-
right: usize,
129-
lim: usize)
130-
-> String {
128+
fn buf_str(toks: &[Token], szs: &[isize], left: usize, right: usize, lim: usize) -> String {
131129
let n = toks.len();
132130
assert_eq!(n, szs.len());
133131
let mut i = left;
134132
let mut l = lim;
135-
let mut s = string::String::from("[");
133+
let mut s = String::from("[");
136134
while i != right && l != 0 {
137135
l -= 1;
138136
if i != left {
139137
s.push_str(", ");
140138
}
141-
s.push_str(&format!("{}={}",
142-
szs[i],
143-
tok_str(&toks[i])));
139+
s.push_str(&format!("{}={}", szs[i], &toks[i]));
144140
i += 1;
145141
i %= n;
146142
}
@@ -169,7 +165,7 @@ pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> {
169165
debug!("mk_printer {}", linewidth);
170166
let token = vec![Token::Eof; n];
171167
let size = vec![0; n];
172-
let scan_stack = vec![0; n];
168+
let scan_stack = VecDeque::with_capacity(n);
173169
Printer {
174170
out: out,
175171
buf_len: n,
@@ -182,9 +178,6 @@ pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> {
182178
left_total: 0,
183179
right_total: 0,
184180
scan_stack: scan_stack,
185-
scan_stack_empty: true,
186-
top: 0,
187-
bottom: 0,
188181
print_stack: Vec::new(),
189182
pending_indentation: 0
190183
}
@@ -246,9 +239,8 @@ pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> {
246239
/// approximation for purposes of line breaking).
247240
///
248241
/// The "input side" of the printer is managed as an abstract process called
249-
/// SCAN, which uses 'scan_stack', 'scan_stack_empty', 'top' and 'bottom', to
250-
/// manage calculating 'size'. SCAN is, in other words, the process of
251-
/// calculating 'size' entries.
242+
/// SCAN, which uses 'scan_stack', to manage calculating 'size'. SCAN is, in
243+
/// other words, the process of calculating 'size' entries.
252244
///
253245
/// The "output side" of the printer is managed by an abstract process called
254246
/// PRINT, which uses 'print_stack', 'margin' and 'space' to figure out what to
@@ -291,13 +283,7 @@ pub struct Printer<'a> {
291283
/// Begin (if there is any) on top of it. Stuff is flushed off the
292284
/// bottom as it becomes irrelevant due to the primary ring-buffer
293285
/// advancing.
294-
scan_stack: Vec<usize> ,
295-
/// Top==bottom disambiguator
296-
scan_stack_empty: bool,
297-
/// Index of top of scan_stack
298-
top: usize,
299-
/// Index of bottom of scan_stack
300-
bottom: usize,
286+
scan_stack: VecDeque<usize> ,
301287
/// Stack of blocks-in-progress being flushed by print
302288
print_stack: Vec<PrintStackElem> ,
303289
/// Buffered indentation to avoid writing trailing whitespace
@@ -316,15 +302,15 @@ impl<'a> Printer<'a> {
316302
debug!("pp Vec<{},{}>", self.left, self.right);
317303
match token {
318304
Token::Eof => {
319-
if !self.scan_stack_empty {
305+
if !self.scan_stack.is_empty() {
320306
self.check_stack(0);
321307
self.advance_left()?;
322308
}
323309
self.indent(0);
324310
Ok(())
325311
}
326312
Token::Begin(b) => {
327-
if self.scan_stack_empty {
313+
if self.scan_stack.is_empty() {
328314
self.left_total = 1;
329315
self.right_total = 1;
330316
self.left = 0;
@@ -339,7 +325,7 @@ impl<'a> Printer<'a> {
339325
Ok(())
340326
}
341327
Token::End => {
342-
if self.scan_stack_empty {
328+
if self.scan_stack.is_empty() {
343329
debug!("pp End/print Vec<{},{}>", self.left, self.right);
344330
self.print(token, 0)
345331
} else {
@@ -353,7 +339,7 @@ impl<'a> Printer<'a> {
353339
}
354340
}
355341
Token::Break(b) => {
356-
if self.scan_stack_empty {
342+
if self.scan_stack.is_empty() {
357343
self.left_total = 1;
358344
self.right_total = 1;
359345
self.left = 0;
@@ -370,7 +356,7 @@ impl<'a> Printer<'a> {
370356
Ok(())
371357
}
372358
Token::String(s, len) => {
373-
if self.scan_stack_empty {
359+
if self.scan_stack.is_empty() {
374360
debug!("pp String('{}')/print Vec<{},{}>",
375361
s, self.left, self.right);
376362
self.print(Token::String(s, len), len)
@@ -392,12 +378,10 @@ impl<'a> Printer<'a> {
392378
if self.right_total - self.left_total > self.space {
393379
debug!("scan window is {}, longer than space on line ({})",
394380
self.right_total - self.left_total, self.space);
395-
if !self.scan_stack_empty {
396-
if self.left == self.scan_stack[self.bottom] {
397-
debug!("setting {} to infinity and popping", self.left);
398-
let scanned = self.scan_pop_bottom();
399-
self.size[scanned] = SIZE_INFINITY;
400-
}
381+
if Some(&self.left) == self.scan_stack.back() {
382+
debug!("setting {} to infinity and popping", self.left);
383+
let scanned = self.scan_pop_bottom();
384+
self.size[scanned] = SIZE_INFINITY;
401385
}
402386
self.advance_left()?;
403387
if self.left != self.right {
@@ -408,43 +392,21 @@ impl<'a> Printer<'a> {
408392
}
409393
pub fn scan_push(&mut self, x: usize) {
410394
debug!("scan_push {}", x);
411-
if self.scan_stack_empty {
412-
self.scan_stack_empty = false;
413-
} else {
414-
self.top += 1;
415-
self.top %= self.buf_len;
416-
assert!((self.top != self.bottom));
417-
}
418-
self.scan_stack[self.top] = x;
395+
self.scan_stack.push_front(x);
419396
}
420397
pub fn scan_pop(&mut self) -> usize {
421-
assert!((!self.scan_stack_empty));
422-
let x = self.scan_stack[self.top];
423-
if self.top == self.bottom {
424-
self.scan_stack_empty = true;
425-
} else {
426-
self.top += self.buf_len - 1; self.top %= self.buf_len;
427-
}
428-
return x;
398+
self.scan_stack.pop_front().unwrap()
429399
}
430400
pub fn scan_top(&mut self) -> usize {
431-
assert!((!self.scan_stack_empty));
432-
return self.scan_stack[self.top];
401+
*self.scan_stack.front().unwrap()
433402
}
434403
pub fn scan_pop_bottom(&mut self) -> usize {
435-
assert!((!self.scan_stack_empty));
436-
let x = self.scan_stack[self.bottom];
437-
if self.top == self.bottom {
438-
self.scan_stack_empty = true;
439-
} else {
440-
self.bottom += 1; self.bottom %= self.buf_len;
441-
}
442-
return x;
404+
self.scan_stack.pop_back().unwrap()
443405
}
444406
pub fn advance_right(&mut self) {
445407
self.right += 1;
446408
self.right %= self.buf_len;
447-
assert!((self.right != self.left));
409+
assert!(self.right != self.left);
448410
}
449411
pub fn advance_left(&mut self) -> io::Result<()> {
450412
debug!("advance_left Vec<{},{}>, sizeof({})={}", self.left, self.right,
@@ -481,7 +443,7 @@ impl<'a> Printer<'a> {
481443
Ok(())
482444
}
483445
pub fn check_stack(&mut self, k: isize) {
484-
if !self.scan_stack_empty {
446+
if !self.scan_stack.is_empty() {
485447
let x = self.scan_top();
486448
match self.token[x] {
487449
Token::Begin(_) => {
@@ -512,19 +474,16 @@ impl<'a> Printer<'a> {
512474
let ret = write!(self.out, "\n");
513475
self.pending_indentation = 0;
514476
self.indent(amount);
515-
return ret;
477+
ret
516478
}
517479
pub fn indent(&mut self, amount: isize) {
518480
debug!("INDENT {}", amount);
519481
self.pending_indentation += amount;
520482
}
521483
pub fn get_top(&mut self) -> PrintStackElem {
522-
let print_stack = &mut self.print_stack;
523-
let n = print_stack.len();
524-
if n != 0 {
525-
(*print_stack)[n - 1]
526-
} else {
527-
PrintStackElem {
484+
match self.print_stack.last() {
485+
Some(el) => *el,
486+
None => PrintStackElem {
528487
offset: 0,
529488
pbreak: PrintStackBreak::Broken(Breaks::Inconsistent)
530489
}
@@ -538,7 +497,7 @@ impl<'a> Printer<'a> {
538497
write!(self.out, "{}", s)
539498
}
540499
pub fn print(&mut self, token: Token, l: isize) -> io::Result<()> {
541-
debug!("print {} {} (remaining line space={})", tok_str(&token), l,
500+
debug!("print {} {} (remaining line space={})", token, l,
542501
self.space);
543502
debug!("{}", buf_str(&self.token,
544503
&self.size,
@@ -566,7 +525,7 @@ impl<'a> Printer<'a> {
566525
Token::End => {
567526
debug!("print End -> pop End");
568527
let print_stack = &mut self.print_stack;
569-
assert!((!print_stack.is_empty()));
528+
assert!(!print_stack.is_empty());
570529
print_stack.pop().unwrap();
571530
Ok(())
572531
}
@@ -603,12 +562,12 @@ impl<'a> Printer<'a> {
603562
}
604563
}
605564
}
606-
Token::String(s, len) => {
565+
Token::String(ref s, len) => {
607566
debug!("print String({})", s);
608567
assert_eq!(l, len);
609568
// assert!(l <= space);
610569
self.space -= len;
611-
self.print_str(&s[..])
570+
self.print_str(s)
612571
}
613572
Token::Eof => {
614573
// Eof should never get here.
@@ -652,15 +611,15 @@ pub fn eof(p: &mut Printer) -> io::Result<()> {
652611
}
653612

654613
pub fn word(p: &mut Printer, wrd: &str) -> io::Result<()> {
655-
p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as isize))
614+
p.pretty_print(Token::String(wrd.to_string(), wrd.len() as isize))
656615
}
657616

658617
pub fn huge_word(p: &mut Printer, wrd: &str) -> io::Result<()> {
659-
p.pretty_print(Token::String(/* bad */ wrd.to_string(), SIZE_INFINITY))
618+
p.pretty_print(Token::String(wrd.to_string(), SIZE_INFINITY))
660619
}
661620

662621
pub fn zero_word(p: &mut Printer, wrd: &str) -> io::Result<()> {
663-
p.pretty_print(Token::String(/* bad */ wrd.to_string(), 0))
622+
p.pretty_print(Token::String(wrd.to_string(), 0))
664623
}
665624

666625
pub fn spaces(p: &mut Printer, n: usize) -> io::Result<()> {

0 commit comments

Comments
 (0)