add_library(frontend STATIC
  AntlrDriver.cpp
  SyntaxTreePrinter.cpp
)

set(ANTLR4_GRAMMAR "${PROJECT_SOURCE_DIR}/src/antlr4/SysY.g4")
set(ANTLR4_GENERATED_FILES
  "${ANTLR4_GENERATED_DIR}/SysYLexer.cpp"
  "${ANTLR4_GENERATED_DIR}/SysYLexer.h"
  "${ANTLR4_GENERATED_DIR}/SysYLexer.interp"
  "${ANTLR4_GENERATED_DIR}/SysYLexer.tokens"
  "${ANTLR4_GENERATED_DIR}/SysYParser.cpp"
  "${ANTLR4_GENERATED_DIR}/SysYParser.h"
  "${ANTLR4_GENERATED_DIR}/SysY.interp"
  "${ANTLR4_GENERATED_DIR}/SysY.tokens"
  "${ANTLR4_GENERATED_DIR}/SysYBaseVisitor.h"
  "${ANTLR4_GENERATED_DIR}/SysYVisitor.h"
)

add_custom_command(
  OUTPUT ${ANTLR4_GENERATED_FILES}
  COMMAND ${CMAKE_COMMAND} -E make_directory "${ANTLR4_GENERATED_DIR}"
  COMMAND ${Java_JAVA_EXECUTABLE} -jar "${ANTLR4_JAR}"
          -Dlanguage=Cpp
          -visitor
          -no-listener
          -Xexact-output-dir
          -o "${ANTLR4_GENERATED_DIR}"
          "${ANTLR4_GRAMMAR}"
  DEPENDS "${ANTLR4_GRAMMAR}" "${ANTLR4_JAR}"
  COMMENT "Generating ANTLR4 parser sources from SysY.g4"
  VERBATIM
)

add_custom_target(antlr4_generated DEPENDS ${ANTLR4_GENERATED_FILES})
add_dependencies(frontend antlr4_generated)

target_sources(frontend PRIVATE
  "${ANTLR4_GENERATED_DIR}/SysYLexer.cpp"
  "${ANTLR4_GENERATED_DIR}/SysYParser.cpp"
)

target_link_libraries(frontend PUBLIC
  build_options
  ${ANTLR4_RUNTIME_TARGET}
)
