aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/macro.lux
blob: 193b5a25efd2c86ed9f2b960e49a1f5bfdaef8ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
(.module:
  [library
   [lux #*
    [abstract
     ["." monad (#+ do)]]
    [data
     ["." text ("#\." monoid)]
     ["." name ("#\." codec)]
     [collection
      ["." list ("#\." monoid monad)]]]
    [macro
     ["." code]]
    [math
     [number
      ["." nat]
      ["." int]]]]]
  ["." // #_
   ["#" meta
    ["." location]]])

(def: .public (single_expansion syntax)
  {#.doc (doc "Given code that requires applying a macro, does it once and returns the result."
              "Otherwise, returns the code as-is.")}
  (-> Code (Meta (List Code)))
  (case syntax
    [_ (#.Form (#.Item [[_ (#.Identifier name)] args]))]
    (do //.monad
      [?macro (//.macro name)]
      (case ?macro
        (#.Some macro)
        ((:as Macro' macro) args)
        
        #.None
        (\ //.monad in (list syntax))))

    _
    (\ //.monad in (list syntax))))

(def: .public (expansion syntax)
  {#.doc (doc "Given code that requires applying a macro, expands repeatedly until no more direct macro-calls are left."
              "Otherwise, returns the code as-is.")}
  (-> Code (Meta (List Code)))
  (case syntax
    [_ (#.Form (#.Item [[_ (#.Identifier name)] args]))]
    (do //.monad
      [?macro (//.macro name)]
      (case ?macro
        (#.Some macro)
        (do {! //.monad}
          [top_level_expansion ((:as Macro' macro) args)]
          (|> top_level_expansion
              (monad.map //.monad expansion)
              (\ ! map list\join)))
        
        #.None
        (\ //.monad in (list syntax))))

    _
    (\ //.monad in (list syntax))))

(def: .public (full_expansion syntax)
  {#.doc "Expands all macro-calls everywhere recursively, until only primitive/base code remains."}
  (-> Code (Meta (List Code)))
  (case syntax
    [_ (#.Form (#.Item [[_ (#.Identifier name)] args]))]
    (do //.monad
      [?macro (//.macro name)]
      (case ?macro
        (#.Some macro)
        (do //.monad
          [expansion ((:as Macro' macro) args)
           expansion' (monad.map //.monad full_expansion expansion)]
          (in (list\join expansion')))
        
        #.None
        (do //.monad
          [parts' (monad.map //.monad full_expansion (list& (code.identifier name) args))]
          (in (list (code.form (list\join parts')))))))

    [_ (#.Form (#.Item [harg targs]))]
    (do //.monad
      [harg+ (full_expansion harg)
       targs+ (monad.map //.monad full_expansion targs)]
      (in (list (code.form (list\compose harg+ (list\join (: (List (List Code)) targs+)))))))

    [_ (#.Tuple members)]
    (do //.monad
      [members' (monad.map //.monad full_expansion members)]
      (in (list (code.tuple (list\join members')))))

    [_ (#.Record members)]
    (|> members
        (monad.map //.monad
                   (function (_ [left right])
                     (do //.monad
                       [left (full_expansion left)
                        right (full_expansion right)]
                       (case [left right]
                         [(#.Item left #.End) (#.Item right #.End)]
                         (in [left right])

                         _
                         (//.failure "Record members must expand into singletons.")))))
        (\ //.monad map (|>> code.record list)))

    _
    (\ //.monad in (list syntax))))

(def: .public (gensym prefix)
  {#.doc (doc "Generates a unique name as an Code node (ready to be used in code templates)."
              "A prefix can be given (or just be empty text) to better identify the code for debugging purposes.")}
  (-> Text (Meta Code))
  (do //.monad
    [id //.seed]
    (in (|> id
            (\ nat.decimal encode)
            ($_ text\compose "__gensym__" prefix)
            [""] code.identifier))))

(def: (get_local_identifier ast)
  (-> Code (Meta Text))
  (case ast
    [_ (#.Identifier [_ name])]
    (\ //.monad in name)

    _
    (//.failure (text\compose "Code is not a local identifier: " (code.format ast)))))

(def: .public wrong_syntax_error
  (-> Name Text)
  (|>> name\encode
       (text\compose "Wrong syntax for ")))

(macro: .public (with_gensyms tokens)
  {#.doc (doc "Creates new identifiers and offers them to the body expression."
              (syntax: .public (synchronized lock body)
                (with_gensyms [g!lock g!body g!_]
                  (in (list (` (let [(~ g!lock) (~ lock)
                                     (~ g!_) ("jvm monitorenter" (~ g!lock))
                                     (~ g!body) (~ body)
                                     (~ g!_) ("jvm monitorexit" (~ g!lock))]
                                 (~ g!body)))))
                  )))}
  (case tokens
    (^ (list [_ (#.Tuple identifiers)] body))
    (do {! //.monad}
      [identifier_names (monad.map ! ..get_local_identifier identifiers)
       .let [identifier_defs (list\join (list\map (: (-> Text (List Code))
                                                     (function (_ name) (list (code.identifier ["" name]) (` (gensym (~ (code.text name)))))))
                                                  identifier_names))]]
      (in (list (` ((~! do) (~! //.monad)
                    [(~+ identifier_defs)]
                    (~ body))))))

    _
    (//.failure (..wrong_syntax_error (name_of ..with_gensyms)))))

(def: .public (one_expansion token)
  {#.doc "Works just like expand, except that it ensures that the output is a single Code token."}
  (-> Code (Meta Code))
  (do //.monad
    [token+ (..expansion token)]
    (case token+
      (^ (list token'))
      (in token')

      _
      (//.failure "Macro expanded to more than 1 element."))))

(template [<macro> <func>]
  [(macro: .public (<macro> tokens)
     {#.doc (doc "Performs a macro-expansion and logs the resulting code."
                 "You can either use the resulting code, or omit them."
                 "By omitting them, this macro produces nothing (just like the lux.comment macro)."
                 (<macro> #omit
                          (def: (foo bar baz)
                            (-> Int Int Int)
                            (int.+ bar baz))))}
     (let [[module _] (name_of .._)
           [_ short] (name_of <macro>)
           macro_name [module short]]
       (case (: (Maybe [Bit Code])
                (case tokens
                  (^ (list [_ (#.Tag ["" "omit"])]
                           token))
                  (#.Some [#1 token])

                  (^ (list token))
                  (#.Some [#0 token])

                  _
                  #.None))
         (#.Some [omit? token])
         (do //.monad
           [location //.location
            output (<func> token)
            .let [_ ("lux io log" ($_ text\compose (name\encode macro_name) " " (location.format location)))
                  _ (list\map (|>> code.format "lux io log")
                              output)
                  _ ("lux io log" "")]]
           (in (if omit?
                 (list)
                 output)))

         #.None
         (//.failure (..wrong_syntax_error macro_name)))))]

  [log_single_expansion! ..single_expansion]
  [log_expansion!        ..expansion]
  [log_full_expansion!   ..full_expansion]
  )