[racket] A safe version of unsafe-struct-ref [for Whalesong]

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Thu Jul 3 14:11:25 EDT 2014

Thanks to all for the advice. It seems the following version of match
works for Whalesong:

    https://github.com/soegaard/whalesong-libs

Admitted I have only made superfical tests.


In match/compiler.rkt I replaced

(define (gen-clause k rows x xs esc)
  <...>
  ;; it's a structure

    [(box? k)
     ;; all the rows are structures with the same predicate
     (let* ([s (Row-first-pat (car rows))]
            [accs (Struct-accessors s)]
            [accs (if (Struct-complete? s)
                      (build-list (length accs) (λ (i) #`(λ (x)
(unsafe-struct-ref x #,i))))
                      accs)]
            [pred (Struct-pred s)])
       (compile-con-pat accs pred Struct-ps))]
    <...>)

with

(define (gen-clause k rows x xs esc)
  <...>
    ;; it's a structure
    [(box? k)
     ;; all the rows are structures with the same predicate
     (let* ([s (Row-first-pat (car rows))]
            [accs (Struct-accessors s)]
            [accs (if (Struct-complete? s)
                      (build-list (length accs)
                                  (λ (i) (with-syntax ([a (list-ref accs i)])
                                           #`(λ (x) (a x))))) ; [Whalesong]
                      accs)]
            [pred (Struct-pred s)])
       (compile-con-pat accs pred Struct-ps))]
    <...>)

/Jens Axel

2014-07-03 15:12 GMT+02:00 Sam Tobin-Hochstadt <samth at cs.indiana.edu>:
> The output of `match` when it uses `unsafe-struct-ref` can't be
> faithfully implemented safely. In particular, `match` has access to
> the accessor function, which may give you results that you can't get
> from safe reflection such as `struct->vector`.
>
> Instead, I think you should just implement `unsafe-struct-ref` to look
> inside the abstraction of structs, so that it violates the abstraction
> in the same way that it does in Racket. While this won't potentially
> crash in JavaScript, it will be unsafe relative to the abstractions of
> Racket, and thus deserves the name unsafe.
>
> Sam
>
> On Wed, Jul 2, 2014 at 9:06 PM, Jens Axel Søgaard <jensaxel at soegaard.net> wrote:
>> Is it possible to implement unsafe-struct-ref using safe constructs only?
>>
>> The reason behind this peculiar question, is that I am porting racket/match
>> to Whalesong. The match compiler uses various unsafe constructs that Whalesong
>> doesn't implement. It is straightforward to replace, say,
>> unsafe-vector-ref with vector-ref.
>>
>> But unsafe-struct-ref ?
>>
>> It is okay to use all tricks in the book in phase 1 (Whalesong has
>> restrictions in phase 0 only).
>>
>> /Jens Axel
>> ____________________
>>   Racket Users list:
>>   http://lists.racket-lang.org/users



-- 
--
Jens Axel Søgaard


Posted on the users mailing list.