~subsetpark/fugue

ref: 2f3909210b2002f2d4f389d5a40017d1ba943f89 fugue/fugue.janet -rw-r--r-- 22.3 KiB
2f390921 — Zach Smith Tweak with-slots: @ by itself should be this 6 months ago
                                                                                
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
#
# Bootstrapping
#

(defn- bare-proto
  "Basic prototype table."
  [name defined-fields]
  @{:_meta @{:object-type :prototype
             :fields defined-fields
             :prototype-allocations @{}
             :instance-defaults @{}
             :getters @{}}
    :_name name})

(def Root
  "Root of the Fugue object hierarchy."
  (->
    (bare-proto "Prototype" [])
    (put :_init identity)))

(defn fields
  ```
  Return all the defined fields for `obj` and its prototype
  hierarchy.
  ```
  [obj]
  (let [proto-fields ;(if (table? obj)
                        (fields (table/getproto obj))
                        @[])
        obj-fields (or (get-in obj [:_meta :fields]) @[])]
    (array ;proto-fields ;obj-fields)))

#
# defproto Forms
#

(defn- proto-docstring
  [name defined-fields]
  (string/format
    "%s Prototype.\nFields: %q"
    (string name)
    ((comp freeze (partial map symbol)) defined-fields)))

(defn- field-definitions
  [name fields]
  (let [init-args @[]
        proto-allocated-fields @[]
        proto-allocations @{}
        instance-defaults @{}
        getters @{}]
    (loop [[field-name attrs] :in fields
           :let [key-field (keyword field-name)]]
      # Assemble list of arguments to constructor
      (when (attrs :init?)
        (array/push init-args field-name))
      # Assemble fields that should be set directly on this prototype
      (when (= (attrs :allocation) :prototype)
        (array/push proto-allocated-fields key-field))
      # Assemble values to be set directly on prototype
      (when-let [proto-value (attrs :allocate-value)]
        (put proto-allocations key-field (eval proto-value)))
      # Assemble mapping of fields to default values for instances
      (when-let [default-value (attrs :default)]
        (put instance-defaults key-field (eval default-value)))
      # Assemble mapping of fields to getters (unless excluded)
      (when-let [getter-name (match attrs
                               {:getter getter} getter
                               _ field-name)]
        (put getters field-name getter-name)))
    [init-args proto-allocated-fields proto-allocations instance-defaults getters]))

