Use constant in attribute

Hello, I am building a Restful API, so I need to validate some data. I used validate package, but I thinks that’s irrelevant.

I have a “schema” with attributes that validate the data, which perfectly works:

type login = {
    username : string;  [@regex  "^[a-zA-Z0-9]{4,16}$"]
    ...
} [@@deriving yojson, validate]

I’d like to move all my regex string costants in a separate file, to reuse them in various schema (username is both in login and register requests, so in both schemas):

(* regex.ml file *)
let username = "^[a-zA-Z0-9]{4,16}$"

(* login.ml file *)
  type login = {
    username : string; [@regex  Regex.username]
    ...
  } [@@deriving yojson, validate]

That doesn’t work: Error: constant expected. My basic understanding is that attributes must have an “hardcoded” value. Is there any way to make this work?

The value must be usable by the PPX which is a purely syntactic transformer, so references to identifiers are out of this scope because that would require typechecking, as well as some module-aware smart code to extract the actual string literal, when that’s even possible.

To do what you want, it seems you need a preceding preprocessing step to insert the string, either using another PPX, or some kind of macro system like M4. Intuitively, I would strongly go with a PPX, although even that seems a bit overkill/brittle.

1 Like