Exercise 1: Other Block-Level Tags Also Close an Open
— Possible Solution
====================================================================
THE TESTS
------------------------------
parse_html("
Hello
")
parse_html("Hello
Title
")
RESULTS
------------------------------
<#document>
'Hello'
-
'x'
<#document>
'Hello'
'Title'
Both produce exactly two top-level siblings -- p and ul in the first
case, p and h1 in the second -- not a ul or h1 nested inside the p.
WHY ul AND h1 BOTH TRIGGER THE SAME BEHAVIOR AS div
------------------------------
The check in visit_binary... (no -- in the parser's own opentag
branch) is a single membership test:
if tok.name in P_CLOSING_TAGS and top_tag == 'p':
stack.pop()
P_CLOSING_TAGS is a flat set containing 'div', 'ul', 'h1' (and every
other h1-h6 heading, 'ol', 'table', and the rest) all as equally
ordinary members -- there is nothing structurally special about
'div' in the code itself; it's simply one name among roughly two
dozen that all happen to share the same real-world property:
they're every one of them block-level container or heading elements
that HTML's own specification says are never meant to sit inside a
still-open paragraph. The rule doesn't distinguish "container-like"
tags from "heading-like" tags at all -- it just asks one question,
"is this new tag's name anywhere in the list," and treats every
member of that list identically. That's exactly why adding ul and h1
to the set was enough to make both of them behave the same way div
already did, with no additional code needed beyond the single
membership check that already existed.