~singpolyma/dhall-ruby

7274a86b64cd761f0c0c3d0bddb790f2d5aba1fc — Stephen Paul Weber 3 years ago d79e79e
Add Dhall.load
2 files changed, 65 insertions(+), 0 deletions(-)

M lib/dhall.rb
A test/test_load.rb
M lib/dhall.rb => lib/dhall.rb +8 -0
@@ 1,6 1,14 @@
# frozen_string_literal: true

module Dhall
	def self.load(source, resolver: Resolvers::Default.new)
		Promise.resolve(nil).then {
			load_raw(source).resolve(resolver: resolver)
		}.then do |resolved|
			TypeChecker.for(resolved).annotate(TypeChecker::Context.new).normalize
		end
	end

	def self.load_raw(source)
		begin
			return from_binary(source) if source.encoding == Encoding::BINARY

A test/test_load.rb => test/test_load.rb +57 -0
@@ 0,0 1,57 @@
# frozen_string_literal: true

require "minitest/autorun"

require "dhall"

class TestLoad < Minitest::Test
	def test_load_natural_source
		assert_equal Dhall::Natural.new(value: 1), Dhall.load("1").sync
	end

	def test_load_natural_source_mislabeled_encoding
		assert_equal Dhall::Natural.new(value: 1), Dhall.load("1".b).sync
	end

	def test_load_natural_binary
		assert_equal(
			Dhall::Natural.new(value: 1),
			Dhall.load("\x82\x0f\x01".b).sync
		)
	end

	def test_load_normalizes
		assert_equal(
			Dhall::Natural.new(value: 2),
			Dhall.load("1 + 1").sync
		)
	end

	def test_load_resolves
		assert_equal(
			Dhall::Natural.new(value: 2),
			Dhall.load(
				"/path/to/source.dhall",
				resolver: Dhall::Resolvers::Default.new(
					path_reader: ->(s) { s.map { "1 + 1" } }
				)
			).sync
		)
	end

	def test_load_typechecks
		assert_raises TypeError do
			Dhall.load("1 + \"hai\"").sync
		end
	end

	def test_load_raw_not_normalizes_or_typechecks
		assert_equal(
			Dhall::Operator::Plus.new(
				lhs: Dhall::Natural.new(value: 1),
				rhs: Dhall::Text.new(value: "hai")
			),
			Dhall.load_raw("1 + \"hai\"")
		)
	end
end