Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. #lang racket
  2.  
  3. (require (for-syntax syntax/parse
  4. syntax/boundmap
  5. racket))
  6.  
  7. (provide (except-out (all-from-out racket) #%app)
  8. (rename-out [infix #%app])
  9. infix-set!
  10. $)
  11.  
  12. (define-for-syntax infix-hash (make-free-identifier-mapping))
  13.  
  14. (define-syntax-rule (infix-set! (name p assoc) ...)
  15. (begin-for-syntax (free-identifier-mapping-put! infix-hash
  16. #`name
  17. (cons (syntax->datum #`p)
  18. (syntax->datum #`assoc))) ...))
  19.  
  20.  
  21. (define-for-syntax (get-id-props id)
  22. (free-identifier-mapping-get infix-hash id (λ () #f)))
  23.  
  24.  
  25. (define-syntax (infix stx)
  26. (define-syntax-class op
  27. (pattern x:id
  28. #:when (get-id-props #'x)))
  29.  
  30. (define-splicing-syntax-class l
  31. (pattern (~seq arg op:op)))
  32.  
  33. (define-splicing-syntax-class r
  34. (pattern (~seq l:l r:r)
  35. #:do [(define new-op (attribute l.op))
  36. (define new-op-prior (car (get-id-props (attribute l.op))))
  37. (define new-arg (attribute l.arg))
  38. (define comparator
  39. (case (cdr (get-id-props (attribute l.op)))
  40. [(left) >=]
  41. [(right) >]))
  42. (define-values (ops args)
  43. (let loop ([ops (attribute r.op-stack)]
  44. [args (attribute r.arg-stack)])
  45. (cond
  46. [(null? ops) (values (list (cons new-op new-op-prior)) (cons new-arg args))]
  47. [(comparator new-op-prior (cdar ops))
  48. (values (cons (cons new-op new-op-prior) ops) (cons new-arg args))]
  49. [else (loop (cdr ops) (cons #`(#,(caar ops) #,(first args) #,(second args)) (cddr args)))])))]
  50. #:attr op-stack ops
  51. #:attr arg-stack args)
  52. (pattern x
  53. #:attr op-stack `()
  54. #:attr arg-stack (list #`x)))
  55.  
  56. (syntax-parse stx
  57. [(_ infix-expr:r)
  58. (let loop ([ops (map car (attribute infix-expr.op-stack))]
  59. [args (attribute infix-expr.arg-stack)])
  60. (if (null? ops)
  61. (car args)
  62. (loop (cdr ops) (cons #`(#,(car ops) #,(first args) #,(second args)) (cddr args)))))]
  63. [(_ args ...) #`(args ...)]))
  64.  
  65. (infix-set! (+ 5 left)
  66. (- 5 left)
  67. (* 6 left)
  68. (/ 6 left)
  69. ($ 3 right))
  70.  
  71. (define ($ f x) (f x))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement