-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpyperler.pyx
More file actions
1848 lines (1669 loc) · 56.6 KB
/
pyperler.pyx
File metadata and controls
1848 lines (1669 loc) · 56.6 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
# vim: set fileencoding=utf-8 :
#
# pyperler.pyx
#
# Copyright (C) 2013-2015, Timo Kluck <tkluck@infty.nl>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
r"""
>>> import pyperler
>>> i = pyperler.Interpreter()
Accessing scalar variables:
>>> i("$a = 2 + 2;")
4
>>> i.Sa
4
>>> i('$a')
4
>>> list(range(i.Sa))
[0, 1, 2, 3]
>>> i.Sa = 5
>>> list(range(i.Sa))
[0, 1, 2, 3, 4]
>>> i('undef')
<pyperler.undef>
Integer, float, and string conversions:
>>> i.Sb = 2.3
>>> i.Sb
2.3
>>> i.Sc = "abc"
>>> i.Sc
'abc'
Evaluating list expressions in array context:
>>> i["qw / a b c d e /"].strings()
('a', 'b', 'c', 'd', 'e')
With perl's weak typing, any non-number string has the integer value 0:
>>> i["qw / a b c d e /"].ints()
(0, 0, 0, 0, 0)
If we do not cast, we get a list of pyperler.ScalarValue objects. Their
`repr` is their string value:
>>> list(i["qw / a b c d e /"])
['a', 'b', 'c', 'd', 'e']
In scalar context, an array yields its length:
>>> i("@array = qw / a b c d e /")
5
>>> i("@array")
5
which is also available from Python:
>>> len(i.Aarray)
5
Fun with Perl's secret operators:
>>> i("()= qw / a b c d e /")
5
Accessing array values:
>>> i("@d = (10 .. 20)")
11
>>> i.Ad.ints()
(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
>>> i.Ad[2]
12
>>> list(i.Ad)[2]
12
>>> i.Ad[0] = 9
>>> int(i('$d[0]'))
9
>>> i['@d[0..2]'].ints()
(9, 11, 12)
>>> i.Ad.ints()
(9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
Assigning iterables to arrays:
>>> i.Ad = (10 for _ in range(5))
>>> i.Ad.ints()
(10, 10, 10, 10, 10)
>>> i.Aletters = "nohtyP ni lreP"
>>> i('@letters = reverse @letters')
14
>>> list(i.Aletters)
['P', 'e', 'r', 'l', ' ', 'i', 'n', ' ', 'P', 'y', 't', 'h', 'o', 'n']
Accessing hash values:
>>> i("%b = (greece => 'Aristotle', germany => 'Hegel');")
4
>>> i.Pb['greece']
'Aristotle'
>>> i.Pb['germany'] = 'Kant'
>>> i('$c = $b{germany}')
'Kant'
>>> i.Sc
'Kant'
>>> i.Pparrot = {'dead': True}
>>> i("$parrot{dead}")
1
Accessing objects
>>> i.void_context("use Car; $car = Car->new")
>>> i.Scar.set_brand("Toyota")
<pyperler.undef>
>>> i.Scar.drive(20)
<pyperler.undef>
>>> i("$car->distance")
20
>>> i.Scar.distance()
20
>>> i.Scar.drive(20)
<pyperler.undef>
Verify that this makes the intended change to the object:
>>> i("$car->distance")
40
>>> i.Scar.distance()
40
Catching perl exceptions ('die'):
>>> i.Scar.out_of_gas() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
RuntimeError: Out of gas! at ...perllib/Car.pm line ...
<BLANKLINE>
Nested structures:
>>> _ = i("$a = { dictionary => { a => 65, b => 66 }, array => [ 4, 5, 6] }")
>>> i.Sa['dictionary']['a']
65
>>> i.Sa['array'][1]
5
Assigning non-string iterables to a nested element will create an arrayref:
>>> i.Sa['array'] = range(2,5)
>>> i["@{ $a->{array} }"].ints()
(2, 3, 4)
Similarly, assiging a dict to a nested element will create a hashref:
>>> i.Sa['dictionary'] = {'c': 67, 'd': 68}
>>> int(i('$a->{dictionary}->{c}'))
67
>>> sorted(i['keys %{ $a->{dictionary} } '].strings())
['c', 'd']
Calling subs:
>>> i("sub do_something { for (1..10) { 2 + 2 }; return 3; }")
<pyperler.undef>
>>> i.Fdo_something()
3
>>> i("sub add_two { return $_[0] + 2; }")
<pyperler.undef>
>>> i.Fadd_two("4")
6
Anonymous subs:
>>> i('sub { return 2*$_[0]; }')(6)
12
In packages:
>>> i.F['Car::all_brands'].list_context()
('Toyota', 'Nissan')
Passing a Perl function as a callback to python. Yo'll need to
specify whether you want it to evaluate in scalar context or
list context:
>>> def long_computation(on_ready):
... for i in range(10**5): 2 + 2
... return on_ready(5)
...
>>> long_computation(i('sub { return 4; }').scalar_context)
4
>>> i('sub callback { return $_[0]; }')
<pyperler.undef>
>>> long_computation(i.Fcallback.scalar_context)
5
You can maintain a reference to a Perl object, without it being
a Perl variable:
>>> car = i('Car->new')
>>> car.set_brand('Chevrolet')
<pyperler.undef>
>>> car.drive(20)
<pyperler.undef>
>>> car.brand()
'Chevrolet'
>>> i('$Car::destroyed_cars')
0
>>> del car # this deletes it on the Perl side, too
>>> i('$Car::destroyed_cars')
1
>>> i('sub p { return $_[0] ** $_[1]; }');
<pyperler.undef>
>>> i.Fp(2,3)
8.0
But the canonical way is this:
>>> Car = i.use('Car')
>>> car = Car()
>>> car.drive(20)
<pyperler.undef>
>>> car.set_brand('Honda');
<pyperler.undef>
>>> car.brand()
'Honda'
You can access class methods by calling them on the class:
>>> Car.all_brands.list_context()
('Toyota', 'Nissan')
Check that we report a proper error for non-existing packages:
>>> Pkg = i.use('Non::Existing::Package') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ImportError: Can't locate Non/Existing/Package.pm in @INC (you may need to install the Non::Existing::Package module) ...
BEGIN failed--compilation aborted at ...
<BLANKLINE>
You can also pass Python functions as Perl callbacks:
>>> def f(): return 3
>>> i('sub callit { return $_[0]->() }');
<pyperler.undef>
>>> i.Fcallit(f)
3
>>> def g(x): return x**2
>>> i('sub pass_three { return $_[0]->(3) }');
<pyperler.undef>
>>> i.Fpass_three(g)
9
>>> i('sub call_first { return $_[0]->($_[1]); }');
<pyperler.undef>
>>> i.Fcall_first(lambda x: eval(str(x)), "2+2")
4
And this even works if you switch between Perl and Python several times:
>>> i.Fcall_first(i, "2+2") # no lock or segfault
4
And also when we don't discard the return value:
>>> def h(x): return int(i(x))
>>> i.Fcall_first(h, "2+2")
4
Test that we recover objects when we pass them through perl
>>> class FooBar(object):
... def __init__(self):
... self._last_set_item = None
... def foo(self):
... return "bar"
... def __getitem__(self, key):
... return 'key length: %d' % len(key)
... def __setitem__(self, key, value):
... self._last_set_item = value
... def __len__(self):
... return 31337
... def __bool__(self):
... return bool(self._last_set_item)
...
>>> i('sub shifter { shift; }')
<pyperler.undef>
>>> foobar = FooBar()
>>> type(foobar)
<class 'pyperler.FooBar'>
>>> type(i.Fshifter(FooBar()))
<class 'pyperler.FooBar'>
>>> id(foobar) == id(i.Fshifter(foobar))
True
And that indexing and getting the length works:
>>> i('sub { return $_[0]->{miss}; }')(foobar)
'key length: 4'
>>> i('sub { $_[0]->{funny_joke} = "dkfjasd"; return undef; }')(foobar)
<pyperler.undef>
>>> i('sub { return $_[0] ? "YES" : "no"; }')(foobar)
'YES'
>>> i('sub { return scalar@{ $_[0] }; }')(foobar)
31337
>>> Table = i.use('Text::Table')
>>> t = Table("Planet", "Radius\nkm", "Density\ng/cm^3")
>>> _ = t.load(
... [ "Mercury", 2360, 3.7 ],
... [ "Venus", 6110, 5.1 ],
... [ "Earth", 6378, 5.52 ],
... [ "Jupiter", 71030, 1.3 ],
... )
>>> print( t.table() )
Planet Radius Density
km g/cm^3
Mercury 2360 3.7
Venus 6110 5.1
Earth 6378 5.52
Jupiter 71030 1.3
<BLANKLINE>
Using list context:
>>> a,b,c = i['qw / alpha beta gamma /']
>>> b
'beta'
Test using more than 32-bits numbers:
>>> i('sub { shift; }')(2**38)
274877906944
Test using negative numbers:
>>> i('sub { shift; }')(-1)
-1
Test passing blessed scalar values through Python:
>>> i.Sdaewoo_matiz = Car()
>>> i('ref $daewoo_matiz')
'Car'
We even support introspection if your local CPAN installation sports Class::Inspector:
>>> Inspector = i.use('Class::Inspector') # this line is not needed, but if it fails you know you need to install Class::Inspector
>>> Car.__dir__()
['DESTROY', 'all_brands', 'brand', 'distance', 'drive', 'new', 'out_of_gas', 'set_brand']
>>> nissan_sunny = Car()
>>> nissan_sunny.__dir__()
['DESTROY', 'all_brands', 'brand', 'distance', 'drive', 'new', 'out_of_gas', 'set_brand']
Fail gracefully when a variable doesn't exist:
>>> i.Snon_existing_variable
Traceback (most recent call last):
...
NameError: name '$non_existing_variable' is not defined
Use Perl's awesome interface to regular expressions for shorter code:
>>> i.S_ = "abc"
>>> a,b,c = i['/(.)(.)(.)/']
>>> a,b,c
('a', 'b', 'c')
We support the common perl idiom
while(my $row = $object->next) {
...
}
for iteration:
>>> i('use DummyIterable')
<pyperler.undef>
>>> i.void_context('$numbers = bless [1,2,3], "DummyIterable"')
>>> for a in i.Snumbers:
... print(a)
...
1
2
3
Also nice for string quoting:
>>> a,b,c = i['qw/a b c/']
>>> a
'a'
Also, creating a new interpreter works like yo'd expect:
>>> i.Sa = 3
>>> i.Sa
3
>>> i = pyperler.Interpreter()
>>> i.Sa
Traceback (most recent call last):
...
NameError: name '$a' is not defined
Deal with null-bytes in perl strings:
>>> a = bytes(i('"a\\x00b"'))
>>> len(a)
3
Check that we have all python's array methods on an arrayref:
>>> a = i("[1,2,3,4,5,6]")
>>> a.append(7)
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> b = a.copy()
>>> b.append(7)
>>> a,b
([1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 7])
>>> a.count(7), b.count(7)
(1, 2)
>>> a.clear(); a
[]
>>> a= i("[1,2,3,4,5,6,7]")
>>> a.extend((x**3 for x in range(2,4))); a
[1, 2, 3, 4, 5, 6, 7, 8, 27]
>>> a.index(27)
8
>>> a.insert(8,9); a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 27]
>>> a.pop(), a
(27, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.pop(2), a
(3, [1, 2, 4, 5, 6, 7, 8, 9])
>>> a.remove(2); a
[1, 4, 5, 6, 7, 8, 9]
>>> a.reverse(); a
[9, 8, 7, 6, 5, 4, 1]
We cannot directly compare scalar values, because we don't
know whether you want string or number comparison. You can
make that explicit by specifying a key:
>>> a.append(10)
>>> a.sort(key=int); a
[1, 4, 5, 6, 7, 8, 9, 10]
>>> a.sort(key=str); a
['1', '10', '4', '5', '6', '7', '8', '9']
>>> b=[1,2,3,2,3,4,8,5,0,1]
>>> b.sort(key=int); b
[0, 1, 1, 2, 2, 3, 3, 4, 5, 8]
Dictionary methods on hashrefs:
>>> a = i("{ foo => 3, bar => 4 }")
>>> b = a.copy(); b["baz"] = 5
>>> b["baz"]
5
>>> a.get('bar')
4
>>> a.get('baz', 'not found')
'not found'
>>> sorted(a.items()) == [('bar', 4), ('foo', 3)]
True
>>> sorted(a.keys()) == ['bar', 'foo']
True
>>> a.pop('foo')
3
>>> sorted(a.keys()) == ['bar']
True
>>> a.popitem() == ('bar', 4)
True
>>> a
{}
>>> a.setdefault('baz', 6)
6
>>> a.setdefault('baz', 7)
6
>>> sorted(a.keys()) == ['baz']
True
>>> a.update(foo=3, bar=4)
>>> sorted(a.items()) == [('bar', 4), ('baz', 6), ('foo', 3)]
True
>>> sorted(a.values(), key=int)
[3, 4, 6]
>>> a.clear()
>>> a
{}
Ensure proper refcounting even when marshalling back and forth
>>> Car = i.use('Car')
>>> i('$Car::destroyed_cars = 0')
0
>>> car = Car()
Pass it to a Perl function:
>>> i('sub { }')(car)
<pyperler.undef>
>>> del car
>>> i('$Car::destroyed_cars')
1
Pass it to a python callback:
>>> car = Car()
>>> i('sub { $_[0]->($_[1]) }')(lambda x: 0, car)
0
>>> del car
>>> i('$Car::destroyed_cars')
2
Have a reference both in Python and in Perl:
>>> car = i("$car = Car->new")
>>> i('sub { }')(car, i.Scar)
<pyperler.undef>
>>> i('sub { $_[0]->($_[1], $_[2]) }')(lambda x, y: 0, car, i.Scar)
0
>>> i.Scar = None
>>> i('$Car::destroyed_cars')
2
>>> del car
>>> i('$Car::destroyed_cars')
3
"""
from libc.stdlib cimport malloc, free
cimport dlfcn
from cpython cimport PyObject, Py_INCREF, Py_DECREF, PY_MAJOR_VERSION
cimport perl
from collections import defaultdict
include "PythonObjectPm.pyx"
cpdef PERL_SYS_INIT3(argv, env):
cdef int argc
cdef char** cargv
cdef char** cenv
perl.PERL_SYS_INIT3(&argc, &cargv, &cenv)
include "callbacks.pyx"
cdef void xs_init():
cdef char *file = "file"
perl.newXS("DynaLoader::boot_DynaLoader", &perl.boot_DynaLoader, file);
perl.newXS("Python::bootstrap", &dummy, file)
perl.newXS("Python::Object::bootstrap", &dummy, file)
perl.newXS("Python::PyObject_CallObject", <void*>&call_object, file)
perl.newXS("Python::PyObject_Str", &object_to_str, file)
perl.newXS("Python::PyObject_IsTrue", &object_to_bool, file)
perl.newXS("Python::PyObject_GetItem", &object_get_item, file)
perl.newXS("Python::PyObject_SetItem", &object_set_item, file)
perl.newXS("Python::PyObject_Length", &object_length, file)
perl.newXS("Python::PyMapping_Check", &object_is_mapping, file)
perl.newXS("Python::PyObject_DelItem", &object_del_item, file)
cdef class _PerlInterpreter:
cdef perl.PerlInterpreter *_this
def __cinit__(self):
perl.my_perl = perl.perl_alloc()
if perl.my_perl is NULL:
raise MemoryError()
perl.perl_construct(perl.my_perl)
perl.PL_exit_flags |= perl.PERL_EXIT_DESTRUCT_END;
def parse(self, argv):
cdef char **string_buf = <char**>malloc(len(argv) * sizeof(char*))
for i in range(len(argv)):
string_buf[i] = <char*>(argv[i])
perl.perl_parse(perl.my_perl, &xs_init, len(argv), string_buf, NULL)
free(string_buf)
def run(self):
perl.perl_run(perl.my_perl)
cdef perl.SV* _expression_sv(object expression):
if isinstance(expression, ScalarValue):
return perl.SvREFCNT_inc((<ScalarValue>expression)._sv)
else:
expression = str(expression).encode()
return perl.newSVpvn_utf8(expression, len(expression), True)
cdef class Interpreter(object):
cdef _PerlInterpreter _interpreter
cdef object _iterable_methods
cdef readonly ScalarValue _ref
cdef readonly ScalarValue _is_numeric
cdef readonly ScalarValue _is_integer
def __init__(self):
self._interpreter = _PerlInterpreter()
self._interpreter.parse([b"",b"-e",PythonObjectPackage])
self._interpreter.run()
self._iterable_methods = defaultdict(lambda: 'next')
self._is_numeric = self('sub { my $i = shift; (0+$i) eq $i; }')
self._is_integer = self('sub { my $i = shift; int $i eq $i; }')
self._ref = self('sub { ref $_[0]; }')
cdef object _eval(self, object expression, int context):
cdef int count
cdef perl.SV* expression_sv = _expression_sv(expression)
cdef object ret = None
perl.stmt_SAVETMPS()
perl.stmt_dSP()
for _ in ["nogil"]: # with nogil:
count = perl.eval_sv(expression_sv, perl.G_EVAL|context)
perl.SvREFCNT_dec(expression_sv)
perl.stmt_SPAGAIN()
if(context == perl.G_ARRAY):
ret = [_sv_to_python(perl.SvREFCNT_inc(perl.POPs), self) for _ in range(count)]
ret = ListValue(reversed(ret))
elif(context == perl.G_SCALAR):
if(count):
for _ in range(count - 1):
perl.POPs
ret = _sv_to_python(perl.SvREFCNT_inc(perl.POPs), self)
# if not count, then None is a sensible return value
elif(context == perl.G_VOID):
for _ in range(count):
perl.POPs
else:
raise AssertionError("Shouldn't reach here")
perl.stmt_FREETMPS()
perl.stmt_PUTBACK()
if perl.SvTRUE(perl.ERRSV):
raise RuntimeError(perl.SvPVutf8_nolen(perl.ERRSV).decode())
else:
return ret
def void_context(self, expression):
return self._eval(expression, perl.G_VOID)
def scalar_context(self, expression):
return self._eval(expression, perl.G_SCALAR)
def list_context(self, expression):
return self._eval(expression, perl.G_ARRAY)
def __call__(self, expression):
return self._eval(expression, perl.G_SCALAR)
def __getitem__(self, expression):
return self._eval(expression, perl.G_ARRAY)
def __getattribute__(self, name):
"""
>>> import pyperler; i = pyperler.Interpreter()
>>> i('use Data::Dumper')
<pyperler.undef>
>>> print( i.F['Dumper']([1, 2, 2, 3]) )
$VAR1 = [
1,
2,
2,
3
];
<BLANKLINE>
"""
initial = name[0]
cdef perl.SV *scalar_value
cdef perl.AV *array_value
cdef perl.HV *hash_value
short_name = str(name[1:]).encode()
if initial in 'SD':
scalar_value = perl.get_sv(short_name, 0)
if scalar_value:
return _sv_to_python(perl.SvREFCNT_inc(scalar_value), self)
else:
raise NameError("name '$%s' is not defined" % name[1:])
elif initial == 'A':
array_value = perl.get_av(short_name, 0)
if array_value:
return _sv_to_python(perl.newRV_inc(<perl.SV*>array_value), self)
else:
raise NameError("name '@%s' is not defined" % name[1:])
elif initial in 'PH':
hash_value = perl.get_hv(short_name, 0)
if hash_value:
return _sv_to_python(perl.newRV_inc(<perl.SV*>hash_value), self)
else:
raise NameError("name '%%%s' is not defined" % name[1:])
elif initial == 'F':
if len(name) > 1:
return FunctionAttribute(self, name[1:])
else:
class FunctionLookup(object):
def __getitem__(this, key):
return FunctionAttribute(self, key)
def __call__(this, key):
raise RuntimeError("You can't use .F(...); use .F[...] instead")
return FunctionLookup()
elif name == 'use':
def perl_package_constructor(*args, **kwds):
return PerlPackage(self, *args, **kwds)
return perl_package_constructor
else:
return object.__getattribute__(self, name)
def __dir__(self):
return ['use', 'A', 'P', 'H', 'F', 'S', 'D']
def __setattr__(self, name, value):
"""
>>> import pyperler; i = pyperler.Interpreter()
>>> i.Sa = 3
>>> i.Sa
3
>>> i.Sb = 2.3
>>> i.Sb
2.3
>>> i.Aa = [1,2,3]
>>> len(i.Aa)
3
>>> i.Aa[1]
2
>>> i.Ha = {1:'2',2:'3'}
>>> sorted(i.Ha.to_python().values())
[2, 3]
>>> i.Ha[2]
3
"""
initial = name[0].upper()
short_name = str(name[1:]).encode()
cdef perl.SV *sv
cdef perl.AV *array_value
cdef perl.HV *hash_value
if initial in 'SD':
sv = perl.get_sv(short_name, perl.GV_ADD)
_assign_sv(sv, value)
elif initial == 'A':
array_value = perl.get_av(short_name, perl.GV_ADD)
perl.av_clear(array_value)
for element in value:
perl.av_push(array_value, _new_sv_from_object(element))
elif initial in 'PH':
hash_value = perl.get_hv(short_name, perl.GV_ADD)
perl.hv_clear(hash_value)
for k, v in value.items():
k = str(k).encode()
for k, v in value.iteritems():
k = str(k).encode()
perl.hv_store(hash_value, k, len(k), _new_sv_from_object(v), 0)
else:
object.__setattr__(self, name, value)
cdef class PerlPackage:
cdef Interpreter _interpreter
cdef object _name
def __init__(self, interpreter, name, iterable_method='next'):
self._interpreter = interpreter
self._interpreter._iterable_methods[name] = iterable_method
self._name = name
failmessage = None
try:
interpreter('use ' + name)
except RuntimeError as e:
failmessage = e.args[0]
if failmessage:
raise ImportError(failmessage, name=self._name)
def __call__(self, *args, **kwds):
cdef BoundMethod bound_method = BoundMethod()
bound_method._method = "new"
bound_method._sv = _new_sv_from_object(str(self._name))
bound_method._interpreter = self._interpreter
return bound_method(*args, **kwds)
def __getattr__(self, name):
cdef BoundMethod bound_method = BoundMethod()
bound_method._method = name
bound_method._sv = _new_sv_from_object(str(self._name))
bound_method._interpreter = self._interpreter
return bound_method
def __dir__(self):
try:
Inspector = self._interpreter.use('Class::Inspector')
return [str(method) for method in Inspector.methods(self._name)]
except (ImportError, TypeError):
return []
class ListValue(tuple):
def ints(self):
return tuple(int(x) for x in self)
def floats(self):
return tuple(float(x) for x in self)
def strings(self):
return tuple(str(x) for x in self)
cdef class FunctionAttribute(object):
cdef object _name
cdef Interpreter _interpreter
def __init__(self, interpreter, name):
self._name = name
self._interpreter = interpreter
def __call__(self, *args, **kwds):
return call_sub(perl.G_SCALAR, self._name, None, self._interpreter, <perl.SV*>0, <perl.SV*>0, args, kwds)
def scalar_context(self, *args, **kwds):
return call_sub(perl.G_SCALAR, self._name, None, self._interpreter, <perl.SV*>0, <perl.SV*>0, args, kwds)
def list_context(self, *args, **kwds):
return call_sub(perl.G_ARRAY, self._name, None, self._interpreter, <perl.SV*>0, <perl.SV*>0, args, kwds)
def void_context(self, *args, **kwds):
return call_sub(perl.G_VOID, self._name, None, self._interpreter, <perl.SV*>0, <perl.SV*>0, args, kwds)
cdef object _sv_to_python(perl.SV *sv, object interpreter):
cdef perl.MAGIC* magic
cdef perl.SV* reffed
if(perl.SvROK(sv) and perl.sv_derived_from(sv, "Python::Object")):
reffed = perl.SvRV(sv)
magic = perl.mg_find(reffed, <int>('~'))
if(magic and magic[0].mg_virtual == &virtual_table):
obj = <object><void*>perl.SvIVX(reffed)
Py_INCREF(obj)
perl.SvREFCNT_dec(sv)
return obj
else:
raise AssertionError("should be unreachable")
return None
if sv:
ret = ScalarValue()
ret._interpreter = interpreter
ret._sv = sv
return ret
else:
return None
cdef int _free(perl.tTHX hx, perl.SV* sv, perl.MAGIC* mg):
obj = <object><void*>perl.SvIVX(sv)
Py_DECREF(obj)
return 0
cdef int _set(perl.tTHX hx, perl.SV* sv, perl.MAGIC* mg):
obj = <object><void*>perl.SvIVX(sv)
Py_INCREF(obj)
return 0
cdef perl.MGVTBL virtual_table
virtual_table.svt_free = _free
virtual_table.svt_set = _set
cdef perl.SV *_new_sv_from_object(object value):
cdef perl.SV* scalar_value
cdef perl.SV* ref_value
cdef perl.AV* array_value
cdef perl.HV* hash_value
cdef perl.MAGIC* magic
try:
if value is None:
return &perl.PL_sv_undef
elif isinstance(value, int):
return perl.newSViv(value)
elif isinstance(value, float):
return perl.newSVnv(value)
elif isinstance(value, str):
value = value.encode()
return perl.newSVpvn_utf8(value, len(value), True)
elif isinstance(value, bool):
if value:
return perl.SvREFCNT_inc(&perl.PL_sv_yes)
else:
return perl.SvREFCNT_inc(&perl.PL_sv_no)
elif isinstance(value, dict):
hash_value = perl.newHV()
for k, v in value.items():
k = str(k).encode()
perl.hv_store(hash_value, k, len(k), _new_sv_from_object(v), 0)
return perl.newRV_noinc(<perl.SV*>hash_value)
elif isinstance(value, ScalarValue):
return perl.SvREFCNT_inc((<ScalarValue>value)._sv)
elif isinstance(value, (list, tuple, xrange)):
array_value = perl.newAV()
for i in value:
perl.av_push(array_value, _new_sv_from_object(i))
return perl.newRV_noinc(<perl.SV*>array_value)
else:
ref_value = perl.newSV(0);
scalar_value = perl.newSVrv(ref_value, "Python::Object");
Py_INCREF(value)
perl.SvIV_set(scalar_value, <perl.IV><void*>value)
perl.sv_magic(scalar_value, scalar_value, <int>('~'), <char*>0, 0)
magic = perl.mg_find(scalar_value, <int>('~'))
magic[0].mg_virtual = &virtual_table
perl.SvREADONLY(scalar_value)
return ref_value
except:
return perl.SvREFCNT_inc(&perl.PL_sv_undef)
cdef _assign_sv(perl.SV *sv, object value):
if value is None:
perl.SvSetMagicSV(sv, &perl.PL_sv_undef)
elif isinstance(value, int):
perl.SvSetMagicSV(sv, perl.sv_2mortal(perl.newSViv(value)))
elif isinstance(value, float):
perl.SvSetMagicSV(sv, perl.sv_2mortal(perl.newSVnv(value)))
elif isinstance(value, ScalarValue):
perl.SvSetMagicSV(sv, (<ScalarValue>value)._sv)
else:
perl.SvSetMagicSV(sv, perl.sv_2mortal(_new_sv_from_object(value)))
cdef class ScalarValue:
"""
>>> import pyperler; i = pyperler.Interpreter()
>>> i.Sa = 3
>>> i.Sb = 3
>>> i.Sa == i.Sb
Traceback (most recent call last):
...
TypeError: Cannot use comparison operator on two perl scalar values '3' and '3'. Convert either one to string or to integer
>>> i.Sa == 3
True
>>> 3 == i.Sb
True
>>> 4 == i.Sb
False
>>> i.Sa == 4
False
>>> i.Sa == 3.001
False
>>> i.Sa < 3.001
True
>>> i.Sa > 3.001
False
>>> 3 < i.Sa
False
>>> 3 <= i.Sa
True
"""
cdef perl.SV *_sv
cdef Interpreter _interpreter
def __dealloc__(self):
perl.SvREFCNT_dec(self._sv)
def to_python(self, numeric_if_possible=True, force_scalar_to=None):
r"""
>>> import pyperler; i = pyperler.Interpreter()
>>> i('$a = 3')
3
>>> type(i.Sa.to_python()) is int
True
>>> i('@a = (1,2,3,4)')
4
>>> type(i.Aa.to_python()) is list
True
>>> i('%a = (a => 3, b => 4)')
4
>>> type(i.Ha.to_python()) is dict
True
>>> i('$b = undef')
<pyperler.undef>
>>> type(i.Sb.to_python()) is type(None)
True
>>> i('$c = "4.5"')
'4.5'
>>> type(i.Sc.to_python()) is float
True
>>> i('$d = "-4"')
'-4'
>>> type(i.Sd.to_python()) is int
True
>>> i('$e = "-4"')
'-4'
>>> type(i.Se.to_python(numeric_if_possible=False)) is str
True
>>> i.Se.to_python(force_scalar_to=float)
-4.0
>>> i('$f = "hello, world"')
'hello, world'
>>> i.Sf.to_python()
'hello, world'
>>> i.Sf.to_python(force_scalar_to=int)
0
"""
cdef perl.SV* ref_value
if not perl.SvOK(self._sv):
return None
if perl.SvROK(self._sv):
ref_value = perl.SvRV(self._sv)
if perl.SvTYPE(ref_value) == perl.SVt_PVAV:
return [x.to_python(numeric_if_possible, force_scalar_to) if isinstance(x, ScalarValue) else x for x in self]
if perl.SvTYPE(ref_value) == perl.SVt_PVHV:
return {(k.to_python(numeric_if_possible, force_scalar_to) if isinstance(k, ScalarValue) else k):
(v.to_python(numeric_if_possible, force_scalar_to) if isinstance(v, ScalarValue) else v) for k,v in self.items()}
if force_scalar_to is not None:
return force_scalar_to(self)
if numeric_if_possible:
if self._interpreter._is_numeric(self):
if self._interpreter._is_integer(self):
return int(self)
else:
return float(self)
return str(self)
def __str__(self):
u"""
Do some checks about copying the string, and accurate refcounting:
>>> import pyperler; i = pyperler.Interpreter()
>>> i.Sa = "abc" + str(type(i)).replace('type ','').replace('class ','') # i.Sa is assigned a temporary string object
>>> i.Sa
"abc<'pyperler.Interpreter'>"
>>> text = str(i.Sa)
>>> i.Sa = "def"
>>> text[:3]
'abc'
>>> i.Sa
'def'
"""
cdef size_t length = 0
cdef char *buffer = perl.SvPVutf8(self._sv, length)
return bytes(buffer[:length]).decode()
def __bytes__(self):
cdef size_t length = 0
cdef char *buffer = perl.SvPVbyte(self._sv, length)