-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstream.el
385 lines (324 loc) · 12.7 KB
/
stream.el
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
;;; stream.el --- Implementation of streams -*- lexical-binding: t -*-
;; Copyright (C) 2016 Free Software Foundation, Inc.
;; Author: Nicolas Petton <nicolas@petton.fr>
;; Keywords: stream, laziness, sequences
;; Version: 2.2.0
;; Package-Requires: ((emacs "25"))
;; Package: stream
;; Maintainer: nicolas@petton.fr
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This library provides an implementation of streams. Streams are
;; implemented as delayed evaluation of cons cells.
;;
;; Functions defined in `seq.el' can also take a stream as input.
;;
;; streams could be created from any sequential input data:
;; - sequences, making operation on them lazy
;; - a set of 2 forms (first and rest), making it easy to represent infinite sequences
;; - buffers (by character)
;; - buffers (by line)
;; - buffers (by page)
;; - IO streams
;; - orgmode table cells
;; - ...
;;
;; All functions are prefixed with "stream-".
;; All functions are tested in test/automated/stream-tests.el
;;
;; Here is an example implementation of the Fibonacci numbers
;; implemented as in infinite stream:
;;
;; (defun fib (a b)
;; (stream-cons a (fib b (+ a b))))
;; (fib 0 1)
;;; Code:
(eval-when-compile (require 'cl-lib))
(require 'seq)
(require 'thunk)
(eval-and-compile
(defconst stream--identifier '--stream--
"Symbol internally used to identify streams."))
(defmacro stream-make (&rest body)
"Return a stream built from BODY.
BODY must return nil or a cons cell whose cdr is itself a
stream."
(declare (debug t))
`(list ',stream--identifier (thunk-delay ,@body)))
(defmacro stream-cons (first rest)
"Return a stream built from the cons of FIRST and REST.
FIRST and REST are forms and REST must return a stream."
(declare (debug t))
`(stream-make (cons ,first ,rest)))
;;; Convenient functions for creating streams
(cl-defgeneric stream (src)
"Return a new stream from SRC.")
(cl-defmethod stream ((seq sequence))
"Return a stream built from the sequence SEQ.
SEQ can be a list, vector or string."
(if (seq-empty-p seq)
(stream-empty)
(stream-cons
(seq-elt seq 0)
(stream (seq-subseq seq 1)))))
(cl-defmethod stream ((list list))
"Return a stream built from the list LIST."
(if (null list)
(stream-empty)
(stream-cons
(car list)
(stream (cdr list)))))
(cl-defmethod stream ((buffer buffer) &optional pos)
"Return a stream of the characters of the buffer BUFFER.
BUFFER may be a buffer or a string (buffer name).
The sequence starts at POS if non-nil, 1 otherwise."
(with-current-buffer buffer
(unless pos (setq pos (point-min)))
(if (>= pos (point-max))
(stream-empty))
(stream-cons
(with-current-buffer buffer
(save-excursion
(save-restriction
(widen)
(goto-char pos)
(char-after (point)))))
(stream buffer (1+ pos)))))
(declare-function iter-next "generator")
(defun stream-from-iterator (iterator)
"Return a stream generating new elements through ITERATOR.
ITERATOR is an iterator object in terms of the \"generator\"
package."
(stream-make
(condition-case nil
(cons (iter-next iterator) (stream-from-iterator iterator))
(iter-end-of-sequence nil))))
(defun stream-regexp (buffer regexp)
(stream-make
(let (match)
(with-current-buffer buffer
(setq match (re-search-forward regexp nil t)))
(when match
(cons (match-data) (stream-regexp buffer regexp))))))
(defun stream-range (&optional start end step)
"Return a stream of the integers from START to END, stepping by STEP.
If START is nil, it defaults to 0. If STEP is nil, it defaults to
1. START is inclusive and END is exclusive. If END is nil, the
range is infinite."
(unless start (setq start 0))
(unless step (setq step 1))
(if (equal start end)
(stream-empty)
(stream-cons
start
(stream-range (+ start step) end step))))
(defun streamp (stream)
"Return non-nil if STREAM is a stream, nil otherwise."
(and (consp stream)
(eq (car stream) stream--identifier)))
(defun stream-empty ()
"Return a new empty stream."
(list stream--identifier (thunk-delay nil)))
(defun stream-empty-p (stream)
"Return non-nil is STREAM is empty, nil otherwise."
(null (thunk-force (cadr stream))))
(defun stream-first (stream)
"Return the first element of STREAM."
(car (thunk-force (cadr stream))))
(defun stream-rest (stream)
"Return a stream of all but the first element of STREAM."
(or (cdr (thunk-force (cadr stream)))
(stream-empty)))
(defun stream-append (&rest streams)
"Concatenate the STREAMS.
Requesting elements from the resulting stream will request the
elements in the STREAMS in order."
(if (null streams)
(stream-empty)
(stream-make
(let ((first (pop streams)))
(while (and (stream-empty-p first) streams)
(setq first (pop streams)))
(if (stream-empty-p first)
nil
(cons (stream-first first)
(if streams (apply #'stream-append (stream-rest first) streams)
(stream-rest first))))))))
(defmacro stream-pop (stream)
"Return the first element of STREAM and set the value of STREAM to its rest."
(unless (symbolp stream)
(error "STREAM must be a symbol"))
`(prog1
(stream-first ,stream)
(setq ,stream (stream-rest ,stream))))
;;; cl-generic support for streams
(cl-generic-define-generalizer stream--generalizer
11
(lambda (name)
`(when (streamp ,name)
'stream))
(lambda (tag)
(when (eq tag 'stream)
'(stream))))
(cl-defmethod cl-generic-generalizers ((_specializer (eql stream)))
"Support for `stream' specializers."
(list stream--generalizer))
;;; Implementation of seq.el generic functions
(cl-defmethod seqp ((_stream stream))
t)
(cl-defmethod seq-elt ((stream stream) n)
"Return the element of STREAM at index N."
(while (> n 0)
(setq stream (stream-rest stream))
(setq n (1- n)))
(stream-first stream))
(cl-defmethod seq-length ((stream stream))
"Return the length of STREAM.
This function will eagerly consume the entire stream."
(let ((len 0))
(while (not (stream-empty-p stream))
(setq len (1+ len))
(setq stream (stream-rest stream)))
len))
(cl-defmethod seq-subseq ((stream stream) start end)
(seq-take (seq-drop stream start) (- end start)))
(cl-defmethod seq-into-sequence ((stream stream))
"Convert STREAM into a sequence."
(let ((list))
(seq-doseq (elt stream)
(push elt list))
(nreverse list)))
(cl-defmethod seq-into ((stream stream) type)
"Convert STREAM into a sequence of type TYPE."
(seq-into (seq-into-sequence stream) type))
(cl-defmethod seq-into ((stream stream) (_type (eql stream)))
stream)
(cl-defmethod seq-into ((seq sequence) (_type (eql stream)))
(stream seq))
(cl-defmethod seq-take ((stream stream) n)
"Return a stream of the first N elements of STREAM."
(if (or (zerop n)
(stream-empty-p stream))
(stream-empty)
(stream-cons
(stream-first stream)
(seq-take (stream-rest stream) (1- n)))))
(cl-defmethod seq-drop ((stream stream) n)
"Return a stream of STREAM without its first N elements."
(stream-make
(while (not (or (stream-empty-p stream) (zerop n)))
(setq n (1- n))
(setq stream (stream-rest stream)))
(unless (stream-empty-p stream)
(cons (stream-first stream)
(stream-rest stream)))))
(cl-defmethod seq-take-while (pred (stream stream))
"Return a stream of the successive elements for which (PRED elt) is non-nil in STREAM."
(stream-make
(when (funcall pred (stream-first stream))
(cons (stream-first stream)
(seq-take-while pred (stream-rest stream))))))
(cl-defmethod seq-drop-while (pred (stream stream))
"Return a stream from the first element for which (PRED elt) is nil in STREAM."
(stream-make
(while (not (or (stream-empty-p stream)
(funcall pred (stream-first stream))))
(setq stream (stream-rest stream)))
(unless (stream-empty-p stream)
(cons (stream-first stream)
(stream-rest stream)))))
(cl-defmethod seq-map (function (stream stream))
"Return a stream representing the mapping of FUNCTION over STREAM.
The elements of the produced stream are the results of the
applications of FUNCTION on each element of STREAM in succession."
(stream-make
(when (not (stream-empty-p stream))
(cons (funcall function (stream-first stream))
(seq-map function (stream-rest stream))))))
(cl-defmethod seq-do (function (stream stream))
"Evaluate FUNCTION for each element of STREAM eagerly, and return nil.
`seq-do' should never be used on infinite streams without some
kind of nonlocal exit."
(while (not (stream-empty-p stream))
(funcall function (stream-first stream))
(setq stream (stream-rest stream))))
(cl-defmethod seq-filter (pred (stream stream))
"Return a stream of the elements for which (PRED element) is non-nil in STREAM."
(if (stream-empty-p stream)
stream
(stream-make
(while (not (or (stream-empty-p stream)
(funcall pred (stream-first stream))))
(setq stream (stream-rest stream)))
(if (stream-empty-p stream)
nil
(cons (stream-first stream)
(seq-filter pred (stream-rest stream)))))))
(defmacro stream-delay (expr)
"Return a new stream to be obtained by evaluating EXPR.
EXPR will be evaluated once when an element of the resulting
stream is requested for the first time, and must return a stream.
EXPR will be evaluated in the lexical environment present when
calling this function."
(let ((stream (make-symbol "stream")))
`(stream-make (let ((,stream ,expr))
(if (stream-empty-p ,stream)
nil
(cons (stream-first ,stream)
(stream-rest ,stream)))))))
(cl-defmethod seq-copy ((stream stream))
"Return a shallow copy of STREAM."
(stream-delay stream))
(defun stream-of-directory-files-1 (directory &optional nosort recurse follow-links)
"Helper for `stream-of-directory-files'."
(stream-delay
(if (file-accessible-directory-p directory)
(let (files dirs (reverse-fun (if nosort #'identity #'nreverse)))
(dolist (file (directory-files directory t nil nosort))
(let ((is-dir (file-directory-p file)))
(unless (and is-dir
(member (file-name-nondirectory (directory-file-name file))
'("." "..")))
(push file files)
(when (and is-dir
(or follow-links (not (file-symlink-p file)))
(if (functionp recurse) (funcall recurse file) recurse))
(push file dirs)))))
(apply #'stream-append
(stream (funcall reverse-fun files))
(mapcar
(lambda (dir) (stream-of-directory-files-1 dir nosort recurse follow-links))
(funcall reverse-fun dirs))))
(stream-empty))))
(defun stream-of-directory-files (directory &optional full nosort recurse follow-links filter)
"Return a stream of names of files in DIRECTORY.
Call `directory-files' to list file names in DIRECTORY and make
the result a stream. Don't include files named \".\" or \"..\".
The arguments FULL and NOSORT are directly passed to
`directory-files'.
Third optional argument RECURSE non-nil means recurse on
subdirectories. If RECURSE is a function, it should be a
predicate accepting one argument, an absolute file name of a
directory, and return non-nil when the returned stream should
recurse into that directory. Any other non-nil value means
recurse into every readable subdirectory.
Even with recurse non-nil, don't descent into directories by
following symlinks unless FOLLOW-LINKS is non-nil.
If FILTER is non-nil, it should be a predicate accepting one
argument, an absolute file name. It is used to limit the
resulting stream to the files fulfilling this predicate."
(let* ((stream (stream-of-directory-files-1 directory nosort recurse follow-links))
(filtered-stream (if filter (seq-filter filter stream) stream)))
(if full filtered-stream
(seq-map (lambda (file) (file-relative-name file directory)) filtered-stream))))
(provide 'stream)
;;; stream.el ends here