(* -*- tuareg -*- *)
(* NOTE: prepend jbuild.common to this file! *)

let ( ^/ ) = Filename.concat

let source_dirs =
  (if facebook then "facebook" else "opensource")
  :: ( (if clang then ["clang"; "unit" ^/ "clang"] else ["clang_stubs"; "unit" ^/ "clang_stubs"])
     @ [ (if java then "java" else "java_stubs")
       ; (if python && facebook then "python" else "python_stubs")
       ; "absint"
       ; "backend"
       ; "biabduction"
       ; "bufferoverrun"
       ; "checkers"
       ; "concurrency"
       ; "eradicate"
       ; "integration"
       ; "labs"
       ; "quandary"
       ; "unit" ] )


let infer_binaries =
  ["infer"; "inferunit"] @ if facebook then ["InferCreateTraceViewLinks"] else []


let infer_cflags =
  common_cflags
  @ [ "-open"
    ; "Core"
    ; "-open"
    ; "InferStdlib"
    ; "-open"
    ; "IStd"
    ; "-open"
    ; "InferGenerated"
    ; "-open"
    ; "InferIR"
    ; "-open"
    ; "InferBase" ]


(** The build stanzas to be passed to jbuilder *)
let stanzas =
  ( if clang then
      ["(ocamllex (types_lexer ctl_lexer))"; "(menhir ((modules (types_parser ctl_parser))))"]
  else [] )
  @ ( if python && facebook then ["(ocamllex (pythonLexer))"; "(menhir ((modules (pythonParser))))"]
    else [] )
  @ [ Format.sprintf
        {|
(library
 ((name InferModules)
  (flags (%s))
  (ocamlopt_flags (%s))
  (libraries (%s))
  (modules (:standard \ %s infertop))
  (preprocess (pps (ppx_compare ppx_sexp_conv -no-check)))
 ))
|}
        (String.concat " " infer_cflags)
        (String.concat " " common_optflags)
        (String.concat " " ("InferIR" :: common_libraries))
        (String.concat " " infer_binaries)
    ; Format.sprintf
        {|
(executables
 ((names (%s))
  (flags (%s -open InferModules))
  (ocamlopt_flags (%s))
  (libraries (InferModules))
  (modules (%s))
  (preprocess (pps (ppx_compare ppx_sexp_conv -no-check)))
 ))
|}
        (String.concat " " infer_binaries)
        (String.concat " " infer_cflags)
        (String.concat " " common_optflags)
        (String.concat " " infer_binaries)
    ; Format.sprintf
        {|
(executable
 ((name infertop)
  (flags (%s))
  (libraries (utop InferModules))
  (modules (Infertop))
  (preprocess (pps (ppx_compare ppx_sexp_conv -no-check)))
  (link_flags (-linkall -warn-error -31))))
|}
        (String.concat " " infer_cflags) ]
  @ ( List.map
        (fun source_dir ->
          [ Printf.sprintf "(copy_files# %s/*.ml{,i,l})" source_dir
          ; (* menhir doesn't support '# 1 "<source file>"' directives at the start of the file inserted by
       copy# actions *)
            Printf.sprintf "(copy_files %s/*.mly)" source_dir ] )
        source_dirs
    |> List.concat )


;; String.concat "\n" stanzas |> Jbuild_plugin.V1.send
