mirror of
https://github.com/carp-lang/Carp.git
synced 2024-10-12 04:58:18 +03:00
28 lines
1.3 KiB
Plaintext
28 lines
1.3 KiB
Plaintext
(defdynamic fmt-internal [s args]
|
|
(let [idx (String.index-of s \%)
|
|
len (String.count s)]
|
|
(if (= idx -1)
|
|
(if (< 0 (count args))
|
|
(macro-error "error in format string: too many arguments to format string")
|
|
(list 'copy s)) ; no more splits found, just return string
|
|
(if (= \% (String.char-at s (inc idx))) ; this is an escaped %
|
|
(list 'String.append
|
|
@"%"
|
|
(fmt-internal (String.substring s (+ idx 2) len)))
|
|
(if (= 0 (count args)) ; we need to insert something, but have nothing
|
|
(macro-error "error in format string: not enough arguments to format string")
|
|
; okay, this is the meat:
|
|
; get the next % after our escaper
|
|
(let [next (String.index-of (String.substring s (inc idx) len) \%)]
|
|
(if (= -1 next)
|
|
(if (< 1 (count args))
|
|
(macro-error "error in format string: too many arguments to format string")
|
|
(list 'format s (car args)))
|
|
(let [slice (String.substring s 0 (+ (inc idx) next))]
|
|
(list 'String.append (list 'format slice (car args))
|
|
(fmt-internal (String.substring s (+ (inc idx) next) len)
|
|
(cdr args)))))))))))
|
|
|
|
(defmacro fmt [s :rest args]
|
|
(fmt-internal s args))
|