Clojure.spec custom generator for Java objects

I just saw one of the "Rich Negotiations" on clojure.spec and really want to try it on my project. I am writing a series of tools for parsing C code using the eclipse CDT library , and I would like to indicate that my functions receive and emit AST Objects.

I think a very simple specification can be written for a function that takes the AST root and emits all the leaves of the tree as follows:

(import '(org.eclipse.cdt.core.dom.ast IASTNode))
(require '[clojure.spec :as s])

(defn ast-node? [node] (instance? IASTNode node))
(s/def ::ast-node ast-node?)
(s/fdef leaves :args ::ast-node :ret (s/coll-of ::ast-node))

However, when I try to implement the code (s/exercise leaves), I get an error message:

Unable to construct gen at: [] for:  
xxx.x$leaves@xxx  
#:clojure.spec{:path [], :form #function[xxx.xxx/leaves], :failure :no-gen}

How can I write my own generator for Java objects for a complete specification and implementation of my code?

+4
2

, s/with-gen. , node, . node, s/or, , , s/multi-spec ( ).

, Java, :

(s/def ::date 
  (s/with-gen #(instance? java.util.Date %)
    (fn [] (gen/fmap #(java.util.Date. %) (s/gen pos-int?)))))

fmap , . Java , , , (s/gen (s/tuple int? string? int?)).

+7

, Alex "LiteralExpression" AST node:

(ns atom-finder.ast-spec
  (:import [org.eclipse.cdt.internal.core.dom.parser.cpp CPPASTLiteralExpression])
  (:require [clojure.spec :as s]
            [clojure.spec.gen :as gen]))

(def gen-literal-expression-args
 (gen/one-of
  [
   (gen/tuple (s/gen #{CPPASTLiteralExpression/lk_char_constant})
              (gen/char-ascii))
   (gen/tuple (s/gen #{CPPASTLiteralExpression/lk_float_constant})
              (gen/double))
   (gen/tuple (s/gen #{CPPASTLiteralExpression/lk_integer_constant})
              (s/gen (s/int-in -2147483648 2147483647)))
   (gen/tuple (s/gen #{CPPASTLiteralExpression/lk_string_literal})
              (gen/string))]))

(def gen-literal-expression
  (gen/fmap
   (fn [[type val]]
     (CPPASTLiteralExpression. type (.toCharArray (str val))))
   gen-literal-expression-args))

(s/def ::literal-expression
  (s/with-gen
    (partial instance? CPPASTLiteralExpression)
    (fn [] gen-literal-expression)))

(s/exercise :atom-finder.ast-spec/literal-expression 10
0

Source: https://habr.com/ru/post/1663907/


All Articles