ocaml-community / cppo

C-style preprocessor for OCaml
BSD 3-Clause "New" or "Revised" License
104 stars 26 forks source link

Feature request: `ALLUPPERCASE` #75

Open stefan-kral opened 3 years ago

stefan-kral commented 3 years ago

I want to use cppo for improving my ISO/IEC 13211-1:1995 (a.k.a "ISO-Prolog") compliant Prolog processor.

Specifically, I want to reduce the use of string constants in code blocks like the following one:

type plOpSpecifier = (* pre-fix *) FX|FY | (* in-fix *) XFX|XFY|YFX | (* post-fix *) XF|YF;;

let plOpSpecifier_of_string_opt = function
  |  "fx" -> Some  FX
  |  "fy" -> Some  FY
  | "xfx" -> Some XFX
  | "xfy" -> Some XFY
  | "yfx" -> Some YFX
  | "xf"  -> Some XF
  | "yf"  -> Some YF
  | _____ -> None;;

let plAtom_of_plOpSpecifier = function
  |  FX -> `Atom "fx"
  |  FY -> `Atom "fy"
  | XFX -> `Atom "xfx"
  | XFY -> `Atom "xfy"
  | YFX -> `Atom "yfx"
  | XF  -> `Atom "xf"
  | YF  -> `Atom "yf";;

So far, I have come up with the following:

#define X(x)  STRINGIFY(x) -> Some(CAPITALIZE(x))
  let plOpSpecifier_of_string_opt = function
    | X(fx) | X(fy) | X(xfx) | X(xfy) | X(yfx) | X(xf) | X(yf)
    | _ -> None;;
#undef X

#define X(x)  CAPITALIZE(x) -> `Atom(STRINGIFY(x))
  let plAtom_of_plOpSpecifier = function
    | X(fx) | X(fy) | X(xfx) | X(xfy) | X(yfx) | X(xf) | X(yf);;
#undef X

Alas, CAPITALIZE only touches the first character, so I get the following not-yet-perfect output:

$ cat sample.txt | cppo | ocamlformat --enable-outside-detected-project - --impl
let plOpSpecifier_of_string_opt = function
  | "fx" -> Some Fx
  | "fy" -> Some Fy
  | "xfx" -> Some Xfx
  | "xfy" -> Some Xfy
  | "yfx" -> Some Yfx
  | "xf" -> Some Xf
  | "yf" -> Some Yf
  | _ -> None

let plAtom_of_plOpSpecifier = function
  | Fx -> `Atom "fx"
  | Fy -> `Atom "fy"
  | Xfx -> `Atom "xfx"
  | Xfy -> `Atom "xfy"
  | Yfx -> `Atom "yfx"
  | Xf -> `Atom "xf"
  | Yf -> `Atom "yf"

I need all characters in uppercase. Having a ALLUPPERCASE builtin function in cppo would do it.

I wanted to start the discussion on this before filing a PR:) Comments?

pmetzger commented 3 years ago

Although such tricks certainly make it harder to make mistakes when writing code, I would suggest that a PPX is probably a better mechanism here than hacking in cppo. In particular, code refactoring tools and formaters are broken by preprocessors like cppo.