def fast_fitting_predicate(<EOL>page_width,  <EOL>ribbon_frac,  <EOL>min_nesting_level,  <EOL>max_width,<EOL>triplestack<EOL>):
chars_left = max_width<EOL>while chars_left >= <NUM_LIT:0>:<EOL><INDENT>if not triplestack:<EOL><INDENT>return True<EOL><DEDENT>indent, mode, doc = triplestack.pop()<EOL>if doc is NIL:<EOL><INDENT>continue<EOL><DEDENT>elif isinstance(doc, str):<EOL><INDENT>chars_left -= len(doc)<EOL><DEDENT>elif isinstance(doc, Concat):<EOL><INDENT>triplestack.extend(<EOL>(indent, mode, doc)<EOL>for doc in reversed(doc.docs)<EOL>)<EOL><DEDENT>elif isinstance(doc, Annotated):<EOL><INDENT>triplestack.append((indent, mode, doc.doc))<EOL><DEDENT>elif isinstance(doc, Fill):<EOL><INDENT>triplestack.extend(<EOL>(indent, mode, doc)<EOL>for doc in reversed(doc.docs)<EOL>)<EOL><DEDENT>elif isinstance(doc, Nest):<EOL><INDENT>triplestack.append((indent + doc.indent, mode, doc.doc))<EOL><DEDENT>elif isinstance(doc, AlwaysBreak):<EOL><INDENT>return False<EOL>triplestack.append((indent, BREAK_MODE, doc.doc))<EOL><DEDENT>elif doc is HARDLINE:<EOL><INDENT>return True<EOL><DEDENT>elif isinstance(doc, FlatChoice):<EOL><INDENT>if mode is FLAT_MODE:<EOL><INDENT>triplestack.append((indent, mode, doc.when_flat))<EOL><DEDENT>elif mode is BREAK_MODE:<EOL><INDENT>triplestack.append((indent, mode, doc.when_broken))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError<EOL><DEDENT><DEDENT>elif isinstance(doc, Group):<EOL><INDENT>triplestack.append((indent, FLAT_MODE, doc.doc))<EOL><DEDENT>elif isinstance(doc, Contextual):<EOL><INDENT>ribbon_width = max(<NUM_LIT:0>, min(page_width, round(ribbon_frac * page_width)))<EOL>evaluated_doc = doc.fn(<EOL>indent=indent,<EOL>column=max_width - chars_left,<EOL>page_width=page_width,<EOL>ribbon_width=ribbon_width,<EOL>)<EOL>normalized = normalize_doc(evaluated_doc)<EOL>triplestack.append((indent, mode, normalized))<EOL><DEDENT>elif isinstance(doc, SAnnotationPush):<EOL><INDENT>continue<EOL><DEDENT>elif isinstance(doc, SAnnotationPop):<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>raise ValueError((indent, mode, doc))<EOL><DEDENT><DEDENT>return False<EOL>
One element lookahead. Fast, but not the prettiest.