Split out passes 0 and 1 to generic parser.

This commit is contained in:
Dominik Pantůček 2023-04-09 10:23:27 +02:00
parent 7fa9e6901c
commit 3c9f860fc6
2 changed files with 37 additions and 36 deletions

View file

@ -29,6 +29,7 @@
util-parser
(
parser-preprocess-line
parser-parse-line
parser-tests!
)
@ -46,6 +47,23 @@
"")
""))
;; Pass 1: Expects line with comments and surrounding whitespace
;; removed, returns either #f if nothing was parsed, symbol if only
;; one token was there and pair of symbol and string if both key and
;; the value were present.
(define (parser-parse-line line)
(if (= (string-length line) 0)
#f
(let ((dm (irregex-search (irregex "[ \\t]" 'u) line)))
(if dm
(let* ((sep-idx (irregex-match-start-index dm))
(key-str (substring line 0 sep-idx))
(key (string->symbol key-str))
(sep+val (substring line sep-idx))
(val (irregex-replace (irregex "^[ \\t]*" 'u) sep+val "")))
(cons key val))
(string->symbol line)))))
;; Self-tests
(define (parser-tests!)
(run-tests
@ -62,6 +80,23 @@
(test-equal? parser-preprocess-line
(parser-preprocess-line "key value # spaces and comment after spaces")
"key value")
))
(test-false parser-parse-line
(parser-parse-line ""))
(test-eq? parser-parse-line
(parser-parse-line "key")
'key)
(test-equal? parser-parse-line
(parser-parse-line "key value")
'(key . "value"))
(test-equal? parser-parse-line
(parser-parse-line "key value")
'(key . "value"))
(test-equal? parser-parse-line
(parser-parse-line "key value and some")
'(key . "value and some"))
(test-equal? parser-parse-line
(parser-parse-line "key value lot of spaces")
'(key . "value lot of spaces"))
))
)