~singpolyma/dhall-ruby

ref: b22689c79cf8e17d52b1b1db5ee470f40c22df46 dhall-ruby/lib/dhall/binary.rb -rw-r--r-- 6.9 KiB
b22689c7Stephen Paul Weber Switch encoding of binary URI format 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# frozen_string_literal: true

require "cbor"
require "digest/sha2"
require "multihashes"

require "dhall/ast"
require "dhall/builtins"
require "dhall/parser"

module Dhall
	def self.from_binary(cbor_binary)
		decode(CBOR.decode(cbor_binary))
	end

	def self.decode(expression)
		BINARY.each do |match, use|
			return use[expression] if expression.is_a?(match)
		end

		raise "Unknown expression: #{expression.inspect}"
	end

	class Expression
		def self.decode(*args)
			return new(value: args.first) if args.length == 1

			new(*args)
		end

		def to_cbor(packer=nil)
			if packer
				packer.write(as_json)
				packer
			else
				CBOR.encode(as_json)
			end
		end

		def to_binary
			CBOR.encode(::CBOR::Tagged.new(55799, self))
		end

		def digest(digest: Digest::SHA2.new(256))
			(digest << normalize.to_cbor).freeze
		end

		def cache_key
			"sha256:#{digest.hexdigest}"
		end
	end

	class Application
		def self.decode(function, *args)
			function = Dhall.decode(function)
			args.map(&Dhall.method(:decode)).reduce(function) do |f, arg|
				self.for(function: f, argument: arg)
			end
		end
	end

	class Function
		def self.decode(var_or_type, type_or_body, body_or_nil=nil)
			type_or_body = Dhall.decode(type_or_body)

			if body_or_nil.nil?
				of_arguments(Dhall.decode(var_or_type), body: type_or_body)
			else
				raise ArgumentError, "explicit var named _" if var_or_type == "_"

				body_or_nil = Dhall.decode(body_or_nil)
				new(var: var_or_type, type: type_or_body, body: body_or_nil)
			end
		end
	end

	class Operator
		def self.decode(opcode, lhs, rhs)
			OPERATORS[opcode].new(
				lhs: Dhall.decode(lhs),
				rhs: Dhall.decode(rhs)
			)
		end
	end

	class List
		def self.decode(type, *els)
			type = type.nil? ? nil : Builtins[:List].call(Dhall.decode(type))
			if els.empty?
				EmptyList.new(type: type)
			else
				List.new(elements: els.map(&Dhall.method(:decode)), type: type)
			end
		end
	end

	class EmptyList
		def self.decode(type)
			EmptyList.new(type: Dhall.decode(type))
		end
	end

	class Optional
		def self.decode(type, value=nil)
			if value.nil?
				OptionalNone.new(value_type: Dhall.decode(type))
			else
				Optional.new(
					value:      Dhall.decode(value),
					value_type: type.nil? ? type : Dhall.decode(type)
				)
			end
		end
	end

	class ToMap
		def self.decode(record, type=nil)
			new(
				record: Dhall.decode(record),
				type:   type.nil? ? nil : Dhall.decode(type)
			)
		end
	end

	class Merge
		def self.decode(record, input, type=nil)
			new(
				record: Dhall.decode(record),
				input:  Dhall.decode(input),
				type:   type.nil? ? nil : Dhall.decode(type)
			)
		end
	end

	class RecordType
		def self.decode(record)
			if record.empty?
				EmptyRecordType.new
			else
				new(record: Hash[record.map { |k, v| [k, Dhall.decode(v)] }])
			end
		end
	end

	class Record
		def self.decode(record)
			if record.empty?
				EmptyRecord.new
			else
				new(record: Hash[record.map { |k, v| [k, Dhall.decode(v)] }])
			end
		end
	end

	class RecordSelection
		def self.decode(record, selector)
			new(record: Dhall.decode(record), selector: selector)
		end
	end

	class RecordProjection
		def self.decode(record, *selectors)
			record = Dhall.decode(record)
			if selectors.length == 1 && selectors[0].is_a?(Array)
				RecordProjectionByExpression.new(
					record:   record,
					selector: Dhall.decode(selectors[0][0])
				)
			else
				self.for(record, selectors)
			end
		end
	end

	class UnionType
		def self.decode(record)
			new(alternatives: Hash[record.map do |k, v|
				[k, v.nil? ? v : Dhall.decode(v)]
			end])
		end
	end

	class Union
		def self.decode(tag, value, alternatives)
			new(
				tag:          tag,
				value:        Dhall.decode(value),
				alternatives: UnionType.decode(alternatives)
			)
		end
	end

	class If
		def self.decode(pred, thn, els)
			new(
				predicate: Dhall.decode(pred),
				then:      Dhall.decode(thn),
				else:      Dhall.decode(els)
			)
		end
	end

	class TextLiteral
		def self.decode(*chunks)
			lead_text, *pairs = chunks
			chunks =
				[Text.new(value: lead_text)] +
				pairs.each_slice(2).flat_map do |(e, t)|
					[Dhall.decode(e), Text.new(value: t)]
				end

			chunks.length == 1 ? chunks.first : TextLiteral.new(chunks: chunks)
		end
	end

	class Assertion
		def self.decode(type)
			new(type: Dhall.decode(type))
		end
	end

	class Import
		class IntegrityCheck
			def self.decode(integrity_check)
				return unless integrity_check

				IntegrityCheck.new(
					Multihashes.decode(integrity_check).select { |k, _|
						[:code, :digest].include?(k)
					}
				)
			end
		end

		class URI
			def self.decode(headers, authority, *path, query)
				uri = ::URI.scheme_list[name.split(/::/).last.upcase].build(
					Parser.parse(authority, root: :authority).value.merge(
						path: "/#{path.join("/")}"
					)
				)
				uri.instance_variable_set(:@query, query)
				new(headers: headers, uri: uri)
			end
		end

		class Path
			def self.decode(*args)
				new(*args)
			end
		end

		class EnvironmentVariable
			def self.decode(*args)
				new(*args)
			end
		end

		class MissingImport
			def self.decode(*args)
				new(*args)
			end
		end

		def self.decode(integrity_check, import_type, path_type, *parts)
			parts[0] = Dhall.decode(parts[0]) if path_type < 2 && !parts[0].nil?
			path_type = PATH_TYPES.fetch(path_type)

			new(
				IntegrityCheck.decode(integrity_check),
				IMPORT_TYPES[import_type],
				path_type.decode(*parts)
			)
		end
	end

	class LetIn
		def self.decode(*parts)
			body = Dhall.decode(parts.pop)
			parts.each_slice(3).map { |(var, type, assign)|
				Let.new(
					var:    var,
					assign: Dhall.decode(assign),
					type:   type.nil? ? nil : Dhall.decode(type)
				)
			}.reverse.reduce(body) do |inside, let|
				LetIn.new(let: let, body: inside)
			end
		end
	end

	class TypeAnnotation
		def self.decode(value, type)
			new(value: Dhall.decode(value), type: Dhall.decode(type))
		end
	end

	def self.handle_tag(e)
		return e unless e.is_a?(::CBOR::Tagged)
		return e.value if e.tag == 55799

		raise "Unknown tag: #{e.inspect}"
	end

	BINARY = {
		::TrueClass    => ->(e) { Bool.new(value: e) },
		::FalseClass   => ->(e) { Bool.new(value: e) },
		::Float        => ->(e) { Double.new(value: e) },
		::String       => ->(e) { Builtins[e.to_sym] || (raise "Unknown builtin") },
		::Integer      => ->(e) { Variable.new(index: e) },
		::Array        => lambda { |e|
			e = e.map(&method(:handle_tag))
			if e.length == 2 && e.first.is_a?(::String)
				Variable.new(name: e[0], index: e[1])
			else
				tag, *body = e
				BINARY_TAGS[tag]&.decode(*body) ||
					(raise "Unknown expression: #{e.inspect}")
			end
		},
		::CBOR::Tagged => ->(e) { Dhall.decode(handle_tag(e)) }
	}.freeze

	BINARY_TAGS = [
		Application,
		Function,
		Forall,
		Operator,
		List,
		Optional,
		Merge,
		RecordType,
		Record,
		RecordSelection,
		RecordProjection,
		UnionType,
		Union,
		nil,
		If,
		Natural,
		Integer,
		nil,
		TextLiteral,
		Assertion,
		nil,
		nil,
		nil,
		nil,
		Import,
		LetIn,
		TypeAnnotation,
		ToMap,
		EmptyList
	].freeze
end