(defn- proto-form
  "Generate the def form for a Prototype."
  [name parent fields defined-fields
   _init-args proto-allocated-fields proto-allocations instance-defaults getters]
  ~(let [object (,bare-proto (,string ',name) ,defined-fields)]
     (,put-in object [:_meta :prototype-allocations]
        (,table/setproto
           (,table ;(,mapcat |[$0 object] ',proto-allocated-fields))
           (,get-in ',parent [:_meta :prototype-allocations])))
     (,put-in object [:_meta :instance-defaults] ',instance-defaults)
     (,put-in object [:_meta :getters] ',getters)
     (,merge-into object ',proto-allocations)
     (,table/setproto object ',parent)))

(defn- init-form
  "Generate the form that puts the object constructor method."
  [name init-args]

  ~(fn ,(symbol "new-from-" name)
     [self ,;init-args &keys attrs]
     (let [inst @{:_meta @{:object-type :instance}}]
       # Recursively lookup defaults in prototype hierarchy
       (var source-of-defaults self)
       (while source-of-defaults
         (let [defaults (,get-in source-of-defaults [:_meta :instance-defaults])]
           (loop [[default-key default-value] :pairs defaults]
             (,put inst default-key default-value)))
         # Recurse to grandparent
         (set source-of-defaults (,table/getproto source-of-defaults)))

       # Set positional values passed to constructor
       (let [kvs (->> ,init-args
                      (,interleave ',init-args)
                      (,partition 2))]
         (each [arg-name arg] kvs
           (,put inst (,keyword arg-name) arg)))

       # Set additional attributes passed to constructor
       (,merge-into inst attrs)

       # Associate instance with Prototype
       (,table/setproto inst self)

       (:_init inst))))

(put Root :new (eval (init-form 'Root [])))

(defn get-type-or-proto
  ```
  Return the prototype of `obj`, if it has one, otherwise the keyword
  output of `type`.
  ```
  [obj]
  (if (table? obj) (table/getproto obj) (type obj)))

(defn- pred-name [name] (symbol name "?"))

(defn- prototype-check
  "Check if obj is an instance of proto."
  [proto obj]
  (and (table? obj) (= proto (table/getproto obj))))

(defn- pred-form
  "Generate the defn form for the Prototype predicate."
  [name]
  (let [pred-name (pred-name name)
        pred-docstring (string/format ```
                                      Proto instance predicate: return if `obj` is an
                                      instance (that is, a direct child) of %s.
                                      ```
                                      (string name))]
    ~(defn ,pred-name
       ,pred-docstring
       [obj]
       (,prototype-check ,name obj))))

(eval (pred-form 'Root))

(defn- recursive-prototype-check
  "Check if obj is a descendent of ancestor."
  [ancestor obj]
  (or (prototype-check ancestor obj)
      (and (table? obj) (recursive-prototype-check ancestor (table/getproto obj)))))

(defn- pred*-form
  "Generate the defn form for the recursive Prototype predicate."
  [name]
  (let [pred-name (pred-name name)
        rec-pred-name (symbol name "*?")

        rec-pred-docstring (string/format ```
                                          Proto ancestor predicate: return if `obj` is a
                                          descendent of %s.
                                          ```
                                          (string name))]
    ~(defn ,rec-pred-name
       ,rec-pred-docstring
       [obj]
       (,recursive-prototype-check ,name obj))))

(eval (pred*-form 'Root))

(defn- new-form
  "Generate the init form wrapper."
  [name]
  (let [init-name (symbol "new-" name)
        docstring (string/format "Constructor for %s. Return a new object with %s as the prototype."
                                 (string name)
                                 (string name))]
    ~(defn ,init-name
       ,docstring
       [& rest]
       (:new ,name ;rest))))

(eval (new-form 'Root))

(defn- getters
  [name parent [_ _ _ _ getter-list]]
  (seq [[field-name getter-name] :pairs getter-list
        :let [key-field (keyword field-name)
              docstring (string "Get " field-name " from a " name)]]
    (with-syms [self]
      ~(defn ,getter-name
         ,docstring
         [,self]
         (let [current-fields (,fields ,self)]
           (unless (,index-of ,key-field current-fields)
             (,errorf "type error: expected proto with field %q, got %s with fields: %q"
                ,key-field
                (in ,self :_name)
                current-fields)))
         (,in ,self ,key-field)))))

(defmacro defproto
  ````
  Object prototype definition.

  ## Usage
  
  `name` should be any symbol. The resulting prototype will be
  named after it.

  `parent-name` is required; it can be an existing prototype, *or*
  some null-ish value. If null-ish (`nil` or `()` should make the most
  sense...) the parent of the prototype will be set to `fugue/Root`.

  `fields` should be 0 or more pairs of the following format:

  `<field-name> <field-attributes>`

  Where `field-attributes` is a struct describing the field. The
  following attributes are currently recognized:

  - `:default`: provide a default value for all new instances of this
  prototype
  - `:init?`: if truthy, then this field will be a required parameter
  to the prototype 's constructor
  - `:allocation`: if `:prototype`, then `fugue/allocate` will always act on
  the prototype when putting this field.
  - `:allocate-value`: this field will have this attribute set at the
  prototype, so that any children without their own values will
  inherit it.
  - `:getter`: specify a name for the defined function to access this
  field (by default, has the same name as the field). Specify `false`
  to prevent a getter from being defined.

  `defproto` will define a getter function for each of the defined
  fields, unless `:getter` is false.

  `defproto` will also create a `:new` method in the created
  prototype. This will take as positional arguments all of the fields
  specified as `init?`, and then accept in `&keys` format any other
  attributes to set on this object.

  The special method `:_init` will be called as the last step in the
  `:new` constructor. It can be defined for a prototype (see
  `defmethod`) to take a new instance and to make any arbitrary
  mutations on the instance or prototype as part of object
  instantiation. By default it simply returns the instance.

  The value provided to a field's `:default` entry will be inserted
  directly to the instance. Thus, mutable/referenced terms like tables
  and arrays will be shared amongst all instances. In cases where you
  want to insert a new term for each new instance, use the `_init`
  method to put a value at that field.
  
  If `fields` is not of an even length, it wil be taken as an error.

  ---
  
  An example usage:

  ```
  repl:43:> (fugue/defproto Dog () name {:allocate-value "Fido"})
  repl:44:> (fugue/defproto Pekingese Dog size {:default "Extremely Small"})
  repl:45:> (fugue/defmethod speak Dog [self] (string "My name is " (self :name)))
  repl:46:> (fugue/defmethod speak Pekingese [self] (string (prototype-method self) " and I am " (self :size)))
  repl:47:> (speak (:new Pekingese))
  "My name is Fido and I am Extremely Small"
  ```
  ````
  [name parent-name & fields]

  (unless (zero? (mod (length fields) 2))
    (error "defproto received odd number of fields"))

  (let [fields (partition 2 fields)
        parent (if (symbol? parent-name) (eval parent-name) Root)
        defined-fields (map (comp keyword 0) fields)
        field-definitions (field-definitions name fields)
        [init-args] field-definitions]
    (array
      ~(def ,name
         ,(proto-docstring name defined-fields)
         (->
           ,(proto-form name
                        parent
                        fields
                        defined-fields
                        ;field-definitions)
           (,put :new ,(init-form name init-args))))
      (pred-form name)
      (pred*-form name)
      (new-form name)
      ;(getters name parent field-definitions))))

(defn prototype?
  ```
  Is `obj` the result of a `defproto ` call? 
  ```
  [obj]
  (and (Root*? obj)
       (= :prototype (get-in obj [:_meta :object-type]))))

(defn allocate
  ```
  Allocation-aware put. If `obj` has inherited an allocation to a
  specific prototype for this key, then `fugue/allocate` will put `value`
  at `key` in the appropriate prototype, and it will be inherited by
  all descendents of that prototype.
  ```
  [obj key value]
  (if-let [proto (table/getproto obj)
           allocations (get-in proto [:_meta :prototype-allocations])
           allocation (allocations key)
           to-allocate allocation]
    (put to-allocate key value)
    (put obj key value)))

(def- raise-sentinel (gensym))

(defn- defgeneric*
  [name args & body]
  (with-syms [wrapper-args]
    (let [err-msg (string/format
                    "could not apply generic %s to args %%q"
                    (string name))
          method-name (keyword name)
          final-case (case body
                       [raise-sentinel] ~(,errorf
                                            ,err-msg
                                            ,wrapper-args)
                       ~(fn ,args ,;body))]
      ~(defn ,name
         "Generic function."
         [& ,wrapper-args]
         (match (,first ,wrapper-args)
           ({,method-name f} (function? f)) (f ;,wrapper-args)
           _ (,final-case ;,wrapper-args))))))

(defmacro defgeneric
  ```
  Define a generic function. When this function is called, if the
  first argument has a method corresponding to the name of the
  function, call that object 's method with the arguments. Otherwise,
  evaluate `body`.
  ```
  [name args &opt body]
  (default body raise-sentinel)
  (defgeneric* name args body))

(defmacro defmethod
  ```
  Simple single-dispatch method definition. Roughly equivalent to
  `put` ing a function directly into a prototype.

  Defines a few symbols for reference in the body of the method.
  
  - `__parent` - Bound to the parent of `proto`.
  - `__super` - Bound to the method at `name` within `__parent`.
  ```
  [name proto args & body]
  (upscope
    (let [current-binding (dyn name)]
      @[(unless (and current-binding (function? (current-binding :value)))
          (print "Defining generic function for method " name "...")
          (defgeneric* name args raise-sentinel))

        (let [method-name (keyword name)
              full-method-name (symbol proto "-" name)]
          ~(,put ,proto
              ,method-name
              (fn ,full-method-name
                ,args
                (let [__parent (table/getproto ,proto)
                      __super (__parent ,method-name)]
                  ,;body))))])))

#
# Multimethod Helpers
#

(defn- get-cases
  [name store]
  (as-> name .
        (store .)
        (pairs .)
        # Total hack: rely on the fact that `nil` is the smallest
        # value. Thus, when sorted, cases should always have the base
        # case last for any positional argument.
        #
        # ie: [:string :string]
        #     [:string :_]
        #     [:_ :number]
        #     [:_ :_]
        (sort . >)))

(defn- replace-placeholder-symbols
  [types]
  (defn f [sym]
    (case sym
      '_ nil
      :_ nil
      (let [evaled (eval sym)]
        (if (not (or (table? evaled) (keyword? evaled)))
          (errorf `Multimethod type error. Expected keyword or prototype, got:
                   %q of type %q`
                  sym
                  (type sym))
          evaled))))
  (tuple/slice (map f types)))

(defn- put-case
  [name types fun store]
  (let [types (replace-placeholder-symbols types)]
    (put-in store [name types] fun)))

#
# Multimethod Closures
#

(def- var-cases @{})

(defn- set-multi-default
  [name]
  (unless (dyn name)
    (setdyn name {:private true :value @{}})))

(defn- put-multi-case
  [sym name types fun]
  (let [multi-cases ((dyn sym) :value)]
    (put-case name types fun multi-cases)))

(defn- get-multi-cases
  [sym name]
  (let [multi-cases ((dyn sym) :value)]
    (get-cases name multi-cases)))

#
# Open Multi Closures
#

(defn- put-var-case
  [f types fun]
  (put-case f types fun var-cases))

(defn- get-var-cases
  [name]
  (get-cases name var-cases))

#
# Multimethod API
#

(defn multimethod-types-match?
  ```
  Check to see if the types `args` match the sequence `arg-types`,
  according to multimethod rules (ie, following prototype membership
  and using `:_` as a fallback)
  ```
  [args arg-types]
  (if (not= (length arg-types) (length args))
    false
    (do
      (var kk nil)
      (var vk nil)
      (var res true)
      (while true
        (set kk (next args kk))
        (if (= nil kk) (break))
        (set vk (next arg-types vk))
        (if (= nil vk) (break))
        (unless (or (= (arg-types vk) nil)
                    (= (get-type-or-proto (args kk)) (arg-types vk)))
          (set res false)
          (break)))
      res)))

(defn- construct-cond
  "Build main function logic of multimethod"
  [name cases args-symbol]
  (defn cond-case
    [[case-types case]]
    ~[(,multimethod-types-match? ,args-symbol ',case-types)
      (,case ;,args-symbol)])

  (let [body (mapcat cond-case cases)
        err-msg (string/format "could not apply multimethod %s to args %%q" name)]
    ~(cond ,;body (,errorf ,err-msg ,args-symbol))))

(defn- make-docstring
  "Compose docstring for multimethod"
  [cases &opt prefix]
  (default prefix "")
  (as->
    (partial string/format "- %q") .
    (comp . 0)
    (map . cases)
    (string/join . "\n\n")
    (string prefix "Multimethod. Defined types:\n\n" .)))

(defn- emit-defn
  "Generate defn form of multimethod"
  [name docstring args cond-form]
  ~(defn ,name
     ,docstring
     [& ,args]
     ,cond-form))

(defn- find-root
  [t]
  (cond
    (table/rawget t :ref) t
    (table/getproto t) (find-root (table/getproto t))
    nil))

(defn- emit-varfn
  "Generate varfn form of multimethod"
  [name fn-name docstring args cond-form]
  ~(let [cell (,find-root (dyn ',name))
         f (fn ,fn-name [& ,args] ,cond-form)]
     (,put-in cell [:ref 0] f)
     (,put-in cell [:doc] ,docstring)
     f))

(defn- make-case
  [args body]
  (eval ~(fn ,args ,;body)))

(defmacro defmulti
  ````
  Define a multimethod based on all the arguments passed to the
  function.

  Example usage :

  ```
  > (defproto Foo ())
  > (defmulti add [Foo] [f] (put f :value 1))
  > (defmulti add [:number] [x] (+ x 1))
  > (defmulti add [:string] [s] (string s "!"))
  > (def a-foo (:new Foo))
  > (add a-foo)
  @Foo{:value 1 :_meta @{:object-type :instance}}
  > (add 1)
  2
  > (add "s")
  "s!"
  ```

  `defmulti` takes a sequence of type-or-prototypes, and builds a
  function which will check its arguments against those types (as well
  as all other ones specified in other `defmulti` calls to the same
  function name), and execute the function body for the matching type
  signature.

  In addition to type names or prototypes, you can use the symbol `_`
  or keyword `:_` as a wildcard that means "match any type". For
  instance,

  ``` 
  repl:2:> (defmulti cat [:string :_] [s1 s2] (string s1 s2))
  repl:3:> (cat "hello " "world!")
  "hello world!"
  repl:4:> (cat "hello " 42)
  "hello 42"
  repl:5:> (cat 42 "hello")
  error: could not apply multimethod <function cat> to args (42 "hello")
    in cat [repl] on line 2, column 1
    in _thunk [repl] (tailcall) on line 5, column 1
  ```

  Defining a multimethod with the signature `[:string :_]` will match
  on any two arguments if the first one is a string.

  A multimethod without wilcards will be preferred to one with one in
  the same position. For instance, if we define an additional
  multimethod:

  ```
  repl:8:> (defmulti cat [:string :number] [s n] (string s " #" n))
  ```

  Then that more specific method will be preferred and the wildcard
  will be a fallback if the specific one doesn't match:

  ```
  repl:10:> (cat "hello " @"world")
  "hello world"
  repl:12:> (cat "hello" 100)
  "hello #100"
  ```
  ````
  [name multi-types args & body]

  (let [cases-sym (symbol "_fugue-multi-cases-" name)]
    (set-multi-default cases-sym)
    (put-multi-case cases-sym name multi-types (make-case args body))

    (with-syms [args]
      (let [cases (get-multi-cases cases-sym name)
            cond-form (construct-cond (string name) cases args)
            docstring (make-docstring cases)]
        (emit-defn name docstring args cond-form)))))

(defmacro declare-open-multi
  ```
  Declare an open multimethod, ie, one that can be extended.

  Extending an open multimethod (see `extend-multi`) from any other
  environment makes the case extension available wherever the
  multimethod has been imported.
  ```
  [name]
  (let [f (eval ~(fn ,name [& _] (error "No cases declared for open multimethod")))
        ref @[f]
        cell @{:doc "Open multimethod." :ref ref}]
    (put var-cases ref @{})
    (setdyn name cell)
    f))

(defmacro extend-multi
  ```
  Extend an open multimethod (see `declare-open-multi`) using the same
  syntax as `defmulti`.

  See that function's documentation for full usage reference.

  Whenever a case is added to `multi`, that case is available
  wherever the multimethod is imported.
  ```
  [multi multi-types args & body]
  (let [ref (and (dyn multi) (in (dyn multi) :ref))]
    (put-var-case ref multi-types (make-case args body))

    (with-syms [args]
      (let [cases (get-var-cases ref)
            fn-name (->> multi (string/split "/") (last))
            cond-form (construct-cond fn-name cases args)
            docstring (make-docstring cases "Open ")]
        (emit-varfn multi (symbol fn-name) docstring args cond-form)))))

(defn- field-transformer
  [fields obj-sym as proto-name]
  (fn [sym]
    (cond
      (and (tuple? sym) (= (length sym) 2) (= (sym 0) as) (symbol? (sym 1)))
      (let [field-name (-> sym (1) (keyword))]
        (unless (index-of field-name fields)
          (errorf `Encountered field reference %q for prototype %q;

                   Expected one of: %q`
                  sym
                  proto-name
                  fields))
        ~(,obj-sym ,field-name))

      (= sym as)
      obj-sym

      true
      sym)))

(defn- do-with-slots-as
  [proto obj as body]
  (with-syms [x]
    (let [f (-> proto (eval) (fields) (field-transformer x as proto))]
      ~(let [,x ,obj]
         ,;(prewalk f body)
         ,x))))

(defmacro with-slots
  ````
  Anaphoric macro with transformed getter/setters.

  Introduces two useful forms for referring to `obj`.

  It introduces a *reference symbol* - `@` by default
  (see `with-slots-as `to specify the symbol).

  The pattern `(@ <field name>)`, where `<field name>` is a symbol, is
  transformed into `(obj (keyword <field name>))`, if and only if
  `<field name>` is defined for `proto`, so that `(@ name)` or its
  setter form `(set (@ name) foo)` do the right thing.

  The reference symbol by itself is introduces as a reference to
  `obj`.

  Returns `obj`.
  
  ---

  Example :

  ```
  repl:2:> (defproto Foo nil name {:default "Jane Doe"})
  repl:4:> (with-slots Foo (new-Foo)
             (set (@ name) "Cosmo Kramer")
             (print (@ name))
             (print (Foo? @)))
  Cosmo Kramer
  true
  @Foo{:_meta @{:object-type :instance} :name "Cosmo Kramer"}
  ```
  ````
  [proto obj & body]
  (do-with-slots-as proto obj '@ body))

(defmacro with-slots-as
  ```
  Anaphoric macro with transformed getter/setters.

  Specifies `as` as the reference symbol for `with-slots`.

  See `with-slots` documentation for more details.
  ```
  [proto obj as & body]
  (do-with-slots-as proto obj as body))

(defmacro @
  ```
  Compile-time Prototype field checking.

  Accepts two forms:

  `(@ SomePrototype :some-field)` - Translates into `:some-field`, if
  `some-field` is defined on `SomePrototype`.

  `(@ SomePrototype some-object :some-field)` - Asserts (as above) at
  compile time that `some-field` is defined on `SomePrototype`; at
  runtime, checks that `some-object` is a descendent of
  `SomePrototype` and if so, translates to `(some-object
  :some-field)`.
  ```
  [proto x &opt y]
  (let [[obj field] (if y [x y] [nil x])
        fields (fields (eval proto))]

    (unless (index-of field fields)
      (errorf "Field `%s` not found; got fields: %q" (string field) fields))

    (if-not obj
      field
      ~(if-not (,recursive-prototype-check ,proto ,obj)
         (errorf "Expected a %s, got: %q" ,(string proto) (,get-type-or-proto ,obj))
         ,(tuple obj field)))))