/ac.scm

http://github.com/alimoeeny/arc · Scheme · 1509 lines · 1021 code · 292 blank · 196 comment · 0 complexity · bb6de53b704e929ad53e666910dbfaa2 MD5 · raw file

  1. ; Arc Compiler.
  2. (module ac mzscheme
  3. (provide (all-defined))
  4. (require (lib "port.ss"))
  5. (require (lib "process.ss"))
  6. (require (lib "pretty.ss"))
  7. (require (lib "foreign.ss"))
  8. (unsafe!)
  9. (define (ac-global-name s)
  10. (string->symbol (string-append "_" (symbol->string s))))
  11. (define-syntax defarc
  12. (syntax-rules ()
  13. ((defarc (name . args) body ...)
  14. (defarc name (name . args) body ...))
  15. ((defarc arc-name (scheme-name . args) body ...)
  16. (begin
  17. (xdef arc-name (lambda args body ...))
  18. (defarc arc-name scheme-name)))
  19. ((defarc arc-name scheme-name)
  20. (define (scheme-name . args)
  21. (apply (namespace-variable-value (ac-global-name 'arc-name)) args)))
  22. ((defarc name)
  23. (defarc name name))))
  24. ; compile an Arc expression into a Scheme expression,
  25. ; both represented as s-expressions.
  26. ; env is a list of lexically bound variables, which we
  27. ; need in order to decide whether set should create a global.
  28. (defarc (ac s env)
  29. (cond ((string? s) (ac-string s env))
  30. ((literal? s) s)
  31. ((eqv? s 'nil) (list 'quote 'nil))
  32. ((ssyntax? s) (ac (expand-ssyntax s) env))
  33. ((symbol? s) (ac-var-ref s env))
  34. ((ssyntax? (xcar s)) (ac (cons (expand-ssyntax (car s)) (cdr s)) env))
  35. ((eq? (xcar s) '$) (ac-$ (cadr s) env))
  36. ((eq? (xcar s) 'quote) (list 'quote (ac-niltree (cadr s))))
  37. ((eq? (xcar s) 'quasiquote) (ac-qq (cadr s) env))
  38. ((eq? (xcar s) 'if) (ac-if (cdr s) env))
  39. ((eq? (xcar s) 'fn) (ac-fn (cadr s) (cddr s) env))
  40. ((eq? (xcar s) 'assign) (ac-set (cdr s) env))
  41. ; the next three clauses could be removed without changing semantics
  42. ; ... except that they work for macros (so prob should do this for
  43. ; every elt of s, not just the car)
  44. ((eq? (xcar (xcar s)) 'compose) (ac (decompose (cdar s) (cdr s)) env))
  45. ((eq? (xcar (xcar s)) 'complement)
  46. (ac (list 'no (cons (cadar s) (cdr s))) env))
  47. ((eq? (xcar (xcar s)) 'andf) (ac-andf s env))
  48. ((pair? s) (ac-call (car s) (cdr s) env))
  49. (#t (err "Bad object in expression" s))))
  50. (define (ac-string s env)
  51. (if (ar-bflag 'atstrings)
  52. (if (atpos s 0)
  53. (ac (cons 'string (map (lambda (x)
  54. (if (string? x)
  55. (unescape-ats x)
  56. x))
  57. (codestring s)))
  58. env)
  59. (unescape-ats s))
  60. (string-copy s))) ; avoid immutable strings
  61. (defarc ac-literal (literal? x)
  62. (or (boolean? x)
  63. (char? x)
  64. (string? x)
  65. (number? x)
  66. (eq? x '())))
  67. (define (ssyntax? x)
  68. (and (symbol? x)
  69. (not (or (eqv? x '+) (eqv? x '++) (eqv? x '_)))
  70. (let ((name (symbol->string x)))
  71. (has-ssyntax-char? name (- (string-length name) 1)))))
  72. (define (has-ssyntax-char? string i)
  73. (and (>= i 0)
  74. (or (let ((c (string-ref string i)))
  75. (or (eqv? c #\:) (eqv? c #\~)
  76. (eqv? c #\&)
  77. ;(eqv? c #\_)
  78. (eqv? c #\.) (eqv? c #\!)))
  79. (has-ssyntax-char? string (- i 1)))))
  80. (define (read-from-string str)
  81. (let ((port (open-input-string str)))
  82. (let ((val (read port)))
  83. (close-input-port port)
  84. val)))
  85. ; Though graphically the right choice, can't use _ for currying
  86. ; because then _!foo becomes a function. Maybe use <>. For now
  87. ; leave this off and see how often it would have been useful.
  88. ; Might want to make ~ have less precedence than &, because
  89. ; ~foo&bar prob should mean (andf (complement foo) bar), not
  90. ; (complement (andf foo bar)).
  91. (define (expand-ssyntax sym)
  92. ((cond ((or (insym? #\: sym) (insym? #\~ sym)) expand-compose)
  93. ((or (insym? #\. sym) (insym? #\! sym)) expand-sexpr)
  94. ((insym? #\& sym) expand-and)
  95. ; ((insym? #\_ sym) expand-curry)
  96. (#t (error "Unknown ssyntax" sym)))
  97. sym))
  98. (define (expand-compose sym)
  99. (let ((elts (map (lambda (tok)
  100. (if (eqv? (car tok) #\~)
  101. (if (null? (cdr tok))
  102. 'no
  103. `(complement ,(chars->value (cdr tok))))
  104. (chars->value tok)))
  105. (tokens (lambda (c) (eqv? c #\:))
  106. (symbol->chars sym)
  107. '()
  108. '()
  109. #f))))
  110. (if (null? (cdr elts))
  111. (car elts)
  112. (cons 'compose elts))))
  113. (define (expand-and sym)
  114. (let ((elts (map chars->value
  115. (tokens (lambda (c) (eqv? c #\&))
  116. (symbol->chars sym)
  117. '()
  118. '()
  119. #f))))
  120. (if (null? (cdr elts))
  121. (car elts)
  122. (cons 'andf elts))))
  123. ; How to include quoted arguments? Can't treat all as quoted, because
  124. ; never want to quote fn given as first. Do we want to allow quote chars
  125. ; within symbols? Could be ugly.
  126. ; If release, fix the fact that this simply uses v0... as vars. Should
  127. ; make these vars gensyms.
  128. (define (expand-curry sym)
  129. (let ((expr (exc (map (lambda (x)
  130. (if (pair? x) (chars->value x) x))
  131. (tokens (lambda (c) (eqv? c #\_))
  132. (symbol->chars sym)
  133. '()
  134. '()
  135. #t))
  136. 0)))
  137. (list 'fn
  138. (keep (lambda (s)
  139. (and (symbol? s)
  140. (eqv? (string-ref (symbol->string s) 0)
  141. #\v)))
  142. expr)
  143. expr)))
  144. (define (keep f xs)
  145. (cond ((null? xs) '())
  146. ((f (car xs)) (cons (car xs) (keep f (cdr xs))))
  147. (#t (keep f (cdr xs)))))
  148. (define (exc elts n)
  149. (cond ((null? elts)
  150. '())
  151. ((eqv? (car elts) #\_)
  152. (cons (string->symbol (string-append "v" (number->string n)))
  153. (exc (cdr elts) (+ n 1))))
  154. (#t
  155. (cons (car elts) (exc (cdr elts) n)))))
  156. (define (expand-sexpr sym)
  157. (build-sexpr (reverse (tokens (lambda (c) (or (eqv? c #\.) (eqv? c #\!)))
  158. (symbol->chars sym)
  159. '()
  160. '()
  161. #t))
  162. sym))
  163. (define (build-sexpr toks orig)
  164. (cond ((null? toks)
  165. 'get)
  166. ((null? (cdr toks))
  167. (chars->value (car toks)))
  168. (#t
  169. (list (build-sexpr (cddr toks) orig)
  170. (if (eqv? (cadr toks) #\!)
  171. (list 'quote (chars->value (car toks)))
  172. (if (or (eqv? (car toks) #\.) (eqv? (car toks) #\!))
  173. (err "Bad ssyntax" orig)
  174. (chars->value (car toks))))))))
  175. (define (insym? char sym) (member char (symbol->chars sym)))
  176. (define (symbol->chars x) (string->list (symbol->string x)))
  177. (define (chars->value chars) (read-from-string (list->string chars)))
  178. (define (tokens test source token acc keepsep?)
  179. (cond ((null? source)
  180. (reverse (if (pair? token)
  181. (cons (reverse token) acc)
  182. acc)))
  183. ((test (car source))
  184. (tokens test
  185. (cdr source)
  186. '()
  187. (let ((rec (if (null? token)
  188. acc
  189. (cons (reverse token) acc))))
  190. (if keepsep?
  191. (cons (car source) rec)
  192. rec))
  193. keepsep?))
  194. (#t
  195. (tokens test
  196. (cdr source)
  197. (cons (car source) token)
  198. acc
  199. keepsep?))))
  200. (defarc (ac-defined-var? s)
  201. #f)
  202. (define (ac-var-ref s env)
  203. (cond ((lex? s env) s)
  204. ((ac-defined-var? s) (list (ac-global-name s)))
  205. (#t (ac-global-name s))))
  206. ; lowering into mzscheme, with (unquote <foo>) lifting us back into arc
  207. (define (ac-$ args env)
  208. (ac-qqx args
  209. (lambda (x) (ac x env))
  210. (lambda (x) (error 'ac-$ "Can't use ,@ from within $ in: ~a" args))))
  211. ; quasiquote
  212. (define (ac-qq args env)
  213. (list 'quasiquote (ac-qqx args
  214. (lambda (x) (list 'unquote (ac x env)))
  215. (lambda (x) (list 'unquote-splicing
  216. (list 'ar-nil-terminate (ac x env)))))))
  217. ; process the argument of a quasiquote. keep track of
  218. ; depth of nesting. handle unquote only at top level (level = 1).
  219. ; complete form, e.g. x or (fn x) or (unquote (fn x))
  220. (define (ac-qqx x unq splice)
  221. (cond
  222. ((not (pair? x)) x)
  223. ((eqv? (car x) 'unquote) (unq (cadr x)))
  224. ((eqv? (car x) 'unquote-splicing) (splice (cadr x)))
  225. ((eqv? (car x) 'quasiquote)
  226. (list 'quasiquote
  227. (ac-qqx (cadr x)
  228. (lambda (e) (list 'unquote (ac-qqx e unq splice)))
  229. (lambda (e) (list 'unquote-splicing (ac-qqx e unq splice))))))
  230. (#t (imap (lambda (e) (ac-qqx e unq splice)) x))))
  231. ; like map, but don't demand '()-terminated list
  232. (define (imap f l)
  233. (cond ((pair? l)
  234. (cons (f (car l)) (imap f (cdr l))))
  235. ((null? l)
  236. '())
  237. (#t (f l))))
  238. ; (if) -> nil
  239. ; (if x) -> x
  240. ; (if t a ...) -> a
  241. ; (if nil a b) -> b
  242. ; (if nil a b c) -> (if b c)
  243. (define (ac-if args env)
  244. (cond ((null? args) ''nil)
  245. ((null? (cdr args)) (ac (car args) env))
  246. (#t `(if (not (ar-false? ,(ac (car args) env)))
  247. ,(ac (cadr args) env)
  248. ,(ac-if (cddr args) env)))))
  249. (define (ac-dbname! name env)
  250. (if (symbol? name)
  251. (cons (list name) env)
  252. env))
  253. (define (ac-dbname env)
  254. (cond ((null? env) #f)
  255. ((pair? (car env)) (caar env))
  256. (#t (ac-dbname (cdr env)))))
  257. ; translate fn directly into a lambda if it has ordinary
  258. ; parameters, otherwise use a rest parameter and parse it.
  259. (define (ac-fn args body env)
  260. (if (ac-complex-args? args)
  261. (ac-complex-fn args body env)
  262. (ac-nameit
  263. (ac-dbname env)
  264. `(lambda ,(let ((a (ac-denil args))) (if (eqv? a 'nil) '() a))
  265. ,@(ac-body* body (append (ac-arglist args) env))))))
  266. ; does an fn arg list use optional parameters or destructuring?
  267. ; a rest parameter is not complex
  268. (define (ac-complex-args? args)
  269. (cond ((eqv? args '()) #f)
  270. ((symbol? args) #f)
  271. ((and (pair? args) (symbol? (car args)))
  272. (ac-complex-args? (cdr args)))
  273. (#t #t)))
  274. ; translate a fn with optional or destructuring args
  275. ; (fn (x (o y x) (o z 21) (x1 x2) . rest) ...)
  276. ; arguments in top-level list are mandatory (unless optional),
  277. ; but it's OK for parts of a list you're destructuring to
  278. ; be missing.
  279. (define (ac-complex-fn args body env)
  280. (let* ((ra (gensym))
  281. (z (ac-complex-args args env ra #t)))
  282. `(lambda ,ra
  283. (let* ,z
  284. ,@(ac-body* body (append (ac-complex-getargs z) env))))))
  285. ; returns a list of two-element lists, first is variable name,
  286. ; second is (compiled) expression. to be used in a let.
  287. ; caller should extract variables and add to env.
  288. ; ra is the rest argument to the fn.
  289. ; is-params indicates that args are function arguments
  290. ; (not destructuring), so they must be passed or be optional.
  291. (define (ac-complex-args args env ra is-params)
  292. (cond ((or (eqv? args '()) (eqv? args 'nil)) '())
  293. ((symbol? args) (list (list args ra)))
  294. ((pair? args)
  295. (let* ((x (if (and (pair? (car args)) (eqv? (caar args) 'o))
  296. (ac-complex-opt (cadar args)
  297. (if (pair? (cddar args))
  298. (caddar args)
  299. 'nil)
  300. env
  301. ra)
  302. (ac-complex-args
  303. (car args)
  304. env
  305. (if is-params
  306. `(car ,ra)
  307. `(ar-xcar ,ra))
  308. #f)))
  309. (xa (ac-complex-getargs x)))
  310. (append x (ac-complex-args (cdr args)
  311. (append xa env)
  312. `(ar-xcdr ,ra)
  313. is-params))))
  314. (#t (err "Can't understand fn arg list" args))))
  315. ; (car ra) is the argument
  316. ; so it's not present if ra is nil or '()
  317. (define (ac-complex-opt var expr env ra)
  318. (list (list var `(if (pair? ,ra) (car ,ra) ,(ac expr env)))))
  319. ; extract list of variables from list of two-element lists.
  320. (define (ac-complex-getargs a)
  321. (map (lambda (x) (car x)) a))
  322. ; (a b . c) -> (a b c)
  323. ; a -> (a)
  324. (define (ac-arglist a)
  325. (cond ((null? a) '())
  326. ((symbol? a) (list a))
  327. ((symbol? (cdr a)) (list (car a) (cdr a)))
  328. (#t (cons (car a) (ac-arglist (cdr a))))))
  329. (define (ac-body body env)
  330. (map (lambda (x) (ac x env)) body))
  331. ; like ac-body, but spits out a nil expression if empty
  332. (define (ac-body* body env)
  333. (if (null? body)
  334. (list (list 'quote 'nil))
  335. (ac-body body env)))
  336. ; (set v1 expr1 v2 expr2 ...)
  337. (define (ac-set x env)
  338. `(begin ,@(ac-setn x env)))
  339. (define (ac-setn x env)
  340. (if (null? x)
  341. '()
  342. (cons (ac-set1 (ac-macex (car x)) (cadr x) env)
  343. (ac-setn (cddr x) env))))
  344. ; trick to tell Scheme the name of something, so Scheme
  345. ; debugging and profiling make more sense.
  346. (define (ac-nameit name v)
  347. (if (symbol? name)
  348. (let ((n (string->symbol (string-append " " (symbol->string name)))))
  349. (list 'let `((,n ,v)) n))
  350. v))
  351. ; = replaced by set, which is only for vars
  352. ; = now defined in arc (is it?)
  353. ; name is to cause fns to have their arc names for debugging
  354. (define (ac-set1 a b1 env)
  355. (if (symbol? a)
  356. (let ((b (ac b1 (ac-dbname! a env))))
  357. (list 'let `((zz ,b))
  358. (cond ((eqv? a 'nil) (err "Can't rebind nil"))
  359. ((eqv? a 't) (err "Can't rebind t"))
  360. ((lex? a env) `(set! ,a zz))
  361. ((ac-defined-var? a) `(,(ac-global-name a) zz))
  362. (#t `(namespace-set-variable-value! ',(ac-global-name a)
  363. zz)))
  364. 'zz))
  365. (err "First arg to set must be a symbol" a)))
  366. ; given a list of Arc expressions, return a list of Scheme expressions.
  367. ; for compiling passed arguments.
  368. (define (ac-args names exprs env)
  369. (if (null? exprs)
  370. '()
  371. (cons (ac (car exprs)
  372. (ac-dbname! (if (pair? names) (car names) #f) env))
  373. (ac-args (if (pair? names) (cdr names) '())
  374. (cdr exprs)
  375. env))))
  376. ; generate special fast code for ordinary two-operand
  377. ; calls to the following functions. this is to avoid
  378. ; calling e.g. ar-is with its &rest and apply.
  379. (define ac-binaries
  380. '((is ar-is2)
  381. (< ar-<2)
  382. (> ar->2)
  383. (+ ar-+2)))
  384. ; (foo bar) where foo is a global variable bound to a procedure.
  385. (define (ac-global-call fn args env)
  386. (cond ((and (assoc fn ac-binaries) (= (length args) 2))
  387. `(,(cadr (assoc fn ac-binaries)) ,@(ac-args '() args env)))
  388. (#t
  389. `(,(ac-global-name fn) ,@(ac-args '() args env)))))
  390. ; compile a function call
  391. ; special cases for speed, to avoid compiled output like
  392. ; (ar-apply _pr (list 1 2))
  393. ; which results in 1/2 the CPU time going to GC. Instead:
  394. ; (ar-funcall2 _pr 1 2)
  395. ; and for (foo bar), if foo is a reference to a global variable,
  396. ; and it's bound to a function, generate (foo bar) instead of
  397. ; (ar-funcall1 foo bar)
  398. (define (ac-call fn args env)
  399. (let ((macfn (ac-macro? fn)))
  400. (cond (macfn
  401. (ac-mac-call macfn args env))
  402. ((and (pair? fn) (eqv? (car fn) 'fn))
  403. `(,(ac fn env) ,@(ac-args (cadr fn) args env)))
  404. ((and (ar-bflag 'direct-calls) (symbol? fn) (not (lex? fn env)) (bound? fn)
  405. (procedure? (namespace-variable-value (ac-global-name fn))))
  406. (ac-global-call fn args env))
  407. (#t
  408. `((ar-coerce ,(ac fn env) 'fn)
  409. ,@(map (lambda (x) (ac x env)) args))))))
  410. (define (ac-mac-call m args env)
  411. (let ((x1 (apply m (map ac-niltree args))))
  412. (let ((x2 (ac (ac-denil x1) env)))
  413. x2)))
  414. ; returns #f or the macro function
  415. (define (ac-macro? fn)
  416. (if (symbol? fn)
  417. (let ((v (namespace-variable-value (ac-global-name fn)
  418. #t
  419. (lambda () #f))))
  420. (if (and v
  421. (ar-tagged? v)
  422. (eq? (ar-type v) 'mac))
  423. (ar-rep v)
  424. #f))
  425. #f))
  426. ; macroexpand the outer call of a form as much as possible
  427. (define (ac-macex e . once)
  428. (if (pair? e)
  429. (let ((m (ac-macro? (car e))))
  430. (if m
  431. (let ((expansion (ac-denil (apply m (map ac-niltree (cdr e))))))
  432. (if (null? once) (ac-macex expansion) expansion))
  433. e))
  434. e))
  435. ; macros return Arc lists, ending with NIL.
  436. ; but the Arc compiler expects Scheme lists, ending with '().
  437. ; what to do with (is x nil . nil) ?
  438. ; the first nil ought to be replaced with 'NIL
  439. ; the second with '()
  440. ; so the rule is: NIL in the car -> 'NIL, NIL in the cdr -> '().
  441. ; NIL by itself -> NIL
  442. (define (ac-denil x)
  443. (cond ((pair? x) (cons (ac-denil-car (car x)) (ac-denil-cdr (cdr x))))
  444. ((hash-table? x)
  445. (let ((xc (make-hash-table 'equal)))
  446. (hash-table-for-each x
  447. (lambda (k v) (hash-table-put! xc (ac-denil k) (ac-denil v))))
  448. xc))
  449. (#t x)))
  450. (define (ac-denil-car x)
  451. (if (eq? x 'nil)
  452. 'nil
  453. (ac-denil x)))
  454. (define (ac-denil-cdr x)
  455. (if (eq? x 'nil)
  456. '()
  457. (ac-denil x)))
  458. ; is v lexically bound?
  459. (define (lex? v env)
  460. (memq v env))
  461. (define (xcar x)
  462. (and (pair? x) (car x)))
  463. ; #f and '() -> nil for a whole quoted list/tree.
  464. ; Arc primitives written in Scheme should look like:
  465. ; (xdef foo (lambda (lst)
  466. ; (ac-niltree (scheme-foo (ar-nil-terminate lst)))))
  467. ; That is, Arc lists are NIL-terminated. When calling a Scheme
  468. ; function that treats an argument as a list, call ar-nil-terminate
  469. ; to change NIL to '(). When returning any data created by Scheme
  470. ; to Arc, call ac-niltree to turn all '() into NIL.
  471. ; (hash-table-get doesn't use its argument as a list, so it doesn't
  472. ; need ar-nil-terminate).
  473. (define (ac-niltree x)
  474. (cond ((pair? x) (cons (ac-niltree (car x)) (ac-niltree (cdr x))))
  475. ((or (eq? x #f) (eq? x '()) (void? x)) 'nil)
  476. (#t x)))
  477. ; The next two are optimizations, except work for macros.
  478. (define (decompose fns args)
  479. (cond ((null? fns) `((fn vals (car vals)) ,@args))
  480. ((null? (cdr fns)) (cons (car fns) args))
  481. (#t (list (car fns) (decompose (cdr fns) args)))))
  482. (define (ac-andf s env)
  483. (ac (let ((gs (map (lambda (x) (gensym)) (cdr s))))
  484. `((fn ,gs
  485. (and ,@(map (lambda (f) `(,f ,@gs))
  486. (cdar s))))
  487. ,@(cdr s)))
  488. env))
  489. (define err error)
  490. ; run-time primitive procedures
  491. ;(define (xdef a b)
  492. ; (namespace-set-variable-value! (ac-global-name a) b)
  493. ; b)
  494. (define-syntax xdef
  495. (syntax-rules ()
  496. ((xxdef a b)
  497. (let ((nm (ac-global-name 'a))
  498. (a b))
  499. (namespace-set-variable-value! nm a)
  500. a))))
  501. (define fn-signatures (make-hash-table 'equal))
  502. ; This is a replacement for xdef that stores opeator signatures.
  503. ; Haven't started using it yet.
  504. (define (odef a parms b)
  505. (namespace-set-variable-value! (ac-global-name a) b)
  506. (hash-table-put! fn-signatures a (list parms))
  507. b)
  508. (xdef sig fn-signatures)
  509. ; versions of car and cdr for parsing arguments for optional
  510. ; parameters, that yield nil for nil. maybe we should use
  511. ; full Arc car and cdr, so we can destructure more things
  512. (define (ar-xcar x)
  513. (if (or (eqv? x 'nil) (eqv? x '()))
  514. 'nil
  515. (car x)))
  516. (define (ar-xcdr x)
  517. (if (or (eqv? x 'nil) (eqv? x '()))
  518. 'nil
  519. (cdr x)))
  520. ; convert #f from a Scheme predicate to NIL.
  521. (define (ar-nill x)
  522. (if (or (eq? x '()) (eq? x #f))
  523. 'nil
  524. x))
  525. ; definition of falseness for Arc if.
  526. ; must include '() since sometimes Arc functions see
  527. ; Scheme lists (e.g. . body of a macro).
  528. (define (ar-false? x)
  529. (or (eq? x 'nil) (eq? x '()) (eq? x #f)))
  530. ; call a function or perform an array ref, hash ref, &c
  531. ; Non-fn constants in functional position are valuable real estate, so
  532. ; should figure out the best way to exploit it. What could (1 foo) or
  533. ; ('a foo) mean? Maybe it should mean currying.
  534. ; For now the way to make the default val of a hash table be other than
  535. ; nil is to supply the val when doing the lookup. Later may also let
  536. ; defaults be supplied as an arg to table. To implement this, need: an
  537. ; eq table within scheme mapping tables to defaults, and to adapt the
  538. ; code in arc.arc that reads and writes tables to read and write their
  539. ; default vals with them. To make compatible with existing written tables,
  540. ; just use an atom or 3-elt list to keep the default.
  541. (define (ar-apply fn args)
  542. (apply (ar-coerce fn 'fn) args))
  543. (xdef apply (lambda (fn . args)
  544. (ar-apply fn (ar-apply-args args))))
  545. ; replace the nil at the end of a list with a '()
  546. (define (ar-nil-terminate l)
  547. (if (or (eqv? l '()) (eqv? l 'nil))
  548. '()
  549. (cons (car l) (ar-nil-terminate (cdr l)))))
  550. ; turn the arguments to Arc apply into a list.
  551. ; if you call (apply fn 1 2 '(3 4))
  552. ; then args is '(1 2 (3 4 . nil) . ())
  553. ; that is, the main list is a scheme list.
  554. ; and we should return '(1 2 3 4 . ())
  555. ; was once (apply apply list (ac-denil args))
  556. ; but that didn't work for (apply fn nil)
  557. (define (ar-apply-args args)
  558. (cond ((null? args) '())
  559. ((null? (cdr args)) (ar-nil-terminate (car args)))
  560. (#t (cons (car args) (ar-apply-args (cdr args))))))
  561. (xdef cons cons)
  562. (xdef car (lambda (x)
  563. (cond ((pair? x) (car x))
  564. ((eqv? x 'nil) 'nil)
  565. ((eqv? x '()) 'nil)
  566. (#t (err "Can't take car of" x)))))
  567. (xdef cdr (lambda (x)
  568. (cond ((pair? x) (cdr x))
  569. ((eqv? x 'nil) 'nil)
  570. ((eqv? x '()) 'nil)
  571. (#t (err "Can't take cdr of" x)))))
  572. (define (tnil x) (if x 't 'nil))
  573. ; (pairwise pred '(a b c d)) =>
  574. ; (and (pred a b) (pred b c) (pred c d))
  575. ; pred returns t/nil, as does pairwise
  576. ; reduce?
  577. (define (pairwise pred lst)
  578. (cond ((null? lst) 't)
  579. ((null? (cdr lst)) 't)
  580. ((not (eqv? (pred (car lst) (cadr lst)) 'nil))
  581. (pairwise pred (cdr lst)))
  582. (#t 'nil)))
  583. ; not quite right, because behavior of underlying eqv unspecified
  584. ; in many cases according to r5rs
  585. ; do we really want is to ret t for distinct strings?
  586. ; for (is x y)
  587. (define (ar-is2 a b)
  588. (tnil (or (eqv? a b)
  589. (and (string? a) (string? b) (string=? a b))
  590. (and (ar-false? a) (ar-false? b)))))
  591. ; for all other uses of is
  592. (xdef is (lambda args (pairwise ar-is2 args)))
  593. (xdef err err)
  594. (xdef nil 'nil)
  595. (xdef t 't)
  596. (define (all test seq)
  597. (or (null? seq)
  598. (and (test (car seq)) (all test (cdr seq)))))
  599. (define (arc-list? x) (or (pair? x) (eqv? x 'nil) (eqv? x '())))
  600. ; Generic +: strings, lists, numbers.
  601. ; Return val has same type as first argument.
  602. (xdef + (lambda args
  603. (cond ((null? args) 0)
  604. ((char-or-string? (car args))
  605. (apply string-append
  606. (map (lambda (a) (ar-coerce a 'string))
  607. args)))
  608. ((arc-list? (car args))
  609. (ac-niltree (apply append (map ar-nil-terminate args))))
  610. (#t (apply + args)))))
  611. (define (char-or-string? x) (or (string? x) (char? x)))
  612. (define (ar-+2 x y)
  613. (cond ((char-or-string? x)
  614. (string-append (ar-coerce x 'string) (ar-coerce y 'string)))
  615. ((and (arc-list? x) (arc-list? y))
  616. (ac-niltree (append (ar-nil-terminate x) (ar-nil-terminate y))))
  617. (#t (+ x y))))
  618. (xdef - -)
  619. (xdef * *)
  620. (xdef / /)
  621. (xdef mod modulo)
  622. (xdef expt expt)
  623. (xdef sqrt sqrt)
  624. ; generic comparison
  625. (define (ar->2 x y)
  626. (tnil (cond ((and (number? x) (number? y)) (> x y))
  627. ((and (string? x) (string? y)) (string>? x y))
  628. ((and (symbol? x) (symbol? y)) (string>? (symbol->string x)
  629. (symbol->string y)))
  630. ((and (char? x) (char? y)) (char>? x y))
  631. (#t (> x y)))))
  632. (xdef > (lambda args (pairwise ar->2 args)))
  633. (define (ar-<2 x y)
  634. (tnil (cond ((and (number? x) (number? y)) (< x y))
  635. ((and (string? x) (string? y)) (string<? x y))
  636. ((and (symbol? x) (symbol? y)) (string<? (symbol->string x)
  637. (symbol->string y)))
  638. ((and (char? x) (char? y)) (char<? x y))
  639. (#t (< x y)))))
  640. (xdef < (lambda args (pairwise ar-<2 args)))
  641. (xdef len (lambda (x)
  642. (cond ((string? x) (string-length x))
  643. ((hash-table? x) (hash-table-count x))
  644. (#t (length (ar-nil-terminate x))))))
  645. (define (ar-tagged? x)
  646. (and (vector? x) (eq? (vector-ref x 0) 'tagged)))
  647. (define (ar-tag type rep)
  648. (cond ((eqv? (ar-type rep) type) rep)
  649. (#t (vector 'tagged type rep))))
  650. (xdef annotate ar-tag)
  651. ; (type nil) -> sym
  652. (define (exint? x) (and (integer? x) (exact? x)))
  653. (define (ar-type x)
  654. (cond ((ar-tagged? x) (vector-ref x 1))
  655. ((pair? x) 'cons)
  656. ((symbol? x) 'sym)
  657. ((null? x) 'sym)
  658. ((procedure? x) 'fn)
  659. ((char? x) 'char)
  660. ((string? x) 'string)
  661. ((exint? x) 'int)
  662. ((number? x) 'num) ; unsure about this
  663. ((hash-table? x) 'table)
  664. ((output-port? x) 'output)
  665. ((input-port? x) 'input)
  666. ((tcp-listener? x) 'socket)
  667. ((exn? x) 'exception)
  668. ((thread? x) 'thread)
  669. ((thread-cell? x) 'thread-cell)
  670. (#t (err "Type: unknown type" x))))
  671. (xdef type ar-type)
  672. (define (ar-rep x)
  673. (if (ar-tagged? x)
  674. (vector-ref x 2)
  675. x))
  676. (xdef rep ar-rep)
  677. (xdef uniq gensym)
  678. (xdef ccc call-with-current-continuation)
  679. (xdef infile open-input-file)
  680. (xdef outfile (lambda (f . args)
  681. (open-output-file f
  682. 'text
  683. (if (equal? args '(append))
  684. 'append
  685. 'truncate))))
  686. (xdef instring open-input-string)
  687. (xdef outstring open-output-string)
  688. ; use as general fn for looking inside things
  689. (xdef inside get-output-string)
  690. (xdef stdout current-output-port) ; should be a vars
  691. (xdef stdin current-input-port)
  692. (xdef stderr current-error-port)
  693. (xdef call-w/stdout
  694. (lambda (port thunk)
  695. (parameterize ((current-output-port port)) (thunk))))
  696. (xdef call-w/stdin
  697. (lambda (port thunk)
  698. (parameterize ((current-input-port port)) (thunk))))
  699. (xdef readc (lambda str
  700. (let ((c (read-char (if (pair? str)
  701. (car str)
  702. (current-input-port)))))
  703. (if (eof-object? c) 'nil c))))
  704. (xdef readchars (lambda (n . str)
  705. (let ((cs (read-string n (if (pair? str)
  706. (car str)
  707. (current-input-port)))))
  708. (if (eof-object? cs) 'nil (string->list cs)))))
  709. (xdef readb (lambda str
  710. (let ((c (read-byte (if (pair? str)
  711. (car str)
  712. (current-input-port)))))
  713. (if (eof-object? c) 'nil c))))
  714. (xdef readbytes (lambda (n . str)
  715. (let ((bs (read-bytes n (if (pair? str)
  716. (car str)
  717. (current-input-port)))))
  718. (if (eof-object? bs) 'nil (bytes->list bs)))))
  719. (xdef peekc (lambda str
  720. (let ((c (peek-char (if (pair? str)
  721. (car str)
  722. (current-input-port)))))
  723. (if (eof-object? c) 'nil c))))
  724. (xdef writec (lambda (c . args)
  725. (write-char c
  726. (if (pair? args)
  727. (car args)
  728. (current-output-port)))
  729. c))
  730. (xdef writeb (lambda (b . args)
  731. (write-byte b
  732. (if (pair? args)
  733. (car args)
  734. (current-output-port)))
  735. b))
  736. (define (printwith f args)
  737. (let ((port (if (> (length args) 1)
  738. (cadr args)
  739. (current-output-port))))
  740. (when (pair? args)
  741. (f (ac-denil (car args)) port))
  742. (unless (ar-bflag 'explicit-flush)
  743. (flush-output port)))
  744. 'nil)
  745. (defarc write (arc-write . args) (printwith write args))
  746. (xdef disp (lambda args (printwith display args)))
  747. ; sread = scheme read. eventually replace by writing read
  748. (xdef sread (lambda (p eof)
  749. (let ((expr (read p)))
  750. (if (eof-object? expr) eof expr))))
  751. ; these work in PLT but not scheme48
  752. (define char->ascii char->integer)
  753. (define ascii->char integer->char)
  754. (define (iround x) (inexact->exact (round x)))
  755. ; look up first by target type, then by source type
  756. (define coercions (make-hash-table 'equal))
  757. (for-each (lambda (e)
  758. (let ((target-type (car e))
  759. (conversions (make-hash-table 'equal)))
  760. (hash-table-put! coercions target-type conversions)
  761. (for-each
  762. (lambda (x) (hash-table-put! conversions (car x) (cadr x)))
  763. (cdr e))))
  764. `((fn (cons ,(lambda (l) (lambda (i) (list-ref l i))))
  765. (string ,(lambda (s) (lambda (i) (string-ref s i))))
  766. (table ,(lambda (h) (case-lambda
  767. ((k) (hash-table-get h k 'nil))
  768. ((k d) (hash-table-get h k d))))))
  769. (string (int ,number->string)
  770. (num ,number->string)
  771. (char ,string)
  772. (cons ,(lambda (l) (apply string-append
  773. (map (lambda (y) (ar-coerce y 'string))
  774. (ar-nil-terminate l)))))
  775. (sym ,(lambda (x) (if (eqv? x 'nil) "" (symbol->string x)))))
  776. (sym (string ,string->symbol)
  777. (char ,(lambda (c) (string->symbol (string c)))))
  778. (int (char ,(lambda (c . args) (char->ascii c)))
  779. (num ,(lambda (x . args) (iround x)))
  780. (string ,(lambda (x . args)
  781. (let ((n (apply string->number x args)))
  782. (if n (iround n)
  783. (err "Can't coerce " x 'int))))))
  784. (num (string ,(lambda (x . args)
  785. (or (apply string->number x args)
  786. (err "Can't coerce " x 'num))))
  787. (int ,(lambda (x) x)))
  788. (cons (string ,(lambda (x) (ac-niltree (string->list x)))))
  789. (char (int ,ascii->char)
  790. (num ,(lambda (x) (ascii->char (iround x)))))))
  791. (define (ar-coerce x type . args)
  792. (let ((x-type (ar-type x)))
  793. (if (eqv? type x-type) x
  794. (let* ((fail (lambda () (err "Can't coerce " x type)))
  795. (conversions (hash-table-get coercions type fail))
  796. (converter (hash-table-get conversions x-type fail)))
  797. (ar-apply converter (cons x args))))))
  798. (xdef coerce ar-coerce)
  799. (xdef coerce* coercions)
  800. (xdef parameter make-parameter)
  801. (xdef parameterize-sub
  802. (lambda (var val thunk)
  803. (parameterize ((var val)) (thunk))))
  804. (xdef open-socket (lambda (num) (tcp-listen num 50 #t)))
  805. (define (ar-init-socket init-fn . args)
  806. (let ((oc (current-custodian))
  807. (nc (make-custodian)))
  808. (current-custodian nc)
  809. (apply
  810. (lambda (in out . tail)
  811. (current-custodian oc)
  812. (associate-custodian nc in out)
  813. (list* in out tail))
  814. (call-with-values
  815. init-fn
  816. (if (pair? args)
  817. (car args)
  818. list)))))
  819. ; the 2050 means http requests currently capped at 2 meg
  820. ; http://list.cs.brown.edu/pipermail/plt-scheme/2005-August/009414.html
  821. (xdef socket-accept (lambda (s)
  822. (ar-init-socket
  823. (lambda () (tcp-accept s))
  824. (lambda (in out)
  825. (list (make-limited-input-port in 100000 #t)
  826. out
  827. (let-values (((us them) (tcp-addresses out)))
  828. them))))))
  829. (xdef socket-connect (lambda (host port)
  830. (ar-init-socket
  831. (lambda () (tcp-connect host port)))))
  832. ; allow Arc to give up root privileges after it
  833. ; calls open-socket. thanks, Eli!
  834. (define setuid (get-ffi-obj 'setuid #f (_fun _int -> _int)))
  835. (xdef setuid setuid)
  836. (xdef new-thread thread)
  837. (xdef current-thread current-thread)
  838. (define (wrapnil f) (lambda args (apply f args) 'nil))
  839. (xdef sleep (wrapnil sleep))
  840. ; Will system "execute" a half-finished string if thread killed
  841. ; in the middle of generating it?
  842. (xdef system (lambda (s) (tnil (system s))))
  843. (xdef pipe-from (lambda (cmd)
  844. (let ((tf (ar-tmpname)))
  845. (system (string-append cmd " > " tf))
  846. (let ((str (open-input-file tf)))
  847. (system (string-append "rm -f " tf))
  848. str))))
  849. (define (ar-tmpname)
  850. (call-with-input-file "/dev/urandom"
  851. (lambda (rstr)
  852. (do ((s "/tmp/")
  853. (c (read-char rstr) (read-char rstr))
  854. (i 0 (+ i 1)))
  855. ((>= i 16) s)
  856. (set! s (string-append s
  857. (string
  858. (integer->char
  859. (+ (char->integer #\a)
  860. (modulo
  861. (char->integer (read-char rstr))
  862. 26))))))))))
  863. ; PLT scheme provides only eq? and equal? hash tables,
  864. ; we need the latter for strings.
  865. (xdef table (lambda args
  866. (let ((h (make-hash-table 'equal)))
  867. (if (pair? args) ((car args) h))
  868. h)))
  869. ;(xdef table (lambda args
  870. ; (fill-table (make-hash-table 'equal)
  871. ; (if (pair? args) (ac-denil (car args)) '()))))
  872. (define (fill-table h pairs)
  873. (if (eq? pairs '())
  874. h
  875. (let ((pair (car pairs)))
  876. (begin (hash-table-put! h (car pair) (cadr pair))
  877. (fill-table h (cdr pairs))))))
  878. (xdef maptable (lambda (fn table) ; arg is (fn (key value) ...)
  879. (hash-table-for-each table fn)
  880. table))
  881. (define (protect during after)
  882. (dynamic-wind (lambda () #t) during after))
  883. (xdef protect protect)
  884. ; need to use a better seed
  885. (xdef rand random)
  886. (xdef dir (lambda (name)
  887. (ac-niltree (map path->string (directory-list name)))))
  888. ; Would def mkdir in terms of make-directory and call that instead
  889. ; of system in ensure-dir, but make-directory is too weak: it doesn't
  890. ; create intermediate directories like mkdir -p.
  891. (xdef file-exists (lambda (name)
  892. (if (file-exists? name) name 'nil)))
  893. (xdef dir-exists (lambda (name)
  894. (if (directory-exists? name) name 'nil)))
  895. (xdef rmfile (wrapnil delete-file))
  896. (xdef mvfile (lambda (old new)
  897. (rename-file-or-directory old new #t)
  898. 'nil))
  899. ; top level read-eval-print
  900. ; tle kept as a way to get a break loop when a scheme err
  901. (define (arc-eval expr)
  902. (eval (ac expr '())))
  903. (define (tle)
  904. (display "Arc> ")
  905. (let ((expr (read)))
  906. (when (not (eqv? expr ':a))
  907. (write (arc-eval expr))
  908. (newline)
  909. (tle))))
  910. (define last-condition* #f)
  911. (define (tl)
  912. (let ((interactive? (terminal-port? (current-input-port))))
  913. (when interactive?
  914. (display "Use (quit) or ^D to quit, (tl) to return here after an interrupt.\n"))
  915. (tl2 interactive?)))
  916. (define (tl2 interactive?)
  917. (when interactive? (display "arc> "))
  918. (on-err (lambda (c)
  919. (set! last-condition* c)
  920. (parameterize ((current-output-port (current-error-port)))
  921. (display "Error: ")
  922. (write (exn-message c))
  923. (newline)
  924. (tl2 interactive?)))
  925. (lambda ()
  926. (let ((expr (read)))
  927. (if (eof-object? expr)
  928. (begin (when interactive? (newline))
  929. (exit)))
  930. (if (eqv? expr ':a)
  931. 'done
  932. (let ((val (arc-eval expr)))
  933. (when interactive?
  934. (arc-write (ac-denil val))
  935. (newline))
  936. (namespace-set-variable-value! '_that val)
  937. (namespace-set-variable-value! '_thatexpr expr)
  938. (tl2 interactive?)))))))
  939. (define (aload1 p)
  940. (let ((x (read p)))
  941. (if (eof-object? x)
  942. #t
  943. (begin
  944. (arc-eval x)
  945. (aload1 p)))))
  946. (define (atests1 p)
  947. (let ((x (read p)))
  948. (if (eof-object? x)
  949. #t
  950. (begin
  951. (write x)
  952. (newline)
  953. (let ((v (arc-eval x)))
  954. (if (ar-false? v)
  955. (begin
  956. (display " FAILED")
  957. (newline))))
  958. (atests1 p)))))
  959. (define (aload filename)
  960. (call-with-input-file filename aload1))
  961. (define (test filename)
  962. (call-with-input-file filename atests1))
  963. (define (acompile1 ip op)
  964. (let ((x (read ip)))
  965. (if (eof-object? x)
  966. #t
  967. (let ((scm (ac x '())))
  968. (eval scm)
  969. (pretty-print scm op)
  970. (newline op)
  971. (newline op)
  972. (acompile1 ip op)))))
  973. ; compile xx.arc to xx.arc.scm
  974. ; useful to examine the Arc compiler output
  975. (define (acompile inname)
  976. (let ((outname (string-append inname ".scm")))
  977. (if (file-exists? outname)
  978. (delete-file outname))
  979. (call-with-input-file inname
  980. (lambda (ip)
  981. (call-with-output-file outname
  982. (lambda (op)
  983. (acompile1 ip op)))))))
  984. (xdef macex (lambda (e) (ac-macex (ac-denil e))))
  985. (xdef macex1 (lambda (e) (ac-macex (ac-denil e) 'once)))
  986. (xdef eval (lambda (e)
  987. (eval (ac (ac-denil e) '()))))
  988. ; If an err occurs in an on-err expr, no val is returned and code
  989. ; after it doesn't get executed. Not quite what I had in mind.
  990. (define (on-err errfn f)
  991. ((call-with-current-continuation
  992. (lambda (k)
  993. (lambda ()
  994. (with-handlers ((exn:fail? (lambda (c)
  995. (k (lambda () (errfn c))))))
  996. (f)))))))
  997. (xdef on-err on-err)
  998. (define (disp-to-string x)
  999. (let ((o (open-output-string)))
  1000. (display x o)
  1001. (close-output-port o)
  1002. (get-output-string o)))
  1003. (xdef details (lambda (c)
  1004. (disp-to-string (exn-message c))))
  1005. (xdef scar (lambda (x val)
  1006. (if (string? x)
  1007. (string-set! x 0 val)
  1008. (x-set-car! x val))
  1009. val))
  1010. (xdef scdr (lambda (x val)
  1011. (if (string? x)
  1012. (err "Can't set cdr of a string" x)
  1013. (x-set-cdr! x val))
  1014. val))
  1015. ; decide at run-time whether the underlying mzscheme supports
  1016. ; set-car! and set-cdr!, since I can't figure out how to do it
  1017. ; at compile time.
  1018. (define (x-set-car! p v)
  1019. (let ((fn (namespace-variable-value 'set-car! #t (lambda () #f))))
  1020. (if (procedure? fn)
  1021. (fn p v)
  1022. (n-set-car! p v))))
  1023. (define (x-set-cdr! p v)
  1024. (let ((fn (namespace-variable-value 'set-cdr! #t (lambda () #f))))
  1025. (if (procedure? fn)
  1026. (fn p v)
  1027. (n-set-cdr! p v))))
  1028. ; Eli's code to modify mzscheme-4's immutable pairs.
  1029. ;; to avoid a malloc on every call, reuse a single pointer, but make
  1030. ;; it thread-local to avoid races
  1031. (define ptr (make-thread-cell #f))
  1032. (define (get-ptr)
  1033. (or (thread-cell-ref ptr)
  1034. (let ([p (malloc _scheme 1)]) (thread-cell-set! ptr p) p)))
  1035. ;; set a pointer to the cons cell, then dereference it as a pointer,
  1036. ;; and bang the new value in the given offset
  1037. (define (set-ca/dr! offset who p x)
  1038. (if (pair? p)
  1039. (let ([p* (get-ptr)])
  1040. (ptr-set! p* _scheme p)
  1041. (ptr-set! (ptr-ref p* _pointer 0) _scheme offset x))
  1042. (raise-type-error who "pair" p)))
  1043. (define (n-set-car! p x) (set-ca/dr! 1 'set-car! p x))
  1044. (define (n-set-cdr! p x) (set-ca/dr! 2 'set-cdr! p x))
  1045. ; When and if cdr of a string returned an actual (eq) tail, could
  1046. ; say (if (string? x) (string-replace! x val 1) ...) in scdr, but
  1047. ; for now would be misleading to allow this, because fails for cddr.
  1048. (define (string-replace! str val index)
  1049. (if (eqv? (string-length val) (- (string-length str) index))
  1050. (do ((i index (+ i 1)))
  1051. ((= i (string-length str)) str)
  1052. (string-set! str i (string-ref val (- i index))))
  1053. (err "Length mismatch between strings" str val index)))
  1054. ; Later may want to have multiple indices.
  1055. (xdef sref
  1056. (lambda (com val ind)
  1057. (cond ((hash-table? com) (if (eqv? val 'nil)
  1058. (hash-table-remove! com ind)
  1059. (hash-table-put! com ind val)))
  1060. ((string? com) (string-set! com ind val))
  1061. ((pair? com) (nth-set! com ind val))
  1062. (#t (err "Can't set reference " com ind val)))
  1063. val))
  1064. (define (nth-set! lst n val)
  1065. (x-set-car! (list-tail lst n) val))
  1066. ; rewrite to pass a (true) gensym instead of #f in case var bound to #f
  1067. (define (bound? arcname)
  1068. (namespace-variable-value (ac-global-name arcname)
  1069. #t
  1070. (lambda () #f)))
  1071. (xdef bound (lambda (x) (tnil (bound? x))))
  1072. (xdef newstring make-string)
  1073. (xdef trunc (lambda (x) (inexact->exact (truncate x))))
  1074. ; bad name
  1075. (xdef exact (lambda (x) (tnil (exint? x))))
  1076. (xdef msec current-milliseconds)
  1077. (xdef current-process-milliseconds current-process-milliseconds)
  1078. (xdef current-gc-milliseconds current-gc-milliseconds)
  1079. (xdef seconds current-seconds)
  1080. (print-hash-table #t)
  1081. (xdef client-ip (lambda (port)
  1082. (let-values (((x y) (tcp-addresses port)))
  1083. y)))
  1084. ; make sure only one thread at a time executes anything
  1085. ; inside an atomic-invoke. atomic-invoke is allowed to
  1086. ; nest within a thread; the thread-cell keeps track of
  1087. ; whether this thread already holds the lock.
  1088. (define ar-atomic-sema (make-semaphore 1))
  1089. (define ar-atomic-cell (make-thread-cell #f))
  1090. (xdef atomic-invoke (lambda (f)
  1091. (if (thread-cell-ref ar-atomic-cell)
  1092. (ar-apply f '())
  1093. (begin
  1094. (thread-cell-set! ar-atomic-cell #t)
  1095. (protect
  1096. (lambda ()
  1097. (call-with-semaphore
  1098. ar-atomic-sema
  1099. (lambda () (ar-apply f '()))))
  1100. (lambda ()
  1101. (thread-cell-set! ar-atomic-cell #f)))))))
  1102. (xdef dead (lambda (x) (tnil (thread-dead? x))))
  1103. ; Added because Mzscheme buffers output. Not a permanent part of Arc.
  1104. ; Only need to use when declare explicit-flush optimization.
  1105. (xdef flushout (lambda args (flush-output (if (pair? args)
  1106. (car args)
  1107. (current-output-port)))
  1108. 't))
  1109. (xdef ssyntax (lambda (x) (tnil (ssyntax? x))))
  1110. (xdef ssexpand (lambda (x)
  1111. (if (symbol? x) (expand-ssyntax x) x)))
  1112. (xdef quit exit)
  1113. ; there are two ways to close a TCP output port.
  1114. ; (close o) waits for output to drain, then closes UNIX descriptor.
  1115. ; (force-close o) discards buffered output, then closes UNIX desc.
  1116. ; web servers need the latter to get rid of connections to
  1117. ; clients that are not reading data.
  1118. ; mzscheme close-output-port doesn't work (just raises an error)
  1119. ; if there is buffered output for a non-responsive socket.
  1120. ; must use custodian-shutdown-all instead.
  1121. (define custodians (make-hash-table 'equal))
  1122. (define (associate-custodian c i o)
  1123. (hash-table-put! custodians i c)
  1124. (hash-table-put! custodians o c))
  1125. ; if a port has a custodian, use it to close the port forcefully.
  1126. ; also get rid of the reference to the custodian.
  1127. ; sadly doing this to the input port also kills the output port.
  1128. (define (try-custodian p)
  1129. (let ((c (hash-table-get custodians p #f)))
  1130. (if c
  1131. (begin
  1132. (custodian-shutdown-all c)
  1133. (hash-table-remove! custodians p)
  1134. #t)
  1135. #f)))
  1136. (define (ar-close . args)
  1137. (map (lambda (p)
  1138. (cond ((input-port? p) (close-input-port p))
  1139. ((output-port? p) (close-output-port p))
  1140. ((tcp-listener? p) (tcp-close p))
  1141. (#t (err "Can't close " p))))
  1142. args)
  1143. (map (lambda (p) (try-custodian p)) args) ; free any custodian
  1144. 'nil)
  1145. (xdef close ar-close)
  1146. (xdef force-close (lambda args
  1147. (map (lambda (p)
  1148. (if (not (try-custodian p))
  1149. (ar-close p)))
  1150. args)
  1151. 'nil))
  1152. (xdef memory current-memory-use)
  1153. (define ar-declarations (make-hash-table))
  1154. (define (ar-bflag key)
  1155. (not (ar-false? (hash-table-get ar-declarations key 'nil))))
  1156. (xdef declarations* ar-declarations)
  1157. (putenv "TZ" ":GMT")
  1158. (define (gmt-date sec) (seconds->date sec))
  1159. (xdef timedate
  1160. (lambda args
  1161. (let ((d (gmt-date (if (pair? args) (car args) (current-seconds)))))
  1162. (ac-niltree (list (date-second d)
  1163. (date-minute d)
  1164. (date-hour d)
  1165. (date-day d)
  1166. (date-month d)
  1167. (date-year d))))))
  1168. (xdef utf-8-bytes
  1169. (lambda (str)
  1170. (bytes->list (string->bytes/utf-8 str))))
  1171. (xdef sin sin)
  1172. (xdef cos cos)
  1173. (xdef tan tan)
  1174. (xdef asin asin)
  1175. (xdef acos acos)
  1176. (xdef atan atan)
  1177. (xdef log log)
  1178. (xdef lor bitwise-ior)
  1179. (xdef land bitwise-and)
  1180. (xdef lxor bitwise-xor)
  1181. (xdef lnot bitwise-not)
  1182. (xdef shl arithmetic-shift)
  1183. (define (codestring s)
  1184. (let ((i (atpos s 0)))
  1185. (if i
  1186. (cons (substring s 0 i)
  1187. (let* ((rest (substring s (+ i 1)))
  1188. (in (open-input-string rest))
  1189. (expr (read in))
  1190. (i2 (let-values (((x y z) (port-next-location in))) z)))
  1191. (close-input-port in)
  1192. (cons expr (codestring (substring rest (- i2 1))))))
  1193. (list s))))
  1194. ; First unescaped @ in s, if any. Escape by doubling.
  1195. (define (atpos s i)
  1196. (cond ((eqv? i (string-length s))
  1197. #f)
  1198. ((eqv? (string-ref s i) #\@)
  1199. (if (and (< (+ i 1) (string-length s))
  1200. (not (eqv? (string-ref s (+ i 1)) #\@)))
  1201. i
  1202. (atpos s (+ i 2))))
  1203. (#t
  1204. (atpos s (+ i 1)))))
  1205. (define (unescape-ats s)
  1206. (list->string (letrec ((unesc (lambda (cs)
  1207. (cond
  1208. ((null? cs)
  1209. '())
  1210. ((and (eqv? (car cs) #\@)
  1211. (not (null? (cdr cs)))
  1212. (eqv? (cadr cs) #\@))
  1213. (unesc (cdr cs)))
  1214. (#t
  1215. (cons (car cs) (unesc (cdr cs))))))))
  1216. (unesc (string->list s)))))
  1217. )