macros.R 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. macroexpand <- function(ast, envir) {
  2. UseMethod("macroexpand")
  3. }
  4. macroexpand.default <- function(ast, envir) {
  5. ast
  6. }
  7. macroexpand.quote_call <- function(ast, envir) {
  8. ast
  9. }
  10. macroexpand.squote_call <- function(ast, envir) {
  11. ast
  12. }
  13. macroexpand.ral_list <- function(ast, envir) {
  14. if (length(ast) == 0) {
  15. return(ast)
  16. }
  17. if (!is_symbol(ast[[1]])) {
  18. return(ast)
  19. }
  20. fun_name <- as.character(ast[[1]])
  21. if (is_macro(fun_name, envir)) {
  22. fun <- eval(expr(`*ns_manager*`$get_current_ns()$get(!!fun_name)), envir = envir)
  23. return(macroexpand(exec(fun, !!!ast[-1]), envir))
  24. } else {
  25. if (length(ast) > 1) {
  26. for (i in 2:length(ast)) {
  27. ast[[i]] <- macroexpand(ast[[i]], envir)
  28. }
  29. }
  30. }
  31. ast
  32. }
  33. macroexpand.list <- function(ast, envir) {
  34. old_attributes <- attributes(ast)
  35. # TODO: nested macro expansions
  36. # TODO: map macro expansion
  37. # TODO: set macro expansion
  38. for (i in seq_along(ast)) {
  39. ast[[i]] <- macroexpand(ast[[i]], envir)
  40. }
  41. attributes(ast) <- old_attributes
  42. ast
  43. }
  44. #' @include constants.R
  45. is_macro <- function(fun_name, macro_env) {
  46. if (length(fun_name) != 1 || !is.character(fun_name)) {
  47. return(FALSE)
  48. }
  49. if (is.null(meta_data <- get0(RAL_META_DATA_NAME, macro_env))) {
  50. return(FALSE)
  51. }
  52. if (is.null(meta_data <- meta_data[[fun_name]])) {
  53. return(FALSE)
  54. }
  55. inherits(meta_data, "ral_map") && isTRUE(meta_data$get(":macro"))
  56. }