-
Notifications
You must be signed in to change notification settings - Fork 10
/
waul-object
executable file
·1768 lines (1547 loc) · 72 KB
/
waul-object
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
#!/usr/bin/perl
# 99aeabc9ec7fe80b1b39f5e53dc7e49e <- self-modifying Perl magic
# state: 030b1e800b049dc08fac670c981f6004
# istate: caf90f5e1ff5a4b273faade4b138020c
# id: 4e04fdb8e560f4dd2ca4880b91a8e2ea
# This is a self-modifying Perl file. I'm sorry you're viewing the source (it's
# really gnarly). If you're curious what it's made of, I recommend reading
# http://github.com/spencertipping/writing-self-modifying-perl.
#
# If you got one of these from someone and don't know what to do with it, send
# it to spencer@spencertipping.com and I'll see if I can figure out what it
# does.
# For the benefit of HTML viewers (this is a hack):
# <div id='cover' style='position: absolute; left: 0; top: 0; width: 10000px; height: 10000px; background: white'></div>
$|++;
my %data;
my %transient;
my %externalized_functions;
my %datatypes;
my %locations; # Maps eval-numbers to attribute names
my $global_data = join '', <DATA>;
sub meta::define_form {
my ($namespace, $delegate) = @_;
$datatypes{$namespace} = $delegate;
*{"meta::${namespace}::implementation"} = $delegate;
*{"meta::$namespace"} = sub {
my ($name, $value, %options) = @_;
chomp $value;
$data{"${namespace}::$name"} = $value unless $options{no_binding};
&$delegate($name, $value) unless $options{no_delegate}}}
sub meta::eval_in {
my ($what, $where) = @_;
# Obtain next eval-number and alias it to the designated location
@locations{eval('__FILE__') =~ /\(eval (\d+)\)/} = ($where);
my $result = eval $what;
$@ =~ s/\(eval \d+\)/$where/ if $@;
warn $@ if $@;
$result}
meta::define_form 'meta', sub {
my ($name, $value) = @_;
meta::eval_in($value, "meta::$name")};
meta::meta('configure', <<'__');
# A function to configure transients. Transients can be used to store any number of
# different things, but one of the more common usages is type descriptors.
sub meta::configure {
my ($datatype, %options) = @_;
$transient{$_}{$datatype} = $options{$_} for keys %options;
}
__
meta::meta('externalize', <<'__');
# Function externalization. Data types should call this method when defining a function
# that has an external interface.
sub meta::externalize {
my ($name, $attribute, $implementation) = @_;
my $escaped = $name;
$escaped =~ s/[^A-Za-z0-9:]/_/go;
$externalized_functions{$name} = $externalized_functions{$escaped} = $attribute;
*{"::$name"} = *{"::$escaped"} = $implementation || $attribute;
}
__
meta::meta('functor::editable', <<'__');
# An editable type. This creates a type whose default action is to open an editor
# on whichever value is mentioned. This can be changed using different flags.
sub meta::functor::editable {
my ($typename, %options) = @_;
meta::configure $typename, %options;
meta::define_form $typename, sub {
my ($name, $value) = @_;
$options{on_bind} && &{$options{on_bind}}($name, $value);
meta::externalize $options{prefix} . $name, "${typename}::$name", sub {
my $attribute = "${typename}::$name";
my ($command, @new_value) = @_;
return &{$options{default}}(retrieve($attribute)) if ref $options{default} eq 'CODE' and not defined $command;
return edit($attribute) if $command eq 'edit' or $options{default} eq 'edit' and not defined $command;
return associate($attribute, @new_value ? join(' ', @new_value) : join('', <STDIN>)) if $command eq '=' or $command eq 'import' or $options{default} eq 'import' and not defined $command;
return retrieve($attribute)}}}
__
meta::meta('type::alias', <<'__');
meta::configure 'alias', inherit => 0, trim => 1;
meta::define_form 'alias', sub {
my ($name, $value) = @_;
meta::externalize $name, "alias::$name", sub {
# Can't pre-tokenize because shell::tokenize doesn't exist until the library::
# namespace has been evaluated (which will be after alias::).
shell::run(shell::tokenize($value), shell::tokenize(@_));
};
};
__
meta::meta('type::bootstrap', <<'__');
# Bootstrap attributes don't get executed. The reason for this is that because
# they are serialized directly into the header of the file (and later duplicated
# as regular data attributes), they will have already been executed when the
# file is loaded.
meta::configure 'bootstrap', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'bootstrap', sub {};
__
meta::meta('type::cache', <<'__');
meta::configure 'cache', inherit => 0, trim => 1;
meta::define_form 'cache', \&meta::bootstrap::implementation;
__
meta::meta('type::data', 'meta::functor::editable \'data\', extension => \'\', inherit => 0, default => \'cat\';');
meta::meta('type::function', <<'__');
meta::configure 'function', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'function', sub {
my ($name, $value) = @_;
meta::externalize $name, "function::$name", meta::eval_in("sub {\n$value\n}", "function::$name");
};
__
meta::meta('type::hook', <<'__');
meta::configure 'hook', extension => '.pl', inherit => 0, trim => 1;
meta::define_form 'hook', sub {
my ($name, $value) = @_;
*{"hook::$name"} = meta::eval_in("sub {\n$value\n}", "hook::$name");
};
__
meta::meta('type::inc', <<'__');
meta::configure 'inc', inherit => 1, extension => '.pl', trim => 1;
meta::define_form 'inc', sub {
use File::Path 'mkpath';
use File::Basename qw/basename dirname/;
my ($name, $value) = @_;
my $tmpdir = basename($0) . '-' . $$;
my $filename = "/tmp/$tmpdir/$name";
push @INC, "/tmp/$tmpdir" unless grep /^\/tmp\/$tmpdir$/, @INC;
mkpath(dirname($filename));
unless (-e $filename) {
open my $fh, '>', $filename;
print $fh $value;
close $fh;
}
};
__
meta::meta('type::indicator', <<'__');
# Shell indicator function. The output of each of these is automatically
# appended to the shell prompt.
meta::configure 'indicator', inherit => 1, extension => '.pl', trim => 1;
meta::define_form 'indicator', sub {
my ($name, $value) = @_;
*{"indicator::$name"} = meta::eval_in("sub {\n$value\n}", "indicator::$name");
};
__
meta::meta('type::internal_function', <<'__');
meta::configure 'internal_function', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'internal_function', sub {
my ($name, $value) = @_;
*{$name} = meta::eval_in("sub {\n$value\n}", "internal_function::$name");
};
__
meta::meta('type::js', 'meta::functor::editable \'js\', extension => \'.js\', inherit => 1;');
meta::meta('type::library', <<'__');
meta::configure 'library', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'library', sub {
my ($name, $value) = @_;
meta::eval_in($value, "library::$name");
};
__
meta::meta('type::message_color', <<'__');
meta::configure 'message_color', extension => '', inherit => 1, trim => 1;
meta::define_form 'message_color', sub {
my ($name, $value) = @_;
terminal::color($name, $value);
};
__
meta::meta('type::meta', <<'__');
# This doesn't define a new type. It customizes the existing 'meta' type
# defined in bootstrap::initialization. Note that horrible things will
# happen if you redefine it using the editable functor.
meta::configure 'meta', extension => '.pl', inherit => 1, trim => 1;
__
meta::meta('type::parent', <<'__');
meta::define_form 'parent', \&meta::bootstrap::implementation;
meta::configure 'parent', extension => '', inherit => 1, trim => 1;
__
meta::meta('type::retriever', <<'__');
meta::configure 'retriever', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'retriever', sub {
my ($name, $value) = @_;
$transient{retrievers}{$name} = meta::eval_in("sub {\n$value\n}", "retriever::$name");
};
__
meta::meta('type::sdoc', <<'__');
# A meta-type for other types. So retrieve('js::main') will work if you have
# the attribute 'sdoc::js::main'. The filename will be main.js.sdoc.
meta::functor::editable 'sdoc', inherit => 1, extension => sub {
extension_for(attribute($_[0])) . '.sdoc';
};
__
meta::meta('type::slibrary', <<'__');
meta::configure 'slibrary', extension => '.pl.sdoc', inherit => 1;
meta::define_form 'slibrary', sub {
my ($name, $value) = @_;
meta::eval_in(sdoc("slibrary::$name"), "slibrary::$name");
};
__
meta::meta('type::state', <<'__');
# Allows temporary or long-term storage of states. Nothing particularly insightful
# is done about compression, so storing alternative states will cause a large
# increase in size. Also, states don't contain other states -- otherwise the size
# increase would be exponential.
# States are created with the save-state function.
meta::configure 'state', inherit => 0, extension => '.pl', trim => 1;
meta::define_form 'state', \&meta::bootstrap::implementation;
__
meta::meta('type::template', <<'__');
meta::configure 'template', extension => '.pl', inherit => 1;
meta::define_form 'template', sub {
my ($name, $value) = @_;
meta::externalize "template::$name", "template::$name", meta::eval_in("sub {\n$value\n}", "template::$name");
};
__
meta::meta('type::waul', 'meta::functor::editable \'waul\', inherit => 1, extension => \'.waul\', default => \'edit\';');
meta::bootstrap('html', <<'__');
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8' />
<link rel='stylesheet' href='http://spencertipping.com/perl-objects/web/style.css'/>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js'></script>
<script src='http://spencertipping.com/caterwaul/caterwaul.all.min.js'></script>
<script src='http://spencertipping.com/montenegro/montenegro.client.js'></script>
<script src='http://spencertipping.com/perl-objects/web/attribute-parser.js'></script>
<script src='http://spencertipping.com/perl-objects/web/interface.js'></script>
</head>
<body></body>
</html>
__
meta::bootstrap('initialization', <<'__');
#!/usr/bin/perl
# 99aeabc9ec7fe80b1b39f5e53dc7e49e <- self-modifying Perl magic
# state: __state
# istate: __istate
# id: __id
# This is a self-modifying Perl file. I'm sorry you're viewing the source (it's
# really gnarly). If you're curious what it's made of, I recommend reading
# http://github.com/spencertipping/writing-self-modifying-perl.
#
# If you got one of these from someone and don't know what to do with it, send
# it to spencer@spencertipping.com and I'll see if I can figure out what it
# does.
# For the benefit of HTML viewers (this is a hack):
# <div id='cover' style='position: absolute; left: 0; top: 0; width: 10000px; height: 10000px; background: white'></div>
$|++;
my %data;
my %transient;
my %externalized_functions;
my %datatypes;
my %locations; # Maps eval-numbers to attribute names
my $global_data = join '', <DATA>;
sub meta::define_form {
my ($namespace, $delegate) = @_;
$datatypes{$namespace} = $delegate;
*{"meta::${namespace}::implementation"} = $delegate;
*{"meta::$namespace"} = sub {
my ($name, $value, %options) = @_;
chomp $value;
$data{"${namespace}::$name"} = $value unless $options{no_binding};
&$delegate($name, $value) unless $options{no_delegate}}}
sub meta::eval_in {
my ($what, $where) = @_;
# Obtain next eval-number and alias it to the designated location
@locations{eval('__FILE__') =~ /\(eval (\d+)\)/} = ($where);
my $result = eval $what;
$@ =~ s/\(eval \d+\)/$where/ if $@;
warn $@ if $@;
$result}
meta::define_form 'meta', sub {
my ($name, $value) = @_;
meta::eval_in($value, "meta::$name")};
__
meta::bootstrap('perldoc', <<'__');
=head1 Self-modifying Perl script
=head2 Original implementation by Spencer Tipping L<http://spencertipping.com>
The prototype for this script is licensed under the terms of the MIT source code license.
However, this script in particular may be under different licensing terms. To find out how
this script is licensed, please contact whoever sent it to you. Alternatively, you may
run it with the 'license' argument if they have specified a license that way.
You should not edit this file directly. For information about how it was constructed, go
to L<http://spencertipping.com/writing-self-modifying-perl>. For quick usage guidelines,
run this script with the 'usage' argument.
=cut
__
meta::cache('parent-identification', <<'__');
/home/spencertipping/bin/object 99aeabc9ec7fe80b1b39f5e53dc7e49e
/home/spencertipping/conjectures/perl-objects/js 246bc56c88e8e8daae3737dbb16a2a2c
/home/spencertipping/conjectures/perl-objects/sdoc a1e8480e579614c01dabeecf0f963bcc
object 99aeabc9ec7fe80b1b39f5e53dc7e49e
preprocessor 70dae4b46eb4e06798ec6f38d17d4c7b
__
meta::cache('parent-state', <<'__');
246bc56c88e8e8daae3737dbb16a2a2c 4b7d349f48353dcb3e5c5484bf18546c
70dae4b46eb4e06798ec6f38d17d4c7b e25c4729aff094da49d7b9903452bcea
99aeabc9ec7fe80b1b39f5e53dc7e49e 39f70215e806554b2130e45f1ad9c776
a1e8480e579614c01dabeecf0f963bcc 6a1b66304cbd4a94a05b0ef78f1e1bf4
__
meta::data('author', 'Spencer Tipping');
meta::data('default-action', 'shell');
meta::data('license', <<'__');
MIT License
Copyright (c) 2010 Spencer Tipping
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
__
meta::data('permanent-identity', '4e04fdb8e560f4dd2ca4880b91a8e2ea');
meta::function('ad', <<'__');
my ($options, @paths) = separate_options(@_);
@{$transient{path}} = () if $$options{-c};
return @{$transient{path}} = () unless @paths;
push @{$transient{path}}, @paths;
__
meta::function('alias', <<'__');
my ($name, @stuff) = @_;
@_ ? @stuff ? around_hook('alias', @_, sub {associate("alias::$name", join(' ', @stuff), execute => 1)})
: retrieve("alias::$name") // "Undefined alias $name"
: table_display([select_keys('--namespace' => 'alias')], [map retrieve($_), select_keys('--namespace' => 'alias')]);
__
meta::function('cat', 'join "\\n", retrieve(@_);');
meta::function('cc', <<'__');
# Stashes a quick one-line continuation. (Used to remind me what I was doing.)
@_ ? associate('data::current-continuation', hook('set-cc', join(' ', @_))) : retrieve('data::current-continuation');
__
meta::function('ccc', 'rm(\'data::current-continuation\');');
meta::function('child', <<'__');
around_hook('child', @_, sub {
my ($child_name) = @_;
clone($child_name);
enable();
qx($child_name update-from $0);
terminal::info("$child_name\'s identity is " . join '', qx($child_name identity));
disable()});
__
meta::function('clone', <<'__');
my ($options, @files) = separate_options(@_);
for my $file (@files) {
around_hook('clone', $file, sub {
hypothetically(sub {
# Assign a new object identity.
rm('data::permanent-identity');
identity();
file::write($file, serialize(), noclobber => 1);
chmod(0700, $file)})})}
__
meta::function('cp', <<'__');
my $from = shift @_;
my $value = retrieve($from);
associate($_, $value) for @_;
__
meta::function('create', <<'__');
my ($name, $value) = @_;
around_hook('create', $name, $value, sub {
return edit($name) if exists $data{$name};
associate($name, defined $value ? $value : '');
edit($name) unless defined $value});
__
meta::function('current-state', 'serialize(\'-pS\');');
meta::function('cwd', <<'__');
use Cwd qw/getcwd/;
getcwd();
__
meta::function('disable', 'hook(\'disable\', chmod_self(sub {$_[0] & 0666}));');
meta::function('edit', <<'__');
my ($options, @names) = separate_options(@_);
@names = select_keys('--criteria' => "^$$options{'--prefix'}.*" . join('.*', @names), %$options) if $$options{'--prefix'};
my ($name, @others) = @names;
die "cannot edit multiple attributes simultaneously (others are @others)" if @others;
die "$name is virtual or does not exist" unless exists $data{$name};
die "$name is inherited; use 'edit $name -f' to edit anyway" unless is($name, '-u') || is($name, '-d') || exists $$options{'-f'};
my $extension = extension_for($name);
around_hook('edit', @_, sub {
associate($name, invoke_editor_on($data{$name} // '', %$options, attribute => $name, extension => $extension), execute => 1)});
save() unless $data{'data::edit::no-save'} or state() eq $transient{initial};
'';
__
meta::function('edit-self', <<'__');
$global_data = invoke_editor_on($global_data);
save();
__
meta::function('enable', 'hook(\'enable\', chmod_self(sub {$_[0] | ($_[0] & 0444) >> 2}));');
meta::function('expanded-bootstrap', <<'__');
# Write headers into the bootstrap section. There is some subtle stuff going on
# here with the istate header. The idea is to provide other objects a very quick
# way to see whether our state has changed, but we don't want false positives.
# We would get a false positive if, for instance, we included the contents of
# parent:: attributes in the istate hash. The reason is that the parent::
# attribute contains a hash of every attribute provided by that parent, so any
# change in the parent would impact the istate of the child.
#
# The best way to deal with this is to treat parent:: attributes as being
# opaque; we record their existence or nonexistence, but we don't record their
# contents. We also look only at inheritable and unique attributes and fail to
# consider global state.
my $bootstrap_text = retrieve('bootstrap::initialization');
my $state = state();
my $istate = state('-iGP');
my $object_id = identity();
$bootstrap_text =~ s/__state/$state/g;
$bootstrap_text =~ s/__istate/$istate/g;
$bootstrap_text =~ s/__id/$object_id/g;
$bootstrap_text;
__
meta::function('export', <<'__');
# Exports data into a text file.
# export attr1 attr2 attr3 ... file.txt
my $name = pop @_;
@_ or die 'Expected filename';
file::write($name, join "\n", retrieve(@_));
__
meta::function('extern', '&{$_[0]}(retrieve(@_[1 .. $#_]));');
meta::function('grep', <<'__');
# Looks through attributes for a pattern. Usage is grep pattern [options], where
# [options] is the format as provided to select_keys.
my ($pattern, @args) = @_;
my ($options, @criteria) = separate_options(@args);
my @attributes = select_keys(%$options, '--criteria' => join('|', @criteria));
$pattern = qr/$pattern/;
my @m_attributes;
my @m_line_numbers;
my @m_lines;
for my $k (@attributes) {
next unless length $k;
my @lines = split /\n/, retrieve($k);
for (0 .. $#lines) {
next unless $lines[$_] =~ $pattern;
push @m_attributes, $k;
push @m_line_numbers, $_ + 1;
push @m_lines, '' . ($lines[$_] // '')}}
unless ($$options{'-C'}) {
s/($pattern)/\033[1;31m\1\033[0;0m/g for @m_lines;
s/^/\033[1;34m/o for @m_attributes;
s/^/\033[1;32m/o && s/$/\033[0;0m/o for @m_line_numbers}
table_display([@m_attributes], [@m_line_numbers], [@m_lines]);
__
meta::function('hash', 'fast_hash(@_);');
meta::function('hook', <<'__');
my ($hook, @args) = @_;
$transient{active_hooks}{$hook} = 1;
dangerous('', sub {&$_(@args)}) for grep /^hook::${hook}::/, sort keys %data;
@args;
__
meta::function('hooks', 'join "\\n", sort keys %{$transient{active_hooks}};');
meta::function('identity', <<'__');
retrieve('data::permanent-identity') or
associate('data::permanent-identity', fast_hash(join '|', map rand(), 1 .. 32));
__
meta::function('import', <<'__');
my $name = pop @_;
associate($name, @_ ? join('', map(file::read($_), @_)) : join('', <STDIN>));
__
meta::function('initial-state', '$transient{initial};');
meta::function('is', <<'__');
my ($attribute, @criteria) = @_;
my ($options, @stuff) = separate_options(@criteria);
exists $data{$attribute} and attribute_is($attribute, %$options);
__
meta::function('load-state', <<'__');
around_hook('load-state', @_, sub {
my ($state_name) = @_;
my $state = retrieve("state::$state_name");
terminal::state('saving current state into _...');
save_state('_');
delete $data{$_} for grep ! /^state::/, keys %data;
%externalized_functions = ();
terminal::state("restoring state $state_name...");
meta::eval_in($state, "state::$state_name");
terminal::error(hook('load-state-failed', $@)) if $@;
reload();
verify()});
__
meta::function('lock', 'hook(\'lock\', chmod_self(sub {$_[0] & 0555}));');
meta::function('ls', <<'__');
my ($options, @criteria) = separate_options(@_);
my ($external, $shadows, $sizes, $flags, $long, $hashes, $parent_hashes) = @$options{qw(-e -s -z -f -l -h -p)};
$sizes = $flags = $hashes = $parent_hashes = 1 if $long;
return table_display([grep ! exists $data{$externalized_functions{$_}}, sort keys %externalized_functions]) if $shadows;
my $criteria = join('|', @criteria);
my @definitions = select_keys('--criteria' => $criteria, '--path' => $transient{path}, %$options);
my %inverses = map {$externalized_functions{$_} => $_} keys %externalized_functions;
my @externals = map $inverses{$_}, grep length, @definitions;
my @internals = grep length $inverses{$_}, @definitions;
my @sizes = map sprintf('%6d %6d', length(serialize_single($_)), length(retrieve($_))), @{$external ? \@internals : \@definitions} if $sizes;
my @flags = map {my $k = $_; join '', map(is($k, "-$_") ? $_ : '-', qw(d i m u))} @definitions if $flags;
my @hashes = map fast_hash(retrieve($_)), @definitions if $hashes;
my %inherited = parent_attributes(grep /^parent::/o, keys %data) if $parent_hashes;
my @parent_hashes = map $inherited{$_} || '-', @definitions if $parent_hashes;
join "\n", map strip($_), split /\n/, table_display($external ? [grep length, @externals] : [@definitions],
$sizes ? ([@sizes]) : (), $flags ? ([@flags]) : (), $hashes ? ([@hashes]) : (), $parent_hashes ? ([@parent_hashes]) : ());
__
meta::function('metadata-from', <<'__');
my ($filename) = @_;
my %metadata;
# Not using file::read because we only need the first few lines.
open my($fh), '<', $filename or return {};
while (<$fh>) {
/^#\s*(\w+):\s*(.*)$/ and $metadata{$1} = $2;
last unless /^#/;
}
close $fh;
\%metadata;
__
meta::function('minify-uglify', <<'__');
# Minify using uglifyjs compressor
my ($options, @filenames) = separate_options(@_);
my $nomunge = $$options{-m} ? '' : '-nm';
my $lift = $$options{-L} ? '' : '--lift-vars';
for my $filename (@filenames) {
my $minified = $filename;
$minified =~ s/\.js$/.min.js/;
terminal::info("minifying $filename");
file::write($minified, join '', qx(uglifyjs $nomunge $lift "$filename"));
}
__
meta::function('minify-yui', <<'__');
# Minify using YUI compressor
my ($options, @filenames) = separate_options(@_);
my $nomunge = $$options{-m} ? '' : '--nomunge';
my $linebreak = $$options{-B} ? '' : '--line-break 160';
for my $filename (@filenames) {
my $minified = $filename;
$minified =~ s/\.js$/.min.js/;
terminal::info("minifying $filename");
file::write($minified, join '', qx(yuicompressor $nomunge $linebreak "$filename"));
}
__
meta::function('mv', <<'__');
my ($from, $to) = @_;
die "'$from' does not exist" unless exists $data{$from};
associate($to, retrieve($from), execute => 1);
rm($from);
__
meta::function('name', <<'__');
my $name = $0;
$name =~ s/^.*\///;
$name;
__
meta::function('parents', 'join "\\n", grep s/^parent:://o, sort keys %data;');
meta::function('perl', <<'__');
my @result = eval(join ' ', @_);
$@ ? terminal::error($@) : wantarray ? @result : $result[0];
__
meta::function('preprocess', <<'__');
# Implements a simple preprocessing language.
# Syntax follows two forms. One is the 'line form', which gives you a way to specify arguments inline
# but not spanning multiple lines. The other is 'block form', which gives you access to both one-line
# arguments and a block of lines. The line parameters are passed in verbatim, and the block is
# indentation-adjusted and then passed in as a second parameter. (Indentation is adjusted to align
# with the name of the command.)
#
# Here are the forms:
#
# - line arguments to function
#
# - block line arguments << eof
# block contents
# block contents
# ...
# - eof
my ($string, %options) = @_;
my $expansions = 0;
my $old_string = '';
my $limit = $options{expansion_limit} || 100;
my @pieces = ();
sub adjust_spaces {
my ($spaces, $string) = @_;
$string =~ s/^$spaces //mg;
chomp $string;
$string;
}
while ($old_string ne $string and $expansions++ < $limit) {
$old_string = $string;
while ((my @pieces = split /(^(\h*)-\h \S+ \h* \V* <<\h*(\w+)$ \n .*? ^\2-\h\3$)/xms, $string) > 1 and $expansions++ < $limit) {
$pieces[1 + ($_ << 2)] =~ /^ (\h*)-\h(\S+)\h*(\V*)<<\h*(\w+)$ \n(.*?) ^\1-\h\4 $/xms && $externalized_functions{"template::$2"} and
$pieces[1 + ($_ << 2)] = &{"template::$2"}($3, adjust_spaces($1, $5))
for 0 .. $#pieces / 4;
@pieces[2 + ($_ << 2), 3 + ($_ << 2)] = '' for 0 .. $#pieces / 4;
$string = join '', @pieces;
}
if ((my @pieces = split /^(\h*-\h \S+ \h* .*)$/xom, $string) > 1) {
$pieces[1 + ($_ << 1)] =~ /^ \h*-\h(\S+)\h*(.*)$/xom && $externalized_functions{"template::$1"} and
$pieces[1 + ($_ << 1)] = &{"template::$1"}($2)
for 0 .. $#pieces >> 1;
$string = join '', @pieces;
}
}
$string;
__
meta::function('rd', <<'__');
if (@_) {my $pattern = join '|', @_;
@{$transient{path}} = grep $_ !~ /^$pattern$/, @{$transient{path}}}
else {pop @{$transient{path}}}
__
meta::function('reload', 'around_hook(\'reload\', sub {execute($_) for grep ! /^bootstrap::/, keys %data});');
meta::function('rm', <<'__');
around_hook('rm', @_, sub {
exists $data{$_} or terminal::warning("$_ does not exist") for @_;
delete @data{@_}});
__
meta::function('rmparent', <<'__');
# Removes one or more parents.
my ($options, @parents) = separate_options(@_);
my $clobber_divergent = $$options{'-D'} || $$options{'--clobber-divergent'};
my %parents = map {$_ => 1} @parents;
my @other_parents = grep !$parents{$_}, grep s/^parent:://, select_keys('--namespace' => 'parent');
my %kept_by_another_parent;
$kept_by_another_parent{$_} = 1 for grep s/^(\S+)\s.*$/\1/, split /\n/o, cat(@other_parents);
for my $parent (@parents) {
my $keep_parent_around = 0;
for my $line (split /\n/, retrieve("parent::$parent")) {
my ($name, $hash) = split /\s+/, $line;
next unless exists $data{$name};
my $local_hash = fast_hash(retrieve($name));
if ($clobber_divergent or $hash eq $local_hash or ! defined $hash) {rm($name) unless $kept_by_another_parent{$name}}
else {terminal::info("local attribute $name exists and is divergent; use rmparent -D $parent to delete it");
$keep_parent_around = 1}}
$keep_parent_around ? terminal::info("not deleting parent::$parent so that you can run", "rmparent -D $parent if you want to nuke divergent attributes too")
: rm("parent::$parent")}
__
meta::function('save', 'around_hook(\'save\', sub {dangerous(\'\', sub {file::write($0, serialize(\'-V\')); $transient{initial} = state()}) if verify()});');
meta::function('save-state', <<'__');
# Creates a named copy of the current state and stores it.
my ($state_name) = @_;
around_hook('save-state', $state_name, sub {
associate("state::$state_name", current_state(), execute => 1)});
__
meta::function('sdoc', <<'__');
# Applies SDoc processing to a file or attribute. Takes the file or attribute
# name as the first argument and returns the processed text.
my %comments_for_extension =
qw|c /*,*/ cpp // cc // h /*,*/ java // py # rb # pl # pm # ml (*,*) js //
hs -- sh # lisp ;;; lsp ;;; s # scm ;;; sc ;;; as // html <!--,--> mli (*,*) cs //
vim " elisp ; bas ' ada -- asm ; awk # bc # boo # tex % fss (*,*) erl %
scala // hx // io // j NB. lua -- n // m % php // sql -- pov // pro %
r # self "," tcl # texi @c tk # csh # vala // vbs ' v /*,*/ vhdl -- ss ;;;
haml -# sass /*,*/ scss /*,*/ css /*,*/ fig / waul # hh // ps % canard nb[,]|;
# No extension suggests a shebang line, which generally requires # to denote a comment.
$comments_for_extension{''} = '#';
my $generated_string = 'Generated by SDoc';
sub is_code {map /^\s*[^A-Z\|\s]/o, @_}
sub is_blank {map /^\n/o, @_}
sub comment {my ($text, $s, $e) = @_; join "\n", map("$s $_" . (length $e ? " $e" : ''), split /\n/, $text)}
sub paragraphs {map split(/(\n(?:\h*\n)+)/, $_), @_}
my ($filename, $specified_extension) = @_;
my $logical_filename = $filename =~ /^sdoc::(.*)$/ ? $1 : $filename;
# Two possibilities here. One is that the filename is an attribute, in which case
# we want to look up the extension in the transients table. The other is that
# it's a real filename.
my $extension = $specified_extension || extension_for($logical_filename) || ($filename =~ /\.sdoc$/io ? $filename =~ /\.(\w+)\.sdoc$/igo : $filename =~ /\.(\w+)$/igo)[0];
$extension =~ s/^\.//o;
my ($start, $end) = split /,/o, $comments_for_extension{lc $extension} // $comments_for_extension{''} // '#';
join '', map(is_code($_) || is_blank($_) ? ($_ =~ /^\s*c\n(.*)$/so ? $1 : $_) : comment($_, $start, $end), paragraphs retrieve($filename)),
"\n" . comment($generated_string, $start, $end) . "\n";
__
meta::function('sdoc-html', <<'__');
# Converts SDoc to logically-structured HTML. Sections end up being nested,
# and code sections and examples are marked as such. For instance, here is some
# sample output:
# <div class='section level1'>
# <h1 class='title'>Foo</h1>
# <p>This is a paragraph...</p>
# <p>This is another paragraph...</p>
# <pre class='code'>int main () {return 0;}</pre>
# <pre class='quoted'>int main () {return 0} // Won't compile</pre>
# <div class='section level2'>
# <h2 class='title'>Bar</h2>
# ...
# </div>
# </div>
# It is generally good about escaping things that would interfere with HTML,
# but within text paragraphs it lets you write literal HTML. The heuristic is
# that known tags that are reasonably well-formed are allowed, but unknown ones
# are escaped.
my ($attribute) = @_;
my @paragraphs = split /\n(?:\s*\n)+/, retrieve($attribute);
my $known_tags = join '|', qw[html head body meta script style link title div a span input button textarea option select form label iframe blockquote code caption
table tbody tr td th thead tfoot img h1 h2 h3 h4 h5 h6 li ol ul noscript p pre samp sub sup var canvas audio video strong em];
my $section_level = 0;
my @markup;
my $indent = sub {' ' x ($_[0] || $section_level)};
my $unindent = sub {my $spaces = ' ' x ($section_level - 1); s/^$spaces//gm};
my $escape_all = sub {s/&/&/g; s/</</g; s/>/>/g};
my $escape_some = sub {s/&/&/g; s/<(?!\/|($known_tags)[^>]*>.*<\/\1>)/</gs};
my $code = sub {&$escape_all(); &$unindent(); s/^c\n//; push @markup, &$indent() . "<pre class='code'>$_</pre>"};
my $quoted = sub {&$escape_all(); &$unindent(); s/^\|(\s?)/ \1/; s/^ //mg; push @markup, &$indent() . "<pre class='quoted'>$_</pre>"};
my $paragraph = sub {&$escape_some(); push @markup, &$indent() . "<p>$_</p>"};
my $section = sub {my $h = $_[0] > 6 ? 6 : $_[0]; push @markup, &$indent($_[0] - 1) . "<div class='section level$_[0]'>", &$indent($_[0]) . "<h$h>$2</h$h>"};
my $close_section = sub {push @markup, &$indent($_[0]) . "</div>"};
my $title = sub {
my $indentation = (length($1) >> 1) + 1;
&$close_section($section_level) while $section_level-- >= $indentation;
&$section($indentation);
$section_level = $indentation;
};
for (@paragraphs) {
&$code(), next unless /^\h*[A-Z|]/;
&$quoted(), next if /^\h*\|/;
&$title(), s/^.*\n// if /^(\s*)(\S.*)\.\n([^\n]+)/ and length("$1$2") < 60 and length("$1$2") - 10 < length($3);
&$paragraph();
}
&$close_section($section_level) while $section_level--;
join "\n", @markup;
__
meta::function('sdoc-markdown', <<'__');
# Renders a chunk of SDoc as Markdown. This involves converting quoted and
# unquoted code and section headings, but not numbered lists.
my ($attribute) = @_;
my $extension = extension_for($attribute =~ /^sdoc::(.*)$/g) || ($attribute =~ /.*?\.([^\.]+)(?:\.sdoc)?$/gi)[0];
my @paragraphs = split /\n(?:\s*\n)+/, retrieve($attribute);
my $section_level = 0;
my @markup;
my $indent = sub {' ' x ($_[0] || $section_level)};
my $unindent = sub {my $spaces = ' ' x ($section_level - 1); s/^$spaces//gm; $_};
my $code = sub {&$unindent(); s/^c\n//; push @markup, "```$extension\n$_\n```"};
my $quoted = sub {&$unindent(); s/^\|(\s?)/ \1/; s/^ //mg; push @markup, join("\n", map &$indent(2) . $_, split /\n/)};
my $heading = sub {'#' x $_[0]};
my $section = sub {&$unindent(); push @markup, &$heading($_[0]) . ' ' . $2};
my $title = sub {
my $indentation = (length($1) >> 1) + 1;
&$section($indentation);
$section_level = $indentation;
};
for (@paragraphs) {
&$code(), next unless /^\h*[A-Z|]/;
&$quoted(), next if /^\h*\|/;
&$title(), s/^.*\n// if /^(\s*)(\S.*)\.\n([^\n]+)/ and length("$1$2") < 60 and length("$1$2") - 10 < length($3);
push @markup, join "\n", map &$unindent(), split /\n/;
}
join "\n\n", @markup;
__
meta::function('sdoc-packed', <<'__');
# An SDoc preprocessor that removes all comment paragraphs. Paragraph breaks
# are preserved, and no "generated by SDoc" string is added.
join "\n", grep /^\s*[^A-Z| ]/, split /\n(?:\s*\n)+/, retrieve(@_);
__
meta::function('sdocp', <<'__');
# Renders an attribute as SDocP. This logic was taken directly from the sdoc script.
my $attribute = retrieve($_[0]);
sub escape {my @results = map {s/\\/\\\\/go; s/\n/\\n/go; s/'/\\'/go; $_} @_; wantarray ? @results : $results[0]}
"sdocp('" . escape($_[0]) . "', '" . escape($attribute) . "');";
__
meta::function('serialize', <<'__');
my ($options, @criteria) = separate_options(@_);
delete $$options{'-P'};
my $partial = delete $$options{'-p'};
my $criteria = join '|', @criteria;
my @attributes = map serialize_single($_), select_keys(%$options, '-m' => 1, '--criteria' => $criteria), select_keys(%$options, '-M' => 1, '--criteria' => $criteria);
my @final_array = @{$partial ? \@attributes : [expanded_bootstrap(), @attributes, 'internal::main();', '', '__DATA__', $global_data]};
join "\n", @final_array;
__
meta::function('serialize-single', <<'__');
# Serializes a single attribute and optimizes for content.
my $name = $_[0] || $_;
my $contents = retrieve_trimmed($name);
my $meta_function = 'meta::' . namespace($name);
my $invocation = attribute($name);
if ($contents !~ /\v/) {
$contents =~ s/\\/\\\\/go;
$contents =~ s/'/\\'/go;
return "$meta_function('$invocation', '$contents');"}
my $delimiter = '__' . fast_hash($contents);
my $chars = 2;
++$chars until $chars >= length($delimiter) || index("\n$contents", "\n" . substr($delimiter, 0, $chars)) == -1;
$delimiter = substr($delimiter, 0, $chars);
"$meta_function('$invocation', <<'$delimiter');\n$contents\n$delimiter";
__
meta::function('sh', <<'__');
around_hook('sh', @_, sub {
system(@_)});
__
meta::function('shb', <<'__');
# Backgrounded shell.
with_fork(@_, \&::sh);
__
meta::function('shell', <<'__');
my ($options, @arguments) = separate_options(@_);
$transient{repl_prefix} = $$options{'--repl-prefix'};
terminal::cc(retrieve('data::current-continuation')) if length $data{'data::current-continuation'};
around_hook('shell', sub {shell::repl(%$options)});
__
meta::function('size', <<'__');
my $size = 0;
$size += length $data{$_} for keys %data;
sprintf " full logical unique self\n% 7d % 7d % 7d % 7d", length(serialize()), $size, length(serialize('-up')), length $global_data;
__
meta::function('snapshot', <<'__');
my ($name) = @_;
file::write(my $finalname = temporary_name($name), serialize(), noclobber => 1);
chmod 0700, $finalname;
hook('snapshot', $finalname);
__
meta::function('snapshot-if-necessary', 'snapshot() if state() ne $transient{initial};');
meta::function('state', <<'__');
my ($options, @attributes) = separate_options(@_);
@attributes = grep !is($_, '-v'), sort keys %data unless @attributes;
@attributes = grep is($_, '-iu'), @attributes if $$options{'-i'};
@attributes = grep is($_, '-P'), @attributes if $$options{'-P'};
my $hash = fast_hash(fast_hash(scalar @attributes) . join '|', @attributes);
$hash = fast_hash(retrieve_trimmed($_) . "|$hash") for @attributes;
$hash = fast_hash(join '|', $hash, grep s/^parent:://, sort keys %data)
if $$options{'-P'};
$$options{'-G'} ? $hash : fast_hash("$global_data|$hash");
__
meta::function('touch', 'associate($_, \'\') for @_;');
meta::function('unlock', 'hook(\'unlock\', chmod_self(sub {$_[0] | 0200}));');
meta::function('update', 'update_from(@_, grep s/^parent:://o, sort keys %data);');
meta::function('update-from', <<'__');
# Upgrade all attributes that aren't customized. Customization is defined when the data type is created,
# and we determine it here by checking for $transient{inherit}{$type}.
# Note that this assumes you trust the remote script. If you don't, then you shouldn't update from it.
around_hook('update-from-invocation', separate_options(@_), sub {
my ($options, @targets) = @_;
my %parent_id_cache = cache('parent-identification');
my %parent_state_cache = cache('parent-state');
my %already_seen;
@targets or return;
my @known_targets = grep s/^parent:://, parent_ordering(map "parent::$_", grep exists $data{"parent::$_"}, @targets);
my @unknown_targets = grep ! exists $data{"parent::$_"}, @targets;
@targets = (@known_targets, @unknown_targets);
my $save_state = $$options{'-s'} || $$options{'--save'};
my $no_state = $$options{'-S'} || $$options{'--no-state'};
my $no_verify = $$options{'-V'} || $$options{'--no-verify'};
my $no_parents = $$options{'-P'} || $$options{'--no-parent'} || $$options{'--no-parents'};
my $force = $$options{'-f'} || $$options{'--force'};
my $clobber_divergent = $$options{'-D'} || $$options{'--clobber-divergent'};
my $can_skip_already_seen = !($$options{'-K'} || $$options{'--no-skip'}) &&
!$force && !$clobber_divergent;
save_state('before-update') unless $no_state;
for my $target (@targets) {
dangerous("updating from $target", sub {
around_hook('update-from', $target, sub {
my $target_filename = strip(qx(which $target)) || $target;
my %parent_metadata = %{metadata_from($target_filename)};
terminal::warning("$target_filename has no externally visible metadata (makes updating slower)") unless $parent_metadata{id};
my $identity = $parent_id_cache{$target} ||= $parent_metadata{id} || join '', qx($target identity);
next if $can_skip_already_seen and
exists $data{"parent::$target"} and
$already_seen{$identity} || $parent_state_cache{$identity} eq $parent_metadata{istate};
my $attributes = join '', qx($target ls -ahiu);
my %divergent;
die "skipping unreachable $target" unless $attributes;
# These need to come after the reachability check so that we retry against
# other copies in case something fails.
++$already_seen{$identity};
$parent_state_cache{$identity} = $parent_metadata{istate} || join '', qx($target state -iPG);
for my $to_rm (split /\n/, retrieve("parent::$target")) {
my ($name, $hash) = split(/\s+/, $to_rm);
next unless exists $data{$name};
my $local_hash = fast_hash(retrieve($name));