Skip to content

Commit

Permalink
emitter - ensure_padding_newlines
Browse files Browse the repository at this point in the history
Change function to do nothing if called with a empty buffer.
Essentially, padding should only be used as a way of creating
space between two paragraphs/lines.
  • Loading branch information
jwdevantier committed Jul 22, 2022
1 parent 6980a90 commit fb4b8c1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
16 changes: 11 additions & 5 deletions gcgen/emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,16 +155,22 @@ def lines(self) -> Iterator[str]:
for elem in self._buf:
yield str(elem)

def ensure_newlines(self, n: int):
"""Ensure (at least) `n` empty lines."""
def ensure_padding_lines(self, nlines: int):
"""Ensure (at least) `n` empty lines of padding between two sections
NOTE: if the buffer is empty, this call is a NO-OP.
"""
# if empty, n newlines suffice
# if some line BEFORE, then n+1 newlines needed
buf_end = self._buf[-(n + 1):]
if not self._buf:
return

buf_end = self._buf[-(nlines + 1) :]
buf_end.reverse()
num_newlines = 0
for e in buf_end:
if e != "\n":
n += 1
nlines += 1
break
num_newlines += 1
self._buf.extend("\n" for _ in range(0, n - num_newlines))
self._buf.extend("\n" for _ in range(0, nlines - num_newlines))
11 changes: 7 additions & 4 deletions tests/test_emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,19 +108,22 @@ def test_dedent_guard():


@pytest.mark.parametrize("n", [0, 1, 2, 3, 4])
def test_newlines(n):
def test_newlines_empty_is_noop(n):
"""
When calling with an empty buffer, do not add any newlines.
"""
e = Emitter("")
assert e._buf[-n:] == []
e.ensure_newlines(n)
assert e._buf[-n:] == ["\n" for _ in range(0, n)]
e.ensure_padding_lines(n)
assert e._buf[-n:] == []


@pytest.mark.parametrize("n", [0, 1, 2, 3, 4])
def test_newlines2(n):
e = Emitter("")
assert e._buf[-n:] == []
e.emitln("hello, world")
e.ensure_newlines(n)
e.ensure_padding_lines(n)
# Note that an additional "\n" (newline) entry is tolerated
# this is the element which terminates the preceding line.
expected = ["hello, world", "\n"]
Expand Down

0 comments on commit fb4b8c1

Please sign in to comment.