vile / scheme / port_text.v
296 lines · 265 sloc · 9.59 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import strings
4
5// OutputFlusher is an optional host Writer capability. A Writer without it has
6// no Vile-owned pending output, so flush-output-port is a successful no-op.
7// Like write, flush must not reenter an operation on the same port.
8pub interface OutputFlusher {
9mut:
10 flush() !
11}
12
13@[heap]
14struct MemoryPortOutput {
15mut:
16 bytes []u8
17 // Negative means append: ordinary writes need no separate cursor update.
18 position int = -1
19 binary bool
20}
21
22fn (mut sink MemoryPortOutput) write(bytes []u8) !int {
23 if sink.position >= 0 { return sink.write_positioned(bytes) }
24 if bytes.len > max_int - 1 - sink.bytes.len {
25 return failure('memory port exceeds supported length')
26 }
27 sink.bytes << bytes
28 return bytes.len
29}
30
31// open_input_string snapshots the host text. Its one owned byte array also
32// serves as the read buffer; no Reader callback or second input copy is needed.
33pub fn (mut vm VM) open_input_string(text string) !Value {
34 return vm.memory_input_port(text.bytes(), false)
35}
36
37fn (mut vm VM) memory_input_port(bytes []u8, binary bool) !Value {
38 vm.ready()!
39 mut port := &InputPort{ owner: vm.owner, read_size: 4096, source: &closed_port, buffer: bytes, ended: true, binary: binary, memory_input: true }
40 unsafe { port.buffer.flags.set(.noslices) }
41 return payload_value(.input_port, port)
42}
43
44pub fn (mut vm VM) open_output_string() !Value {
45 return vm.memory_output_port(false)
46}
47
48fn (mut vm VM) memory_output_port(binary bool) !Value {
49 vm.ready()!
50 mut sink := &MemoryPortOutput{ binary: binary }
51 unsafe { sink.bytes.flags.set(.noslices) }
52 return payload_value(.output_port, &OutputPort{ owner: vm.owner, sink: sink, memory_output: sink, binary: binary })
53}
54
55// get_output_string returns an independent, mutable snapshot, including after
56// close. Later writes and Scheme mutations cannot change an earlier snapshot.
57pub fn (mut vm VM) get_output_string(value Value) !Value {
58 vm.ready()!
59 port := vm.output_owner(value)!
60 if isnil(port.memory_output) || port.binary { return failure('expected a string output port') }
61 if port.busy { return failure('output port operation is already active') }
62 text := port.memory_output.bytes.bytestr()
63 return owned_string(text, unicode_length(text))
64}
65
66pub fn (mut vm VM) read_line(value Value) !Value {
67 vm.ready()!
68 return vm.read_port_text(value, -1)
69}
70
71// append_source_line appends through the next LF, retaining its original bytes.
72// The Scheme reader validates the accumulated source. Return false only at EOF
73// with no bytes appended. REPLs can share this cursor with read and peek-char.
74pub fn (mut vm VM) append_source_line(value Value, mut source strings.Builder) !bool {
75 vm.ready()!
76 mut port := vm.checked_text_input(value)!
77 initial := source.len
78 if !isnil(custom_input_resource(value)) {
79 for {
80 ch := vm.read_char(value)!
81 if ch.tag == .eof { return source.len != initial }
82 source.write_rune(rune(ch.whole()))
83 if ch.whole() == 10 { return true }
84 }
85 return false
86 }
87 port.busy = true
88 defer {
89 port.busy = false
90 port.release_large_frame()
91 }
92 for port.ensure_bytes(1)! {
93 end := input_quote_end(port.buffer, port.position, 10)
94 found := end < port.buffer.len
95 next := if found { end + 1 } else { end }
96 unsafe { source.write_ptr(&u8(port.buffer.data) + port.position, next - port.position) }
97 port.position = next
98 if found { return true }
99 }
100 return source.len != initial
101}
102
103pub fn (mut vm VM) read_string(value Value, count int) !Value {
104 vm.ready()!
105 if count < 0 { return failure('read-string count must be nonnegative') }
106 return vm.read_port_text(value, count)
107}
108
109// Copy each decoded span directly into the result's owned buffer. Input can
110// compact/refill between spans, and Buffer transfers the completed allocation.
111// A count of -1 reads a line; a nonnegative count reads that many characters.
112@[direct_array_access]
113fn (mut vm VM) read_port_text(value Value, count int) !Value {
114 mut port := vm.checked_text_input(value)!
115 if !isnil(custom_input_resource(value)) {
116 operation := if count == -1 {
117 PortIoOperation.read_line
118 } else if count == -2 {
119 PortIoOperation.get_line
120 } else {
121 PortIoOperation.get_text
122 }
123 return vm.custom_text_input_host_operation(operation, value, unspecified(), 0, if count < 0 {
124 max_int
125 } else {
126 count
127 }, unspecified())
128 }
129 port.busy = true
130 defer {
131 port.busy = false
132 port.release_large_frame()
133 }
134 mut out := strings.new_buffer(0)
135 mut length := 0
136 for count < 0 || length < count {
137 ch, width := port.peek_character()!
138 if width == 0 {
139 if length == 0 { return eof_value() }
140 break
141 }
142 if count < 0 && (ch == `\n` || (count == -1 && ch in [`\r`, rune(0x85), rune(0x2028)])) {
143 port.position += width
144 // CRLF and CRNEL are one ending. Inspect only their exact bytes;
145 // malformed input belonging to the next line stays unread.
146 if ch == `\r` && port.ensure_bytes(1)! {
147 if port.buffer[port.position] == `\n` {
148 port.position++
149 } else if port.buffer[port.position] == 0xc2 && port.ensure_bytes(2)! && port.buffer[port.position + 1] == 0x85 {
150 port.position += 2
151 }
152 }
153 break
154 }
155 if width > max_int - 1 - out.len() {
156 return failure('string length exceeds supported range')
157 }
158 unsafe { out.write_ptr(&u8(port.buffer.data) + port.position, width) }
159 port.position += width
160 length++
161 }
162 return owned_string(out.take_string(), length)
163}
164
165pub fn (mut vm VM) flush_output_port(value Value) ! {
166 vm.ready()!
167 mut port := vm.checked_output(value)!
168 if !isnil(custom_output_resource(value)) {
169 vm.custom_output_host_operation(.flush_output, value, unspecified(), 0, 0, unspecified())!
170 return
171 }
172 port.busy = true
173 defer { port.busy = false }
174 if mut port.sink is OutputFlusher {
175 mut sink := port.sink
176 sink.flush()!
177 }
178}
179
180const text_port_native_descriptors = [
181 NativeDescriptor{'port?', NativeFn(port_anyp)}
182 NativeDescriptor{'textual-port?', port_textualp}
183 NativeDescriptor{'binary-port?', port_binaryp}
184 NativeDescriptor{'input-port-open?', port_input_openp}
185 NativeDescriptor{'output-port-open?', port_output_openp}
186 NativeDescriptor{'close-port', port_close}
187 NativeDescriptor{'open-input-string', port_open_input_string}
188 NativeDescriptor{'open-output-string', port_open_output_string}
189 NativeDescriptor{'get-output-string', port_get_output_string}
190 NativeDescriptor{'read-line', port_read_line}
191 NativeDescriptor{'read-string', port_read_string}
192 NativeDescriptor{'write-string', port_write_string}
193 NativeDescriptor{'flush-output-port', port_flush_output}
194 NativeDescriptor{'eof-object', port_eof_object},
195]!
196
197fn (mut vm VM) install_text_port_primitives() {
198 for index in 0 .. text_port_native_descriptors.len {
199 entry := &text_port_native_descriptors[index]
200 vm.bind_global(entry.name, vm.port_native_procedure(entry))
201 }
202}
203
204fn port_anyp(mut _vm VM, args []Value) !Value {
205 check_arity('port predicate', args.len, 1, 1)!
206 return boolean(args[0].tag in [.input_port, .output_port, .input_output_port])
207}
208
209fn port_binaryp(mut _vm VM, args []Value) !Value {
210 check_arity('binary-port?', args.len, 1, 1)!
211 return boolean(is_binary_port(args[0]))
212}
213
214fn is_binary_port(value Value) bool {
215 return match value.tag {
216 .input_port, .input_output_port { value.input_pointer().binary }
217 .output_port { value.output_pointer().binary }
218 else { false }
219 }
220}
221
222fn port_textualp(mut _vm VM, args []Value) !Value {
223 check_arity('textual-port?', args.len, 1, 1)!
224 return boolean(args[0].tag in [.input_port, .output_port, .input_output_port] && !is_binary_port(args[0]))
225}
226
227fn port_input_openp(mut vm VM, args []Value) !Value {
228 check_arity('input-port-open?', args.len, 1, 1)!
229 if args[0].tag == .output_port {
230 vm.output_owner(args[0])!
231 return boolean(false)
232 }
233 return boolean(!vm.input_owner(args[0])!.closed)
234}
235
236fn port_output_openp(mut vm VM, args []Value) !Value {
237 check_arity('output-port-open?', args.len, 1, 1)!
238 if args[0].tag == .input_port {
239 vm.input_owner(args[0])!
240 return boolean(false)
241 }
242 return boolean(!vm.output_owner(args[0])!.closed)
243}
244
245fn port_close(mut vm VM, args []Value) !Value {
246 check_arity('close-port', args.len, 1, 1)!
247 vm.close_port(args[0])!
248 return unspecified()
249}
250
251fn port_open_input_string(mut vm VM, args []Value) !Value {
252 check_arity('open-input-string', args.len, 1, 1)!
253 return vm.open_input_string(string_data(args[0])!)
254}
255
256fn port_open_output_string(mut vm VM, args []Value) !Value {
257 check_arity('open-output-string', args.len, 0, 0)!
258 return vm.open_output_string()
259}
260
261fn port_get_output_string(mut vm VM, args []Value) !Value {
262 check_arity('get-output-string', args.len, 1, 1)!
263 return vm.get_output_string(args[0])
264}
265
266fn port_read_line(mut vm VM, args []Value) !Value {
267 check_arity('read-line', args.len, 0, 1)!
268 return vm.read_port_text(if args.len == 0 { vm.current_input_value()! } else { args[0] }, -1)
269}
270
271fn port_read_string(mut vm VM, args []Value) !Value {
272 check_arity('read-string', args.len, 1, 2)!
273 count := args[0].as_integer()!
274 if count < 0 || count > max_int { return failure('read-string count out of supported range') }
275 return vm.read_port_text(if args.len == 1 { vm.current_input_value()! } else { args[1] }, int(count))
276}
277
278fn port_write_string(mut vm VM, args []Value) !Value {
279 check_arity('write-string', args.len, 1, 4)!
280 text, first, last, _, _ := string_range(args, 0, 2)!
281 target := if args.len == 1 { vm.current_output_value()! } else { args[1] }
282 mut port := vm.checked_text_output(target)!
283 port.write_text(text_view(text.value, first, last))!
284 return unspecified()
285}
286
287fn port_flush_output(mut vm VM, args []Value) !Value {
288 check_arity('flush-output-port', args.len, 0, 1)!
289 vm.flush_output_port(if args.len == 0 { vm.current_output_value()! } else { args[0] })!
290 return unspecified()
291}
292
293fn port_eof_object(mut _vm VM, args []Value) !Value {
294 check_arity('eof-object', args.len, 0, 0)!
295 return eof_value()
296}
297