FindFLEX.cmake 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file LICENSE.rst or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. FindFLEX
  5. --------
  6. Finds the Fast Lexical Analyzer (Flex) command-line generator and its library,
  7. and provides CMake commands to create custom build rules for using Flex:
  8. .. code-block:: cmake
  9. find_package(FLEX [<version>] ...)
  10. Flex generates lexical analyzers, also known as *scanners* or *lexers*. It also
  11. includes a runtime library (``fl``) that supplies support functions for the
  12. generated scanners, such as input handling, buffer management, and error
  13. reporting.
  14. Result Variables
  15. ^^^^^^^^^^^^^^^^
  16. This module defines the following variables:
  17. ``FLEX_FOUND``
  18. Boolean indicating whether (the requested version of) Flex is found.
  19. ``FLEX_VERSION``
  20. The version of Flex found.
  21. ``FLEX_INCLUDE_DIRS``
  22. The include directories containing headers for using Flex library.
  23. ``FLEX_LIBRARIES``
  24. The libraries needed to link against to use Flex library.
  25. Cache Variables
  26. ^^^^^^^^^^^^^^^
  27. The following cache variables may also be set:
  28. ``FLEX_EXECUTABLE``
  29. The path to the ``flex`` executable.
  30. Commands
  31. ^^^^^^^^
  32. This module provides the following commands if ``flex`` is found:
  33. Generating Scanners
  34. """""""""""""""""""
  35. .. command:: flex_target
  36. Creates a custom build rule to generate a scanner file from a lex file using
  37. Flex:
  38. .. code-block:: cmake
  39. flex_target(
  40. <name>
  41. <input-lex-file>
  42. <output-scanner-file>
  43. [DEFINES_FILE <header>]
  44. [OPTIONS <options>...]
  45. [COMPILE_FLAGS <string>] # Deprecated
  46. )
  47. .. versionchanged:: 3.17
  48. When policy :policy:`CMP0098` is set to ``NEW``, ``flex`` runs in the
  49. :variable:`CMAKE_CURRENT_BINARY_DIR` directory.
  50. ``<name>``
  51. String used as an identifier for this command invocation.
  52. ``<input-lex-file>``
  53. The path to an input Flex source file (``.l``). If given as a relative
  54. path, it will be interpreted relative to the current source directory
  55. (:variable:`CMAKE_CURRENT_SOURCE_DIR`).
  56. ``<output-scanner-file>``
  57. The path of the output file to be generated by Flex. If given as a relative
  58. path, it will be interpreted relative to the current Flex working directory.
  59. ``DEFINES_FILE <header>``
  60. .. versionadded:: 3.5
  61. If Flex is configured to output a header file, this option may be used to
  62. specify its name. If given as a relative path, it will be interpreted
  63. relative to the current Flex working directory.
  64. ``OPTIONS <options>...``
  65. .. versionadded:: 4.0
  66. A :ref:`semicolon-separated list <CMake Language Lists>` of extra options
  67. added to the ``flex`` command line.
  68. ``COMPILE_FLAGS <string>``
  69. .. deprecated:: 4.0
  70. Superseded by ``OPTIONS <options>...``.
  71. A string of space-separated extra options added to the ``flex`` command
  72. line. A :ref:`semicolon-separated list <CMake Language Lists>` will not
  73. work.
  74. ---------------------------------------------------------------------
  75. This command also defines the following variables:
  76. ``FLEX_<name>_DEFINED``
  77. Boolean indicating whether this command was successfully invoked.
  78. ``FLEX_<name>_INPUT``
  79. The Flex source file, an alias for ``<input-lex-file>``.
  80. ``FLEX_<name>_OUTPUT_HEADER``
  81. .. versionadded:: 3.5
  82. The header file generated by ``flex``, if any.
  83. ``FLEX_<name>_OUTPUTS``
  84. A list of files generated by ``flex``, including the output scanner file,
  85. and the header file.
  86. ``FLEX_<name>_OPTIONS``
  87. .. versionadded:: 4.0
  88. A list of command-line options used for the ``flex`` command.
  89. Adding Dependency Between Scanner and Parser
  90. """"""""""""""""""""""""""""""""""""""""""""
  91. .. command:: add_flex_bison_dependency
  92. Adds the required dependency between a scanner and a parser:
  93. .. code-block:: cmake
  94. add_flex_bison_dependency(<flex-name> <bison-name>)
  95. Flex scanners often rely on token definitions generated by Bison, meaning the
  96. code produced by Flex depends on the header file created by Bison.
  97. This command adds the required dependency between a scanner and a parser
  98. where ``<flex-name>`` and ``<bison-name>`` are the first parameters of
  99. respectively ``flex_target(<name> ...)`` and
  100. :command:`bison_target(<name> ...)` commands.
  101. Examples
  102. ^^^^^^^^
  103. Examples: Finding Flex
  104. """"""""""""""""""""""
  105. Finding Flex:
  106. .. code-block:: cmake
  107. find_package(FLEX)
  108. Finding Flex and specifying its minimum required version:
  109. .. code-block:: cmake
  110. find_package(FLEX 2.5.13)
  111. Finding Flex and making it required (if Flex is not found, processing stops
  112. with an error message):
  113. .. code-block:: cmake
  114. find_package(FLEX 2.5.13 REQUIRED)
  115. Example: Generating Scanner
  116. """""""""""""""""""""""""""
  117. Finding Flex and generating scanner source file in the current binary directory
  118. from the lex source file in the current source directory:
  119. .. code-block:: cmake
  120. find_package(FLEX)
  121. if(FLEX_FOUND)
  122. flex_target(MyScanner lexer.l lexer.cpp)
  123. endif()
  124. add_executable(foo foo.cc ${FLEX_MyScanner_OUTPUTS})
  125. Example: Command-line Options
  126. """""""""""""""""""""""""""""
  127. Adding additional command-line options to the ``flex`` executable can be passed
  128. as a list. For example, adding the ``--warn`` option to report warnings, and
  129. the ``--noline`` (``-L``) to not generate ``#line`` directives.
  130. .. code-block:: cmake
  131. find_package(FLEX)
  132. if(FLEX_FOUND)
  133. flex_target(MyScanner lexer.l lexer.cpp OPTIONS --warn --noline)
  134. endif()
  135. :manual:`Generator expressions <cmake-generator-expressions(7)>` can be used in
  136. the ``OPTIONS <options>...`` argument. For example, to add the ``--debug``
  137. (``-d``) option only for the ``Debug`` build type:
  138. .. code-block:: cmake
  139. find_package(FLEX)
  140. if(FLEX_FOUND)
  141. flex_target(MyScanner lexer.l lexer.cpp OPTIONS $<$<CONFIG:Debug>:--debug>)
  142. endif()
  143. Example: Using Flex Library
  144. """""""""""""""""""""""""""
  145. Finding Flex and creating an interface :ref:`imported target <Imported Targets>`
  146. that encapsulates its library usage requirements for linking to a project
  147. target:
  148. .. code-block:: cmake
  149. find_package(FLEX)
  150. if(FLEX_FOUND AND NOT TARGET FLEX::fl)
  151. add_library(FLEX::fl INTERFACE IMPORTED)
  152. set_target_properties(
  153. FLEX::fl
  154. PROPERTIES
  155. INTERFACE_INCLUDE_DIRECTORIES "${FLEX_INCLUDE_DIRS}"
  156. INTERFACE_LINK_LIBRARIES "${FLEX_LIBRARIES}"
  157. )
  158. endif()
  159. if(FLEX_FOUND)
  160. flex_target(MyScanner lexer.l lexer.cpp)
  161. endif()
  162. add_executable(Foo foo.cc ${FLEX_MyScanner_OUTPUTS})
  163. target_link_libraries(Foo PRIVATE FLEX::fl)
  164. Example: Using Flex and Bison
  165. """""""""""""""""""""""""""""
  166. The following example demonstrates, how to use Flex and :module:`Bison
  167. <FindBISON>` in CMake:
  168. .. code-block:: cmake
  169. find_package(BISON)
  170. find_package(FLEX)
  171. if(BISON_FOUND AND FLEX_FOUND)
  172. bison_target(MyParser parser.y parser.cpp)
  173. flex_target(MyScanner lexer.l lexer.cpp)
  174. add_flex_bison_dependency(MyScanner MyParser)
  175. endif()
  176. add_executable(Foo foo.cc ${BISON_MyParser_OUTPUTS} ${FLEX_MyScanner_OUTPUTS})
  177. # ...
  178. See Also
  179. ^^^^^^^^
  180. * The :module:`FindBISON` module to find Bison parser generator.
  181. #]=======================================================================]
  182. find_program(FLEX_EXECUTABLE NAMES flex win-flex win_flex DOC "path to the flex executable")
  183. mark_as_advanced(FLEX_EXECUTABLE)
  184. find_library(FL_LIBRARY NAMES fl
  185. DOC "Path to the fl library")
  186. find_path(FLEX_INCLUDE_DIR FlexLexer.h
  187. DOC "Path to the flex headers")
  188. mark_as_advanced(FL_LIBRARY FLEX_INCLUDE_DIR)
  189. set(FLEX_INCLUDE_DIRS ${FLEX_INCLUDE_DIR})
  190. set(FLEX_LIBRARIES ${FL_LIBRARY})
  191. if(FLEX_EXECUTABLE)
  192. execute_process(COMMAND ${FLEX_EXECUTABLE} --version
  193. OUTPUT_VARIABLE FLEX_version_output
  194. ERROR_VARIABLE FLEX_version_error
  195. RESULT_VARIABLE FLEX_version_result
  196. OUTPUT_STRIP_TRAILING_WHITESPACE)
  197. if(NOT ${FLEX_version_result} EQUAL 0)
  198. if(FLEX_FIND_REQUIRED)
  199. message(SEND_ERROR "Command \"${FLEX_EXECUTABLE} --version\" failed with output:\n${FLEX_version_output}\n${FLEX_version_error}")
  200. else()
  201. message("Command \"${FLEX_EXECUTABLE} --version\" failed with output:\n${FLEX_version_output}\n${FLEX_version_error}\nFLEX_VERSION will not be available")
  202. endif()
  203. else()
  204. # older versions of flex printed "/full/path/to/executable version X.Y"
  205. # newer versions use "basename(executable) X.Y"
  206. get_filename_component(FLEX_EXE_NAME_WE "${FLEX_EXECUTABLE}" NAME_WE)
  207. get_filename_component(FLEX_EXE_EXT "${FLEX_EXECUTABLE}" EXT)
  208. string(REGEX REPLACE "^.*${FLEX_EXE_NAME_WE}(${FLEX_EXE_EXT})?\"? (version )?([0-9]+[^ ]*)( .*)?$" "\\3"
  209. FLEX_VERSION "${FLEX_version_output}")
  210. unset(FLEX_EXE_EXT)
  211. unset(FLEX_EXE_NAME_WE)
  212. endif()
  213. #============================================================
  214. # flex_target() public macro
  215. #============================================================
  216. #
  217. macro(FLEX_TARGET Name Input Output)
  218. set(FLEX_TARGET_PARAM_OPTIONS)
  219. set(FLEX_TARGET_PARAM_ONE_VALUE_KEYWORDS
  220. COMPILE_FLAGS
  221. DEFINES_FILE
  222. )
  223. set(FLEX_TARGET_PARAM_MULTI_VALUE_KEYWORDS OPTIONS)
  224. cmake_parse_arguments(
  225. FLEX_TARGET_ARG
  226. "${FLEX_TARGET_PARAM_OPTIONS}"
  227. "${FLEX_TARGET_PARAM_ONE_VALUE_KEYWORDS}"
  228. "${FLEX_TARGET_PARAM_MULTI_VALUE_KEYWORDS}"
  229. ${ARGN}
  230. )
  231. string(
  232. JOIN "\n" FLEX_TARGET_usage
  233. "Usage:"
  234. " flex_target("
  235. " <name>"
  236. " <input-lex-file>"
  237. " <output-scanner-file>"
  238. " [DEFINES_FILE <header>]"
  239. " [OPTIONS <options>...]"
  240. " [COMPILE_FLAGS <string>]"
  241. " )"
  242. )
  243. if(NOT "${FLEX_TARGET_ARG_UNPARSED_ARGUMENTS}" STREQUAL "")
  244. message(
  245. SEND_ERROR
  246. "Unrecognized arguments: ${FLEX_TARGET_ARG_UNPARSED_ARGUMENTS}\n"
  247. "${FLEX_TARGET_usage}"
  248. )
  249. else()
  250. cmake_policy(GET CMP0098 _flex_CMP0098
  251. PARENT_SCOPE # undocumented, do not use outside of CMake
  252. )
  253. set(_flex_INPUT "${Input}")
  254. if("x${_flex_CMP0098}x" STREQUAL "xNEWx")
  255. set(_flex_WORKING_DIR "${CMAKE_CURRENT_BINARY_DIR}")
  256. if(NOT IS_ABSOLUTE "${_flex_INPUT}")
  257. set(_flex_INPUT "${CMAKE_CURRENT_SOURCE_DIR}/${_flex_INPUT}")
  258. endif()
  259. else()
  260. set(_flex_WORKING_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
  261. endif()
  262. unset(_flex_CMP0098)
  263. set(_flex_OUTPUT "${Output}")
  264. if(NOT IS_ABSOLUTE ${_flex_OUTPUT})
  265. set(_flex_OUTPUT "${_flex_WORKING_DIR}/${_flex_OUTPUT}")
  266. endif()
  267. set(_flex_TARGET_OUTPUTS "${_flex_OUTPUT}")
  268. set(_flex_EXE_OPTS "")
  269. if(NOT "${FLEX_TARGET_ARG_COMPILE_FLAGS}" STREQUAL "")
  270. set(_flex_EXE_OPTS "${FLEX_TARGET_ARG_COMPILE_FLAGS}")
  271. separate_arguments(_flex_EXE_OPTS)
  272. endif()
  273. if(FLEX_TARGET_ARG_OPTIONS)
  274. list(APPEND _flex_EXE_OPTS ${FLEX_TARGET_ARG_OPTIONS})
  275. endif()
  276. set(_flex_OUTPUT_HEADER "")
  277. if(NOT "${FLEX_TARGET_ARG_DEFINES_FILE}" STREQUAL "")
  278. set(_flex_OUTPUT_HEADER "${FLEX_TARGET_ARG_DEFINES_FILE}")
  279. if(IS_ABSOLUTE "${_flex_OUTPUT_HEADER}")
  280. set(_flex_OUTPUT_HEADER_ABS "${_flex_OUTPUT_HEADER}")
  281. else()
  282. set(_flex_OUTPUT_HEADER_ABS "${_flex_WORKING_DIR}/${_flex_OUTPUT_HEADER}")
  283. endif()
  284. list(APPEND _flex_TARGET_OUTPUTS "${_flex_OUTPUT_HEADER_ABS}")
  285. list(APPEND _flex_EXE_OPTS --header-file=${_flex_OUTPUT_HEADER_ABS})
  286. endif()
  287. # Flex cannot create output directories. Create any missing determined
  288. # directories where the files will be generated if they don't exist yet.
  289. set(_flex_MAKE_DIRECTORY_COMMAND "")
  290. foreach(output IN LISTS _flex_TARGET_OUTPUTS)
  291. cmake_path(GET output PARENT_PATH dir)
  292. if(dir)
  293. list(APPEND _flex_MAKE_DIRECTORY_COMMAND ${dir})
  294. endif()
  295. unset(dir)
  296. endforeach()
  297. if(_flex_MAKE_DIRECTORY_COMMAND)
  298. list(REMOVE_DUPLICATES _flex_MAKE_DIRECTORY_COMMAND)
  299. list(
  300. PREPEND
  301. _flex_MAKE_DIRECTORY_COMMAND
  302. COMMAND ${CMAKE_COMMAND} -E make_directory
  303. )
  304. endif()
  305. get_filename_component(_flex_EXE_NAME_WE "${FLEX_EXECUTABLE}" NAME_WE)
  306. add_custom_command(OUTPUT ${_flex_TARGET_OUTPUTS}
  307. ${_flex_MAKE_DIRECTORY_COMMAND}
  308. COMMAND ${FLEX_EXECUTABLE} ${_flex_EXE_OPTS} -o${_flex_OUTPUT} ${_flex_INPUT}
  309. VERBATIM
  310. DEPENDS ${_flex_INPUT}
  311. COMMENT "[FLEX][${Name}] Building scanner with ${_flex_EXE_NAME_WE} ${FLEX_VERSION}"
  312. WORKING_DIRECTORY ${_flex_WORKING_DIR}
  313. COMMAND_EXPAND_LISTS)
  314. set(FLEX_${Name}_DEFINED TRUE)
  315. set(FLEX_${Name}_OUTPUTS ${_flex_TARGET_OUTPUTS})
  316. set(FLEX_${Name}_INPUT ${_flex_INPUT})
  317. set(FLEX_${Name}_OPTIONS ${_flex_EXE_OPTS})
  318. set(FLEX_${Name}_COMPILE_FLAGS ${_flex_EXE_OPTS})
  319. set(FLEX_${Name}_OUTPUT_HEADER ${_flex_OUTPUT_HEADER})
  320. unset(_flex_EXE_NAME_WE)
  321. unset(_flex_EXE_OPTS)
  322. unset(_flex_INPUT)
  323. unset(_flex_MAKE_DIRECTORY_COMMAND)
  324. unset(_flex_OUTPUT)
  325. unset(_flex_OUTPUT_HEADER)
  326. unset(_flex_OUTPUT_HEADER_ABS)
  327. unset(_flex_TARGET_OUTPUTS)
  328. unset(_flex_WORKING_DIR)
  329. endif()
  330. endmacro()
  331. #============================================================
  332. #============================================================
  333. # add_flex_bison_dependency() public macro
  334. #============================================================
  335. #
  336. macro(ADD_FLEX_BISON_DEPENDENCY FlexTarget BisonTarget)
  337. if(NOT FLEX_${FlexTarget}_OUTPUTS)
  338. message(SEND_ERROR "Flex target `${FlexTarget}' does not exist.")
  339. endif()
  340. if(NOT BISON_${BisonTarget}_OUTPUT_HEADER)
  341. message(SEND_ERROR "Bison target `${BisonTarget}' does not exist.")
  342. endif()
  343. set_source_files_properties(${FLEX_${FlexTarget}_OUTPUTS}
  344. PROPERTIES OBJECT_DEPENDS ${BISON_${BisonTarget}_OUTPUT_HEADER})
  345. endmacro()
  346. #============================================================
  347. endif()
  348. include(FindPackageHandleStandardArgs)
  349. find_package_handle_standard_args(FLEX REQUIRED_VARS FLEX_EXECUTABLE
  350. VERSION_VAR FLEX_VERSION)