Class DocBuilder


  • public final class DocBuilder
    extends java.lang.Object
    A DocBuilder converts a sequence of Ops into a Doc.
    • Field Detail

      • stack

        private final java.util.ArrayDeque<Doc.Level> stack
      • appendLevel

        private Doc.Level appendLevel
        A possibly earlier Doc.Level for appending text, à la Philip Wadler.

        Processing Docs presents a subtle problem. Suppose we have a Doc for to an assignment node, a = b, with an optional Doc.Break following the =. Suppose we have 5 characters to write it, so that we think we don't need the break. Unfortunately, this Doc lies in an expression statement Doc for the statement a = b; and this statement does not fit in 3 characters. This is why many formatters sometimes emit lines that are too long, or cheat by using a narrower line length to avoid such problems.

        One solution to this problem is not to decide whether a Doc.Level should be broken until later (in this case, after the semicolon has been seen). A simpler approach is to rewrite the Doc as here, so that the semicolon moves inside the inner Doc, and we can decide whether to break that Doc without seeing later text.

    • Constructor Detail

      • DocBuilder

        public DocBuilder()
        Start to build a DocBuilder.
    • Method Detail

      • open

        void open​(Indent plusIndent)
        Open a new Doc.Level.
        Parameters:
        plusIndent - the extra indent for the Doc.Level
      • close

        void close()
        Close the current Doc.Level.
      • add

        void add​(Doc doc)
        Add a Doc to the current Doc.Level.
        Parameters:
        doc - the Doc
      • build

        public Doc build()
        Return the Doc.
        Returns:
        the Doc
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object