@@ -213,9 +213,12 @@ def pretty_print(q)
213
213
# constantly check where the line ends to avoid accidentally printing some
214
214
# content after a line suffix node.
215
215
class LineSuffix
216
- attr_reader :contents
216
+ DEFAULT_PRIORITY = 1
217
217
218
- def initialize ( contents : [ ] )
218
+ attr_reader :priority , :contents
219
+
220
+ def initialize ( priority : DEFAULT_PRIORITY , contents : [ ] )
221
+ @priority = priority
219
222
@contents = contents
220
223
end
221
224
@@ -741,10 +744,17 @@ def flush
741
744
742
745
# This is a separate command stack that includes the same kind of triplets
743
746
# as the commands variable. It is used to keep track of things that should
744
- # go at the end of printed lines once the other doc nodes are
745
- # accounted for. Typically this is used to implement comments.
747
+ # go at the end of printed lines once the other doc nodes are accounted for.
748
+ # Typically this is used to implement comments.
746
749
line_suffixes = [ ]
747
750
751
+ # This is a special sort used to order the line suffixes by both the
752
+ # priority set on the line suffix and the index it was in the original
753
+ # array.
754
+ line_suffix_sort = -> ( line_suffix ) {
755
+ [ -line_suffix . last , -line_suffixes . index ( line_suffix ) ]
756
+ }
757
+
748
758
# This is a linear stack instead of a mutually recursive call defined on
749
759
# the individual doc nodes for efficiency.
750
760
while commands . any?
@@ -783,7 +793,7 @@ def flush
783
793
commands << [ indent , mode , doc . flat_contents ] if doc . flat_contents
784
794
end
785
795
when LineSuffix
786
- line_suffixes << [ indent , mode , doc . contents ]
796
+ line_suffixes << [ indent , mode , doc . contents , doc . priority ]
787
797
when Breakable
788
798
if mode == MODE_FLAT
789
799
if doc . force?
@@ -804,7 +814,7 @@ def flush
804
814
# to flush them now, as we are about to add a newline.
805
815
if line_suffixes . any?
806
816
commands << [ indent , mode , doc ]
807
- commands += line_suffixes . reverse
817
+ commands += line_suffixes . sort_by ( & line_suffix_sort )
808
818
line_suffixes = [ ]
809
819
next
810
820
end
@@ -838,7 +848,7 @@ def flush
838
848
end
839
849
840
850
if commands . empty? && line_suffixes . any?
841
- commands += line_suffixes . reverse
851
+ commands += line_suffixes . sort_by ( & line_suffix_sort )
842
852
line_suffixes = [ ]
843
853
end
844
854
end
@@ -1012,8 +1022,8 @@ def indent
1012
1022
1013
1023
# Inserts a LineSuffix node into the print tree. The contents of the node are
1014
1024
# determined by the block.
1015
- def line_suffix
1016
- doc = LineSuffix . new
1025
+ def line_suffix ( priority : LineSuffix :: DEFAULT_PRIORITY )
1026
+ doc = LineSuffix . new ( priority : priority )
1017
1027
target << doc
1018
1028
1019
1029
with_target ( doc . contents ) { yield }
0 commit comments