Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
1972 lines (1459 loc) · 74.3 KB
/
Copy path__init__.py
File metadata and controls
1972 lines (1459 loc) · 74.3 KB
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""unpythonic.syntax: Toto, I've a feeling we're not in Python anymore.
Requires MacroPy (package ``macropy3`` on PyPI).
"""
# This module contains the macro interface and docstrings; the submodules
# contain the actual syntax transformers (regular functions that process ASTs)
# that implement the macros.
# insist, deny, it, f, _, force, force1, local, delete, block, expr, dbgprint_block, dbgprint_expr, call_cc
# are just for passing through to the client code that imports us.
from .autoref import autoref as _autoref
from .curry import curry as _curry
from .forall import forall as _forall, insist, deny
from .ifexprs import aif as _aif, it, cond as _cond
from .lambdatools import multilambda as _multilambda, \
namedlambda as _namedlambda, \
quicklambda as _quicklambda, f, _, \
envify as _envify
from .lazify import lazify as _lazify, lazyrec as _lazyrec, force, force1
from .letdo import do as _do, do0 as _do0, local, delete, \
let as _let, letseq as _letseq, letrec as _letrec, \
dlet as _dlet, dletseq as _dletseq, dletrec as _dletrec, \
blet as _blet, bletseq as _bletseq, bletrec as _bletrec
from .letsyntax import let_syntax_expr, let_syntax_block, block, expr
from .nb import nb as _nb
from .dbg import dbg_block as _dbg_block, dbg_expr as _dbg_expr, \
dbgprint_block, dbgprint_expr
from .prefix import prefix as _prefix
from .tailtools import autoreturn as _autoreturn, tco as _tco, \
continuations as _continuations, call_cc
# "where" is only for passing through.
from .letdoutil import UnexpandedLetView, _canonize_bindings, where
from ..dynassign import dyn, make_dynvar
from macropy.core.macros import Macros
macros = Macros()
# Inject default debug printer for expressions.
#
# All the macro interface stuff must happen in this module, so we can't
# decorate the original directly in the implementation module.
dbgprint_expr = macros.expose_unhygienic(dbgprint_expr)
# We pass gen_sym as a dynvar so it doesn't need to appear in the
# formal parameter lists of the underlying syntax transformers.
#
# If you add new macros, use ``with dyn.let(gen_sym=gen_sym):`` if your
# syntax transformer (or any syntax transformers it calls) needs gen_sym.
# This default is here to yell if it's needed and missing; the traceback
# will tell exactly which syntax transformer needed it.
def nogensym(*args, **kwargs):
raise RuntimeError("No gen_sym function set")
make_dynvar(gen_sym=nogensym)
# -----------------------------------------------------------------------------
@macros.block
def autoref(tree, args, *, target, gen_sym, **kw):
"""Implicitly reference attributes of an object.
Example::
e = env(a=1, b=2)
c = 3
with autoref(e):
a
b
c
The transformation is applied in ``Load`` context only. ``Store`` and ``Del``
are not redirected.
Useful e.g. with the ``.mat`` file loader of SciPy.
"""
with dyn.let(gen_sym=gen_sym):
return _autoref(block_body=tree, args=args, asname=target)
# -----------------------------------------------------------------------------
@macros.expr
def aif(tree, *, gen_sym, **kw):
"""[syntax, expr] Anaphoric if.
Usage::
aif[test, then, otherwise]
aif[[pre, ..., test],
[post_true, ..., then], # "then" branch
[post_false, ..., otherwise]] # "otherwise" branch
Inside the ``then`` and ``otherwise`` branches, the magic identifier ``it``
(which is always named literally ``it``) refers to the value of ``test``.
This expands into a ``let`` and an expression-form ``if``.
Each part may consist of multiple expressions by using brackets around it.
To represent a single expression that is a literal list, use extra
brackets: ``[[1, 2, 3]]``.
"""
with dyn.let(gen_sym=gen_sym):
return _aif(tree)
@macros.expr
def cond(tree, *, gen_sym, **kw):
"""[syntax, expr] Lispy cond; like "a if p else b", but has "elif".
Usage::
cond[test1, then1,
test2, then2,
...
otherwise]
cond[[pre1, ..., test1], [post1, ..., then1],
[pre2, ..., test2], [post2, ..., then2],
...
[postn, ..., otherwise]]
This allows human-readable multi-branch conditionals in a lambda.
Each part may consist of multiple expressions by using brackets around it.
To represent a single expression that is a literal list, use extra
brackets: ``[[1, 2, 3]]``.
"""
with dyn.let(gen_sym=gen_sym):
return _cond(tree)
# -----------------------------------------------------------------------------
@macros.block
def curry(tree, **kw): # technically a list of trees, the body of the with block
"""[syntax, block] Automatic currying.
Usage::
from unpythonic.syntax import macros, curry
with curry:
...
All **function calls** and **function definitions** (``def``, ``lambda``)
*lexically* inside the ``with curry`` block are automatically curried.
**CAUTION**: Some builtins are uninspectable or may report their arities
incorrectly; in those cases, ``curry`` may fail, occasionally in mysterious
ways.
The function ``unpythonic.arity.arities``, which ``unpythonic.fun.curry``
internally uses, has a workaround for the inspectability problems of all
builtins in the top-level namespace (as of Python 3.7), but e.g. methods
of builtin types are not handled.
Lexically inside a ``with curry`` block, the auto-curried function calls
will skip the curry if the function is uninspectable, instead of raising
``TypeError`` as usual.
Example::
from unpythonic.syntax import macros, curry
from unpythonic import foldr, composerc as compose, cons, nil, ll
with curry:
def add3(a, b, c):
return a + b + c
assert add3(1)(2)(3) == 6
assert add3(1, 2)(3) == 6
assert add3(1)(2, 3) == 6
assert add3(1, 2, 3) == 6
mymap = lambda f: foldr(compose(cons, f), nil)
double = lambda x: 2 * x
assert mymap(double, ll(1, 2, 3)) == ll(2, 4, 6)
# The definition was auto-curried, so this works here too.
assert add3(1)(2)(3) == 6
"""
return _curry(block_body=tree)
# -----------------------------------------------------------------------------
@macros.expr
def let(tree, args, *, gen_sym, **kw):
"""[syntax, expr] Introduce local bindings.
This is sugar on top of ``unpythonic.lispylet.let``.
Usage::
let((k0, v0), ...)[body]
let((k0, v0), ...)[[body0, ...]]
where ``body`` is an expression. The names bound by ``let`` are local;
they are available in ``body``, and do not exist outside ``body``.
Alternative haskelly syntax is also available::
let[((k0, v0), ...) in body]
let[((k0, v0), ...) in [body0, ...]]
let[body, where((k0, v0), ...)]
let[[body0, ...], where((k0, v0), ...)]
For a body with multiple expressions, use an extra set of brackets,
as shown above. This inserts a ``do``. Only the outermost extra brackets
are interpreted specially; all others in the bodies are interpreted
as usual, as lists.
Note that in the haskelly syntax, the extra brackets for a multi-expression
body should enclose only the ``body`` part.
Each ``name`` in the same ``let`` must be unique.
Assignment to let-bound variables is supported with syntax such as ``x << 42``.
This is an expression, performing the assignment, and returning the new value.
In a multiple-expression body, also an internal definition context exists
for local variables that are not part of the ``let``; see ``do`` for details.
Technical points:
- In reality, the let-bound variables live in an ``unpythonic.env``.
This macro performs the magic to make them look (and pretty much behave)
like lexical variables.
- Compared to ``unpythonic.lispylet.let``, the macro version needs no quotes
around variable names in bindings.
- The body is automatically wrapped in a ``lambda e: ...``.
- For all ``x`` in bindings, the macro transforms lookups ``x --> e.x``.
- Lexical scoping is respected (so ``let`` constructs can be nested)
by actually using a unique name (gensym) instead of just ``e``.
- In the case of a multiple-expression body, the ``do`` transformation
is applied first to ``[body0, ...]``, and the result becomes ``body``.
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _let)
@macros.expr
def letseq(tree, args, *, gen_sym, **kw):
"""[syntax, expr] Let with sequential binding (like Scheme/Racket let*).
Like ``let``, but bindings take effect sequentially. Later bindings
shadow earlier ones if the same name is used multiple times.
Expands to nested ``let`` expressions.
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _letseq)
@macros.expr
def letrec(tree, args, *, gen_sym, **kw):
"""[syntax, expr] Let with mutually recursive binding.
Like ``let``, but bindings can see other bindings in the same ``letrec``.
Each ``name`` in the same ``letrec`` must be unique.
The definitions are processed sequentially, left to right. A definition
may refer to any previous definition. If ``value`` is callable (lambda),
it may refer to any definition, including later ones.
This is useful for locally defining mutually recursive functions.
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _letrec)
def _destructure_and_apply_let(tree, args, expander, allow_call_in_name_position=False):
if args:
bs = _canonize_bindings(args, locref=tree, allow_call_in_name_position=allow_call_in_name_position)
return expander(bindings=bs, body=tree)
# haskelly syntax
view = UnexpandedLetView(tree) # note this gets only the part inside the brackets
return expander(bindings=view.bindings, body=view.body)
# -----------------------------------------------------------------------------
# Decorator versions, for "let over def".
@macros.decorator
def dlet(tree, args, *, gen_sym, **kw):
"""[syntax, decorator] Decorator version of let, for 'let over def'.
Example::
@dlet((x, 0))
def count():
x << x + 1
return x
assert count() == 1
assert count() == 2
**CAUTION**: function arguments, local variables, and names declared as
``global`` or ``nonlocal`` in a given lexical scope shadow names from the
``let`` environment *for the entirety of that lexical scope*. (This is
modeled after Python's standard scoping rules.)
**CAUTION**: assignment to the let environment is ``name << value``;
the regular syntax ``name = value`` creates a local variable in the
lexical scope of the ``def``.
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _dlet)
@macros.decorator
def dletseq(tree, args, *, gen_sym, **kw):
"""[syntax, decorator] Decorator version of letseq, for 'letseq over def'.
Expands to nested function definitions, each with one ``dlet`` decorator.
Example::
@dletseq((x, 1),
(x, x+1),
(x, x+2))
def g(a):
return a + x
assert g(10) == 14
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _dletseq)
@macros.decorator
def dletrec(tree, args, *, gen_sym, **kw):
"""[syntax, decorator] Decorator version of letrec, for 'letrec over def'.
Example::
@dletrec((evenp, lambda x: (x == 0) or oddp(x - 1)),
(oddp, lambda x: (x != 0) and evenp(x - 1)))
def f(x):
return evenp(x)
assert f(42) is True
assert f(23) is False
Same cautions apply as to ``dlet``.
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _dletrec)
@macros.decorator
def blet(tree, args, *, gen_sym, **kw):
"""[syntax, decorator] def --> let block.
Example::
@blet((x, 21))
def result():
return 2*x
assert result == 42
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _blet)
@macros.decorator
def bletseq(tree, args, *, gen_sym, **kw):
"""[syntax, decorator] def --> letseq block.
Example::
@bletseq((x, 1),
(x, x+1),
(x, x+2))
def result():
return x
assert result == 4
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _bletseq)
@macros.decorator
def bletrec(tree, args, *, gen_sym, **kw):
"""[syntax, decorator] def --> letrec block.
Example::
@bletrec((evenp, lambda x: (x == 0) or oddp(x - 1)),
(oddp, lambda x: (x != 0) and evenp(x - 1)))
def result():
return evenp(42)
assert result is True
Because names inside a ``def`` have mutually recursive scope,
an almost equivalent pure Python solution (no macros) is::
from unpythonic.misc import call
@call
def result():
evenp = lambda x: (x == 0) or oddp(x - 1)
oddp = lambda x: (x != 0) and evenp(x - 1)
return evenp(42)
assert result is True
"""
with dyn.let(gen_sym=gen_sym):
return _destructure_and_apply_let(tree, args, _bletrec)
# -----------------------------------------------------------------------------
# Imperative code in expression position.
@macros.expr
def do(tree, *, gen_sym, **kw):
"""[syntax, expr] Stuff imperative code into an expression position.
Return value is the value of the last expression inside the ``do``.
See also ``do0``.
Usage::
do[body0, ...]
Example::
do[local[x << 42],
print(x),
x << 23,
x]
This is sugar on top of ``unpythonic.seq.do``, but with some extra features.
- To declare and initialize a local name, use ``local[name << value]``.
The operator ``local`` is syntax, not really a function, and it
only exists inside a ``do``.
- By design, there is no way to create an uninitialized variable;
a value must be given at declaration time. Just use ``None``
as an explicit "no value" if needed.
- Names declared within the same ``do`` must be unique. Re-declaring
the same name is an expansion-time error.
- To assign to an already declared local name, use ``name << value``.
**local name declarations**
A ``local`` declaration comes into effect in the expression following
the one where it appears. Thus::
result = []
let((lst, []))[do[result.append(lst), # the let "lst"
local[lst << lst + [1]], # LHS: do "lst", RHS: let "lst"
result.append(lst)]] # the do "lst"
assert result == [[], [1]]
**Syntactic ambiguity**
These two cases cannot be syntactically distinguished:
- Just one body expression, which is a literal tuple or list,
- Multiple body expressions, represented as a literal tuple or list.
``do`` always uses the latter interpretation.
Whenever there are multiple expressions in the body, the ambiguity does not
arise, because then the distinction between the sequence of expressions itself
and its items is clear.
Examples::
do[1, 2, 3] # --> tuple, 3
do[(1, 2, 3)] # --> tuple, 3 (since in Python, the comma creates tuples;
# parentheses are only used for disambiguation)
do[[1, 2, 3]] # --> list, 3
do[[[1, 2, 3]]] # --> list containing a list, [1, 2, 3]
do[([1, 2, 3],)] # --> tuple containing a list, [1, 2, 3]
do[[1, 2, 3],] # --> tuple containing a list, [1, 2, 3]
do[[(1, 2, 3)]] # --> list containing a tuple, (1, 2, 3)
do[((1, 2, 3),)] # --> tuple containing a tuple, (1, 2, 3)
do[(1, 2, 3),] # --> tuple containing a tuple, (1, 2, 3)
It is possible to use ``unpythonic.misc.pack`` to create a tuple from
given elements: ``do[pack(1, 2, 3)]`` is interpreted as a single-item body
that creates a tuple (by calling a function).
Note the outermost brackets belong to the ``do``; they don't yet create a list.
In the *use brackets to denote a multi-expr body* syntax (e.g. ``multilambda``,
``let`` constructs), the extra brackets already create a list, so in those
uses, the ambiguity does not arise. The transformation inserts not only the
word ``do``, but also the outermost brackets. For example::
let((x, 1),
(y, 2))[[
[x, y]]]
transforms to::
let((x, 1),
(y, 2))[do[[ # "do[" is inserted between the two opening brackets
[x, y]]]] # and its closing "]" is inserted here
which already gets rid of the ambiguity.
**Notes**
Macros are expanded in an inside-out order, so a nested ``let`` shadows
names, if the same names appear in the ``do``::
do[local[x << 17],
let((x, 23))[
print(x)], # 23, the "x" of the "let"
print(x)] # 17, the "x" of the "do"
The reason we require local names to be declared is to allow write access
to lexically outer environments from inside a ``do``::
let((x, 17))[
do[x << 23, # no "local[...]"; update the "x" of the "let"
local[y << 42], # "y" is local to the "do"
print(x, y)]]
With the extra bracket syntax, the latter example can be written as::
let((x, 17))[[
x << 23,
local[y << 42],
print(x, y)]]
It's subtly different in that the first version has the do-items in a tuple,
whereas this one has them in a list, but the behavior is exactly the same.
Python does it the other way around, requiring a ``nonlocal`` statement
to re-bind a name owned by an outer scope.
The ``let`` constructs solve this problem by having the local bindings
declared in a separate block, which plays the role of ``local``.
"""
with dyn.let(gen_sym=gen_sym):
return _do(tree)
@macros.expr
def do0(tree, *, gen_sym, **kw):
"""[syntax, expr] Like do, but return the value of the first expression."""
with dyn.let(gen_sym=gen_sym):
return _do0(tree)
# -----------------------------------------------------------------------------
@macros.expr
def let_syntax(tree, args, *, gen_sym, **kw):
with dyn.let(gen_sym=gen_sym): # gen_sym is only needed by the implicit do.
return _destructure_and_apply_let(tree, args, let_syntax_expr, allow_call_in_name_position=True)
# Python has no function overloading, but expr and block macros go into
# different parts of MacroPy's macro registry.
#
# Normal run-time code sees only the dynamically latest definition,
# so the docstring goes here.
@macros.block
def let_syntax(tree, **kw):
"""[syntax] Introduce local **syntactic** bindings.
**Expression variant**::
let_syntax((lhs, rhs), ...)[body]
let_syntax((lhs, rhs), ...)[[body0, ...]]
Alternative haskelly syntax::
let_syntax[((lhs, rhs), ...) in body]
let_syntax[((lhs, rhs), ...) in [body0, ...]]
let_syntax[body, where((lhs, rhs), ...)]
let_syntax[[body0, ...], where((lhs, rhs), ...)]
**Block variant**::
with let_syntax:
with block as xs: # capture a block of statements - bare name
...
with block(a, ...) as xs: # capture a block of statements - template
...
with expr as x: # capture a single expression - bare name
...
with expr(a, ...) as x: # capture a single expression - template
...
body0
...
A single expression can be a ``do[]`` if multiple expressions are needed.
The bindings are applied **at macro expansion time**, substituting
the expression on the RHS for each instance of the corresponding LHS.
Each substitution gets a fresh copy.
This is useful to e.g. locally abbreviate long function names at macro
expansion time (with zero run-time overhead), or to splice in several
(possibly parametric) instances of a common pattern.
In the expression variant, ``lhs`` may be:
- A bare name (e.g. ``x``), or
- A simple template of the form ``f(x, ...)``. The names inside the
parentheses declare the formal parameters of the template (that can
then be used in the body).
In the block variant:
- The **as-part** specifies the name of the LHS.
- If a template, the formal parameters are declared on the ``block``
or ``expr``, not on the as-part (due to syntactic limitations).
**Templates**
To make parametric substitutions, use templates.
Templates support only positional arguments, with no default values.
Even in block templates, parameters are always expressions (because they
use the function-call syntax at the use site).
In the body of the ``let_syntax``, a template is used like a function call.
Just like in an actual function call, when the template is substituted,
any instances of its formal parameters on its RHS get replaced by the
argument values from the "call" site; but ``let_syntax`` performs this
at macro-expansion time.
Note each instance of the same formal parameter gets a fresh copy of the
corresponding argument value.
**Substitution order**
This is a two-step process. In the first step, we apply template substitutions.
In the second step, we apply bare name substitutions to the result of the
first step. (So RHSs of templates may use any of the bare-name definitions.)
Within each step, the substitutions are applied **in the order specified**.
So if the bindings are ``((x, y), (y, z))``, then ``x`` transforms to ``z``.
But if the bindings are ``((y, z), (x, y))``, then ``x`` transforms to ``y``,
and only an explicit ``y`` at the use site transforms to ``z``.
**Notes**
Inspired by Racket's ``let-syntax`` and ``with-syntax``, see:
https://docs.racket-lang.org/reference/let.html
https://docs.racket-lang.org/reference/stx-patterns.html
**CAUTION**: This is essentially a toy macro system inside the real
macro system, implemented with the real macro system.
The usual caveats of macro systems apply. Especially, we support absolutely
no form of hygiene. Be very, very careful to avoid name conflicts.
``let_syntax`` is meant only for simple local substitutions where the
elimination of repetition can shorten the code and improve readability.
If you need to do something complex, prefer writing a real macro directly
in MacroPy.
"""
return let_syntax_block(block_body=tree)
@macros.expr
def abbrev(tree, args, *, gen_sym, **kw):
with dyn.let(gen_sym=gen_sym): # gen_sym is only needed by the implicit do.
yield _destructure_and_apply_let(tree, args, let_syntax_expr, allow_call_in_name_position=True)
@macros.block
def abbrev(tree, **kw):
"""[syntax] Exactly like ``let_syntax``, but expands in the first pass, outside in.
Because this variant expands before any macros in the body, it can locally
rename other macros, e.g.::
abbrev((a, ast_literal))[
a[tree1] if a[tree2] else a[tree3]]
**CAUTION**: Because of the expansion order, nesting ``abbrev`` will not
lexically scope the substitutions. Instead, the outermost ``abbrev`` expands
first, and then any inner ones expand with whatever substitutions they have
remaining.
If the same name is used on the LHS in two or more nested ``abbrev``,
any inner ones will likely raise an error (unless the outer substitution
just replaces a name with another), because also the names on the LHS
in the inner ``abbrev`` will undergo substitution when the outer
``abbrev`` expands.
"""
yield let_syntax_block(block_body=tree)
# -----------------------------------------------------------------------------
@macros.expr
def forall(tree, **kw):
"""[syntax, expr] Nondeterministic evaluation.
Fully based on AST transformation, with real lexical variables.
Like Haskell's do-notation, but here specialized for the List monad.
Example::
# pythagorean triples
pt = forall[z << range(1, 21), # hypotenuse
x << range(1, z+1), # shorter leg
y << range(x, z+1), # longer leg
insist(x*x + y*y == z*z),
(x, y, z)]
assert tuple(sorted(pt)) == ((3, 4, 5), (5, 12, 13), (6, 8, 10),
(8, 15, 17), (9, 12, 15), (12, 16, 20))
"""
return _forall(exprs=tree)
# -----------------------------------------------------------------------------
@macros.block
def multilambda(tree, *, gen_sym, **kw):
"""[syntax, block] Supercharge your lambdas: multiple expressions, local variables.
For all ``lambda`` lexically inside the ``with multilambda`` block,
``[...]`` denotes a multiple-expression body with an implicit ``do``::
lambda ...: [expr0, ...] --> lambda ...: do[expr0, ...]
Only the outermost set of brackets around the body of a ``lambda`` denotes
a multi-expression body; the rest are interpreted as lists, as usual.
Examples::
with multilambda:
echo = lambda x: [print(x), x]
assert echo("hi there") == "hi there"
count = let((x, 0))[
lambda: [x << x + 1,
x]]
assert count() == 1
assert count() == 2
mk12 = lambda: [[1, 2]]
assert mk12() == [1, 2]
For local variables, see ``do``.
"""
# two-pass macro:
# - yield from to first yield the first-pass output
# - then return to return the StopIteration final value (second-pass output if any)
with dyn.let(gen_sym=gen_sym):
return (yield from _multilambda(block_body=tree))
@macros.block
def namedlambda(tree, **kw):
"""[syntax, block] Name lambdas implicitly.
Lexically inside a ``with namedlambda`` block, any literal ``lambda``
that is assigned to a name using one of the supported assignment forms
is named to have the name of the LHS of the assignment. The name is
captured at macro expansion time.
Naming modifies the original function object.
We support:
- Single-item assignments to a local name, ``f = lambda ...: ...``
- Assignments to unpythonic environments, ``f << (lambda ...: ...)``
- Let bindings, ``let[(f, (lambda ...: ...)) in ...]``, using any
let syntax supported by unpythonic (here using the haskelly let-in
just as an example).
Support for other forms of assignment might or might not be added in a
future version.
Example::
with namedlambda:
f = lambda x: x**3 # assignment: name as "f"
let((x, 42), (g, None), (h, None))[[
g << (lambda x: x**2), # env-assignment: name as "g"
h << f, # still "f" (no literal lambda on RHS)
(g(x), h(x))]]
foo = let[(f7, lambda x: x) in f7] # let-binding: name as "f7"
The naming is performed using the function ``unpythonic.misc.namelambda``,
which will update ``__name__``, ``__qualname__`` and ``__code__.co_name``.
"""
return (yield from _namedlambda(block_body=tree))
@macros.block
def quicklambda(tree, **kw):
"""[syntax, block] Use ``macropy.quick_lambda`` with ``unpythonic.syntax``.
To be able to transform correctly, the block macros in ``unpythonic.syntax``
that transform lambdas (e.g. ``multilambda``, ``tco``) need to see all
``lambda`` definitions written with Python's standard ``lambda``.
However, the highly useful ``macropy.quick_lambda`` uses the syntax
``f[...]``, which (to the analyzer) does not look like a lambda definition.
This macro changes the expansion order, forcing any ``f[...]`` lexically
inside the block to expand in the first pass.
Any expression of the form ``f[...]`` (the ``f`` is literal) is understood
as a quick lambda, whether or not ``f`` and ``_`` are imported at the
call site.
Example - a quick multilambda::
from unpythonic.syntax import macros, multilambda, quicklambda, f, _, local
with quicklambda, multilambda:
func = f[[local[x << _],
local[y << _],
x + y]]
assert func(1, 2) == 3
(This is of course rather silly, as an unnamed argument can only be mentioned
once. If we're giving names to them, a regular ``lambda`` is shorter to write.
The point is, this combo is now possible.)
"""
return (yield from _quicklambda(block_body=tree))
@macros.block
def envify(tree, *, gen_sym, **kw):
"""[syntax, block] Make formal parameters live in an unpythonic env.
The purpose is to allow overwriting formals using unpythonic's
expression-assignment ``name << value``. The price is that the references
to the arguments are copied into an env whenever an envified function is
entered.
Example - PG's accumulator puzzle (http://paulgraham.com/icad.html)::
with envify:
def foo(n):
return lambda i: n << n + i
Of course, now we can::
with autoreturn, envify:
def foo(n):
lambda i: n << n + i
"""
with dyn.let(gen_sym=gen_sym):
return (yield from _envify(block_body=tree))
# -----------------------------------------------------------------------------
@macros.block
def autoreturn(tree, **kw):
"""[syntax, block] Implicit "return" in tail position, like in Lisps.
Each ``def`` function definition lexically within the ``with autoreturn``
block is examined, and if the last item within the body is an expression
``expr``, it is transformed into ``return expr``.
If the last item is an if/elif/else block, the transformation is applied
to the last item in each of its branches.
If the last item is a ``with`` or ``async with`` block, the transformation
is applied to the last item in its body.
If the last item is a try/except/else/finally block, the rules are as follows.
If an ``else`` clause is present, the transformation is applied to the last
item in it; otherwise, to the last item in the ``try`` clause. Additionally,
in both cases, the transformation is applied to the last item in each of the
``except`` clauses. The ``finally`` clause is not transformed; the intention
is it is usually a finalizer (e.g. to release resources) that runs after the
interesting value is already being returned by ``try``, ``else`` or ``except``.
Example::
with autoreturn:
def f():
"I'll just return this"
assert f() == "I'll just return this"
def g(x):
if x == 1:
"one"
elif x == 2:
"two"
else:
"something else"
assert g(1) == "one"
assert g(2) == "two"
assert g(42) == "something else"
**CAUTION**: If the final ``else`` is omitted, as often in Python, then
only the ``else`` item is in tail position with respect to the function
definition - likely not what you want.
So with ``autoreturn``, the final ``else`` should be written out explicitly,
to make the ``else`` branch part of the same if/elif/else block.
**CAUTION**: ``for``, ``async for``, ``while`` are currently not analyzed;
effectively, these are defined as always returning ``None``. If the last item
in your function body is a loop, use an explicit return.
**CAUTION**: With ``autoreturn`` enabled, functions no longer return ``None``
by default; the whole point of this macro is to change the default return
value.
The default return value is ``None`` only if the tail position contains
a statement (because in a sense, a statement always returns ``None``).
"""
return (yield from _autoreturn(block_body=tree))
@macros.block
def tco(tree, *, gen_sym, **kw):
"""[syntax, block] Implicit tail-call optimization (TCO).
Examples::
with tco:
evenp = lambda x: (x == 0) or oddp(x - 1)
oddp = lambda x: (x != 0) and evenp(x - 1)
assert evenp(10000) is True
with tco:
def evenp(x):
if x == 0:
return True
return oddp(x - 1)
def oddp(x):
if x != 0:
return evenp(x - 1)
return False
assert evenp(10000) is True
This is based on a strategy similar to MacroPy's tco macro, but using
the TCO machinery from ``unpythonic.tco``.
This recursively handles also builtins ``a if p else b``, ``and``, ``or``;
and from ``unpythonic.syntax``, ``do[]``, ``let[]``, ``letseq[]``, ``letrec[]``,
when used in computing a return value. (``aif[]`` and ``cond[]`` also work.)
Note only calls **in tail position** will be TCO'd. Any other calls
are left as-is. Tail positions are:
- The whole return value, if it is just a single call.
- Both ``a`` and ``b`` branches of ``a if p else b`` (but not ``p``).
- The last item in an ``and``/``or``. If these are nested, only the
last item in the whole expression involving ``and``/``or``. E.g. in::
(a and b) or c
a and (b or c)
in either case, only ``c`` is in tail position, regardless of the
values of ``a``, ``b``.
- The last item in a ``do[]``.
- In a ``do0[]``, this is the implicit item that just returns the
stored return value.
- The argument of a call to an escape continuation. The ``ec(...)`` call
itself does not need to be in tail position; escaping early is the
whole point of an ec.
All function definitions (``def`` and ``lambda``) lexically inside the block
undergo TCO transformation. The functions are automatically ``@trampolined``,
and any tail calls in their return values are converted to ``jump(...)``
for the TCO machinery.
Note in a ``def`` you still need the ``return``; it marks a return value.
But see ``autoreturn``::
with autoreturn, tco:
def evenp(x):
if x == 0:
True
else:
oddp(x - 1)
def oddp(x):
if x != 0:
evenp(x - 1)
else:
False
assert evenp(10000) is True
**CAUTION**: regarding escape continuations, only basic uses of ecs created
via ``call_ec`` are currently detected as being in tail position. Any other
custom escape mechanisms are not supported. (This is mainly of interest for
lambdas, which have no ``return``, and for "multi-return" from a nested
function.)
*Basic use* is defined as either of these two cases::
# use as decorator
@call_ec
def result(ec):
...
# use directly on a literal lambda
result = call_ec(lambda ec: ...)
When macro expansion of the ``with tco`` block starts, names of escape
continuations created **anywhere lexically within** the ``with tco`` block