~singpolyma/dhall-ruby

d5231cf7ad1ff8324d52204e875078834e3cafdb — Stephen Paul Weber 3 years ago 5d49b50
Improve the multiline algorithm

Require that the whitespace being stripped is a common prefix.
2 files changed, 10 insertions(+), 5 deletions(-)

M lib/dhall/parser.rb
M lib/dhall/util.rb
M lib/dhall/parser.rb => lib/dhall/parser.rb +6 -5
@@ 276,14 276,15 @@ module Dhall
		module SingleQuoteLiteral
			def value
				chunks = capture(:single_quote_continue).value
				raw = chunks.join + "\n"
				indent = raw.scan(/^[ \t]*(?=[^ \t\r\n])/).map(&:length).min
				indent = 0 if raw.end_with?("\n\n")
				raw = chunks.join
				indent = raw.scan(/^[ \t]*(?=[^ \t\r\n])/).map(&:chars)
				            .reduce(&Util.method(:longest_common_prefix)).length
				indent = 0 if raw.end_with?("\n")

				TextLiteral.for(
					*chunks
					.chunk { |c| c != "\n" }
					.flat_map { |(line, chunk)| line ? chunk[indent..-1] : chunk }
						.chunk { |c| c != "\n" }
						.flat_map { |(line, chunk)| line ? chunk[indent..-1] : chunk }
				)
			end
		end

M lib/dhall/util.rb => lib/dhall/util.rb +4 -0
@@ 177,5 177,9 @@ module Dhall
				str.encode(Encoding::UTF_8)
			end
		end

		def self.longest_common_prefix(a, b)
			a.zip(b).take_while { |(x, y)| x == y }.map(&:first)
		end
	end
end