Skip to content
Masataro Asai edited this page Sep 18, 2021 · 3 revisions

Trivia has several contrib packages that integrates to other libraries.

trivia.ppcre

Provides 3 patterns: ppcre, split and split*.

ppcre pattern

ppcre pattern is a wrapper around ppcre:scan-to-strings.

Syntax
ppcre (regexp &key start end sharedp) &rest subpatterns (long form)

ppcre regexp &rest subpatterns (short form)

(match "abcccdddcd"
  ((ppcre "ab([cd]+)" var)
    var))
;; -> "cccdddcd"

split, split* pattern

split pattern is a wrapper around ppcre:split. split* pattern is a soft-match variant.

Syntax
split regexp &rest subpatterns

split* regexp &rest subpatterns

(match "a b"
  ((split " " var)
    :does-not-match)
  ((split " " var var2 var3)
    :does-not-match)
  ((split " " var var2)
    (list var var2)))
;; -> ("a" "b")

(match "a b"
  ((split* " " var)
    var)
;; -> ("a")

trivia.cffi

-> pattern provides a foreign slot access. null-pointer pattern matches against a null pointer.

Syntax
(-> foreign-struct-type &rest slots)
  • slots := {slot}*
  • slot := slotname | (& slotname) | (slotname subpattern)
  • slotname := symbol
Syntax
(null-pointer)

Example:

(defcstruct bar
  (baz :int))
(defcstruct foo
  (bar (:struct bar)))
#|
this is identical to

  (defcstruct foo
    (bar (:pointer (:struct bar))))

or

  struct foo {
    bar *bar;
  }
|#

(match (foreign-alloc 'foo) ; returns a pointer
  ((-> (:struct foo)
       bar)                           ; foreign-slot-value access (leaf pattern)
   bar))
;; -> a list (BAZ -121372672) returned by cffi:foreign-slot-value.
;; the list is generated by a generic function cffi:translate-from-foreign specialized on (T CFFI::FOREIGN-STRUCT-TYPE).


(match (foreign-alloc 'foo) ; returns a pointer
  ((-> (:struct foo)
       (& bar))                       ; explicit foreign-slot-pointer access
   bar))
;; -> #.(SB-SYS:INT-SAP #X7F8C40000DE0) , a foreign pointer.


(match (foreign-alloc 'foo) ; returns a pointer
  ((-> (:struct foo)
       (bar myval))                       ; implicit foreign-slot-pointer access (nested pattern).
   myval))
;; -> #.(SB-SYS:INT-SAP #X7F8C40000E00) , a foreign pointer.


(match (foreign-alloc 'foo) ; returns a pointer
  ((-> (:struct foo)
       (bar                           ; implicit foreign-slot-pointer access (nested pattern)
        ;; the result is further matched against struct bar
        (-> (:struct bar)
            baz)))                      ; leaf node: value access
   baz))
;; -> 0 , an uninitialized integer.

trivia.quasiquote

Loading this package and using the :fare-quasiquote readtable, you can now write a pattern with a quasiquoted list.

(in-readtable :fare-quasiquote)
;; or better,
(ql:quickload :cl-syntax-quasiquote)
(cl-syntax:use-syntax :fare-quasiquote)

(match (list 1 2)
  (`(,b ,c)
    (assert (= 1 b))
    (assert (= 2 c))))