forked from CyberShadow/RABCDAsm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
disassembler.d
1841 lines (1640 loc) · 43 KB
/
disassembler.d
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
/*
* Copyright 2010, 2011, 2012, 2013, 2014, 2015 Vladimir Panteleev <[email protected]>
* This file is part of RABCDAsm.
*
* RABCDAsm 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.
*
* RABCDAsm 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 RABCDAsm. If not, see <https://www.gnu.org/licenses/>.
*/
module disassembler;
import std.algorithm;
import std.array;
import std.conv;
import std.digest.md;
import std.exception;
import std.file;
import std.format;
import std.path;
import std.stdio;
import std.string;
import abcfile;
import asprogram;
import autodata;
import common;
alias std.array.join join;
final class StringBuilder
{
enum BUF_SIZE = 256*1024;
static char[] buf;
static size_t pos;
string filename;
File file;
this(string filename)
{
this.filename = filename;
if (exists(longPath(filename)))
throw new Exception(filename ~ " exists");
string[] dirSegments = split(filename, "/");
for (int l=0; l<dirSegments.length-1; l++)
{
auto subdir = join(dirSegments[0..l+1], "/");
if (subdir.length && !exists(longPath(subdir)))
mkdir(longPath(subdir));
}
file = openFile(filename, "wb");
assert(!pos, "Opening new file with unflushed buffer");
}
static this()
{
buf = new char[BUF_SIZE];
}
void put(in char[] s)
{
checkIndent();
auto end = pos + s.length;
if (end > buf.length)
{
flush();
end = s.length;
while (end > buf.length)
buf.length = buf.length*2;
}
buf[pos..end] = s[];
pos = end;
}
void put(char c)
{
if (pos == buf.length) // speed hack: no indent check
flush();
buf[pos++] = c;
}
alias put opCatAssign;
void write(T)(T v)
{
checkIndent();
formattedWrite(this, "%s", v);
}
void flush()
{
if (pos)
{
file.rawWrite(buf[0..pos]);
pos = 0;
}
}
void save()
{
flush();
file.close();
}
int indent;
bool indented;
string linePrefix;
void newLine()
{
this ~= '\n';
indented = false;
}
void noIndent()
{
indented = true;
}
void checkIndent()
{
if (!indented)
{
for (int i=0; i<indent; i++)
this ~= ' ';
indented = true;
if (linePrefix)
this ~= linePrefix;
}
}
}
final class RefBuilder : ASTraitsVisitor
{
bool[uint][string][ASType.Max] homonyms;
debug bool homonymsBuilt;
bool hasHomonyms(ASProgram.Namespace ns)
{
debug assert(homonymsBuilt);
auto pnsHomonyms = ns.name in homonyms[ns.kind];
auto nsHomonyms = pnsHomonyms ? *pnsHomonyms : null;
return nsHomonyms.length > 1;
}
void addHomonym(ASProgram.Namespace ns)
{
debug assert(!homonymsBuilt);
homonyms[ns.kind][ns.name][ns.id] = true;
}
/// Represents a link in a "context chain", which represents the context in which an object is encountered.
/// The common root of contexts is used to build ref strings, namespace labels, file paths etc.
/// Expansion is recursive and delayed until decompilation (an object may be encountered inside a private namespace,
/// all contexts of which are unknown until the whole program is scanned).
struct ContextItem
{
enum Type
{
Multiname, /// An ASProgram.Multiname (may be a private namespace, etc.)
String, /// Fixed string
Group, /// Multiple ContextItem[]s (which are expanded and the common root is taken as the result)
}
Type type;
union
{
ASProgram.Multiname multiname;
struct
{
string str;
bool filenameSuffix;
}
struct
{
ContextItem[] group;
string groupFallback;
}
}
struct Segment
{
char delim;
string str;
}
ContextItem[] reduceGroup(RefBuilder refs)
{
assert(type==Type.Group);
ContextItem[][] contexts;
foreach (context; group)
contexts ~= ContextItem.expand(refs, [context]);
ContextItem[] context;
if (contexts.length)
context = reduce!contextRoot(contexts);
if (!context.length)
context = /*null*/[ContextItem(groupFallback)];
return context;
}
Segment[] toSegments(RefBuilder refs, bool filename)
out(result)
{
debug(CONTEXTS) std.stdio.writefln("Segmented:\n\t%s\nto\n\t%s\n", this, result);
}
body
{
final switch(type)
{
case Type.Multiname:
{
assert(multiname.kind == ASType.QName);
auto ns = multiname.vQName.ns;
auto nsName = ns.name;
// if (refs.hasHomonyms(ns))
// nsName ~= '#' ~ to!string(ns.id);
if (nsName.length)
if (multiname.vQName.name.length)
return [Segment('/', nsName), Segment(filename ? '/' : ':', multiname.vQName.name)];
else
return [Segment('/', nsName)];
else
if (multiname.vQName.name.length)
return [Segment('/', multiname.vQName.name)];
else
assert(0);
}
case Type.String:
return [Segment((filename && filenameSuffix) ? '.' : '/', str)];
case Type.Group:
{
Segment[] segments;
foreach (context; reduceGroup(refs))
segments ~= context.toSegments(refs, filename);
return segments;
}
}
}
static ContextItem[] expand(RefBuilder refs, ContextItem[] context)
{
ContextItem[] newContext;
foreach (ref c; context)
{
auto cEx = c.expand(refs);
if (cEx)
newContext ~= cEx;
}
return newContext;
}
bool expanding;
/// Recursively expand contexts (lower to Type.String ContextItems)
ContextItem[] expand(RefBuilder refs)
in
{
debug(CONTEXTS) std.stdio.writefln("Expanding:\n\t%s\n", this);
}
out(result)
{
debug(CONTEXTS) std.stdio.writefln("Expanded:\n\t%s\nto\n\t%s\n", this, result);
}
body
{
if (expanding)
final switch (type)
{
case Type.String:
assert(0);
case Type.Multiname:
return (&this)[0..1];
case Type.Group:
return [ContextItem(groupFallback)];
}
assert(!expanding);
expanding = true;
scope(exit) expanding = false;
final switch (type)
{
case Type.Multiname:
switch (multiname.kind)
{
case ASType.QName:
{
auto ns = multiname.vQName.ns;
if (ns.kind == ASType.PrivateNamespace)
{
// auto pcontext = ns.id in refs.namespaces[ns.kind].contexts;
// if (pcontext is null)
// return (&this)[0..1];
// assert(pcontext);
auto context = refs.namespaces[ns.kind].getContext(refs, ns.id);
debug(CONTEXTS) std.stdio.writefln("Context of namespace %s is:\n\t%s\n", ns, context);
// auto expanded = expand(refs, context);
// if (expanded is null) return null;
return /*expanded*/context ~ (multiname.vQName.name.length ? [ContextItem(multiname.vQName.name)] : null); // hack
}
break;
}
case ASType.Multiname:
return multiname.vMultiname.name.length ? [ContextItem(multiname.vMultiname.name)] : null;
default:
debug
assert(false, text(multiname.kind));
else
break;
}
break;
case Type.String:
break;
case Type.Group:
return reduceGroup(refs);
}
return (&this)[0..1];
}
this(ASProgram.Multiname m)
{
this.type = Type.Multiname;
this.multiname = m;
}
this(string s, bool filenameSuffix = false)
{
this.type = Type.String;
this.str = s;
this.filenameSuffix = filenameSuffix;
}
this(ContextItem[] group, string groupFallback)
{
this.type = Type.Group;
this.group = group;
this.groupFallback = groupFallback;
}
mixin AutoCompare;
mixin AutoToString;
R processData(R, string prolog, string epilog, H)(ref H handler) const
{
mixin(prolog);
mixin(addAutoField("type"));
final switch (type)
{
case Type.Multiname:
mixin(addAutoField("multiname"));
break;
case Type.String:
mixin(addAutoField("str"));
mixin(addAutoField("filenameSuffix"));
break;
case Type.Group:
mixin(addAutoField("group"));
mixin(addAutoField("groupFallback"));
break;
}
mixin(epilog);
}
static bool similar(ref ContextItem i1, ref ContextItem i2)
{
if (i1.type != i2.type) return false;
final switch (i1.type)
{
case ContextItem.Type.String:
return i1.str == i2.str;
case ContextItem.Type.Multiname:
assert(i1.multiname.kind == ASType.QName && i2.multiname.kind == ASType.QName);
if (i1.multiname.vQName.name != i2.multiname.vQName.name) return false;
return nsSimilar(i1.multiname.vQName.ns, i2.multiname.vQName.ns);
case ContextItem.Type.Group:
return i1.group == i2.group;
}
}
// truncate=true -> return partial ContextItem
// truncate=false -> return null on partial match
static ContextItem[] combine(bool truncate)(ref ContextItem c1, ref ContextItem c2)
{
if (similar(c1, c2))
return [c1];
if (c1.type != ContextItem.Type.Multiname || c2.type != ContextItem.Type.Multiname)
return null;
if (c1.multiname.kind != ASType.QName || c2.multiname.kind != ASType.QName)
return null;
auto name1 = c1.multiname.vQName.name;
auto name2 = c2.multiname.vQName.name;
auto ns1 = c1.multiname.vQName.ns;
auto ns2 = c2.multiname.vQName.ns;
if (nsSimilar(ns1, ns2) && ns1.name.length && truncate)
{
auto m = new ASProgram.Multiname;
m.kind = ASType.QName;
m.vQName.ns = ns1;
return [ContextItem(m)];
}
if (name1 && !name2 && truncate)
{
swap(c1, c2);
swap(ns1, ns2);
swap(name1, name2);
}
if (!name1 && name2 && nsSimilar(ns1, ns2))
{
if (truncate)
{
auto m = new ASProgram.Multiname;
m.kind = ASType.QName;
m.vQName.ns = ns1;
return [ContextItem(m)];
}
else
return [c2];
}
if (ns1.name.length && ns2.name.length)
{
if (nsSimilar(ns1, ns2))
{
assert(name1 != name2); // handled by similar() check
static if (truncate)
assert(false); // handled above
else
{
if (name2.length)
return [c1, ContextItem(name2)];
else
return [c1];
}
}
if (ns1.name.length > ns2.name.length && truncate)
{
swap(c1, c2);
swap(ns1, ns2);
swap(name1, name2);
}
auto fullName1 = ns1.name ~ (name1 ? ':' ~ name1 : "");
auto fullName2 = ns2.name ~ (name2 ? ':' ~ name2 : "");
if (fullName2.startsWith(fullName1 ~ ":"))
return [truncate ? c1 : c2];
}
return null;
}
alias combine!true commonRoot;
alias combine!false deduplicate;
}
ContextItem[] context; // potential optimization: use array-based stack
void pushContext(T...)(T v) { context ~= ContextItem(v); }
void popContext() { context = context[0..$-1]; }
enum ContextPriority
{
declaration,
usage,
orphan,
max
}
struct ContextSet(T, bool ALLOW_DUPLICATES)
{
ContextItem[][T] contexts;
ContextItem[][][ContextPriority.max][T] contextSets;
debug bool contextsSealed;
string[T] names, filenames;
debug bool coagulated;
bool add(U)(U obj, ContextItem[] context, ContextPriority priority)
{
debug assert(!coagulated);
debug assert(!contextsSealed);
auto p = cast(T)obj;
auto pset = p in contextSets;
if (!pset)
{
contextSets[p] = contextSets[p].init;
contextSets[p][priority] ~= context.dup;
return true;
}
else
{
static bool rawEqual(T)(T[] arr1, T[] arr2) { return cast(ubyte[])arr1 == cast(ubyte[])arr2; }
if ((*pset)[priority].length==0 || !rawEqual((*pset)[priority][$-1], context)) // Optimization: don't add contexts identical to the last added
(*pset)[priority] ~= context.dup;
return false;
}
}
bool addIfNew(U)(U obj, ContextItem[] context, ContextPriority priority)
{
if (isAdded(obj))
return false;
else
return add(obj, context, priority);
}
void coagulate(RefBuilder refs)
{
debug assert(!coagulated);
int[string] collisionCounter;
T[string] first;
foreach (obj, set; contextSets)
if (obj !in contexts)
getContext(refs, obj);
foreach (obj; contexts.keys.sort())
{
auto context = contexts[obj];
auto bname = refs.contextToString(context, false);
auto bfilename = refs.contextToString(context, true);
auto pcounter = bname in collisionCounter;
int counter = pcounter ? *pcounter : 0;
if (counter==1)
{
auto firstObj = first[bname];
names[firstObj] ~= "#0";
filenames[firstObj] ~= "#0";
}
string suffix;
if (counter==0)
first[bname] = cast(T)obj;
else
suffix = '#' ~ to!string(counter);
names[obj] = bname ~ suffix;
filenames[obj] = bfilename ~ suffix;
collisionCounter[bname] = counter+1;
}
debug coagulated = true;
}
bool isAdded(U)(U obj) { return (cast(T)obj in contextSets) ? true : false; }
ContextItem[] getContext(U)(RefBuilder refs, U obj)
{
// debug assert(coagulated);
debug contextsSealed = true;
auto p = cast(T)obj;
auto pcontext = p in contexts;
if (pcontext)
return *pcontext;
ContextItem[][] set;
foreach (prioritySet; contextSets[p])
if (prioritySet)
set = prioritySet;
static if (ALLOW_DUPLICATES)
{
auto context = ContextItem.expand(refs, set[0]);
foreach (setContext; set[1..$])
context = contextRoot(context, ContextItem.expand(refs, setContext));
return contexts[p] = context;
}
else
{
if (set.length > 1)
return contexts[p] = [ContextItem("multireferenced")];
else
return contexts[p] = ContextItem.expand(refs, set[0]);
}
}
string getName(U)(U obj)
{
debug assert(coagulated);
auto pname = cast(T)obj in names;
// return pname?*pname:"##" ~ format(obj);
assert(pname, format("Unscanned object: ", obj));
return *pname;
}
static string[string] filenameMappings;
string getFilename(U)(U obj, string suffix)
{
debug assert(coagulated);
auto pname = cast(T)obj in filenames;
assert(pname, format("Unscanned object: ", obj));
auto filename = *pname;
string[] dirSegments = split(filename, "/");
for (int l=0; l<dirSegments.length; l++)
{
again:
string subpath = join(dirSegments[0..l+1], "/");
string subpathl = toLower(subpath);
string* canonicalp = subpathl in filenameMappings;
if (canonicalp && *canonicalp != subpath)
{
dirSegments[l] = dirSegments[l] ~ "_"; // not ~=
goto again;
}
filenameMappings[subpathl] = subpath;
}
filename = join(dirSegments, "/");
return filename ~ "." ~ suffix ~ ".asasm";
}
}
ContextSet!(uint, true)[ASType.Max] namespaces;
ContextSet!(void*, false) objects, scripts;
this(ASProgram as)
{
super(as);
}
bool[void*] orphans;
void addOrphan(T)(T obj) { orphans[cast(void*)obj] = true; }
bool isOrphan(T)(T obj) { return (cast(void*)obj in orphans) ? true : false; }
override void run()
{
foreach (i, vclass; as.orphanClasses)
addOrphan(vclass);
foreach (i, method; as.orphanMethods)
addOrphan(method);
super.run();
foreach (i, v; as.scripts)
{
ContextItem[] classContexts;
foreach (trait; v.traits)
{
if (trait.name.kind == ASType.QName && trait.name.vQName.ns.kind != ASType.PrivateNamespace)
classContexts ~= ContextItem(trait.name);
}
if (!classContexts.length)
foreach (trait; v.traits)
classContexts ~= ContextItem(trait.name);
context = [ContextItem(classContexts, "script_" ~ to!string(i))];
scripts.add(v, context, ContextPriority.declaration);
pushContext("init", true);
addMethod(v.sinit, ContextPriority.declaration);
context = null;
}
foreach (i, vclass; as.orphanClasses)
if (!objects.isAdded(vclass))
{
pushContext("orphan_class_" ~ to!string(i));
addClass(vclass, ContextPriority.orphan);
popContext();
}
foreach (i, method; as.orphanMethods)
if (!objects.isAdded(method))
{
pushContext("orphan_method_" ~ to!string(i));
addMethod(method, ContextPriority.orphan);
popContext();
}
scripts.coagulate(this);
// add namespaces referenced only at script level
foreach (v; as.scripts)
foreach (trait; v.traits)
if (trait.name.kind == ASType.QName)
namespaces[trait.name.vQName.ns.kind].addIfNew(trait.name.vQName.ns.id, scripts.getContext(this, v), ContextPriority.declaration);
foreach (id, b; possibleOrphanPrivateNamespaces)
if (!namespaces[ASType.PrivateNamespace].isAdded(id))
{
pushContext("orphan_namespace_" ~ to!string(id));
namespaces[ASType.PrivateNamespace].add(id, context, ContextPriority.orphan);
popContext();
}
debug homonymsBuilt = true;
foreach (ref namespace; namespaces)
namespace.coagulate(this);
objects.coagulate(this);
}
override void visitTrait(ref ASProgram.Trait trait)
{
auto m = trait.name;
// if (m.kind != ASType.QName)
// throw new Exception("Trait name is not a QName");
pushContext(m);
visitMultiname(m, ContextPriority.declaration);
switch (trait.kind)
{
case TraitKind.Slot:
case TraitKind.Const:
visitMultiname(trait.vSlot.typeName, ContextPriority.usage);
super.visitTrait(trait);
break;
case TraitKind.Class:
addClass(trait.vClass.vclass, ContextPriority.declaration);
pushContext("class", true);
visitTraits(trait.vClass.vclass.traits);
popContext();
pushContext("instance", true);
visitTraits(trait.vClass.vclass.instance.traits);
popContext();
break;
case TraitKind.Function:
addMethod(trait.vFunction.vfunction, ContextPriority.declaration);
super.visitTrait(trait);
break;
case TraitKind.Method:
addMethod(trait.vMethod.vmethod, ContextPriority.declaration);
super.visitTrait(trait);
break;
case TraitKind.Getter:
pushContext("getter");
addMethod(trait.vMethod.vmethod, ContextPriority.declaration);
popContext();
super.visitTrait(trait);
break;
case TraitKind.Setter:
pushContext("setter");
addMethod(trait.vMethod.vmethod, ContextPriority.declaration);
popContext();
super.visitTrait(trait);
break;
default:
super.visitTrait(trait);
break;
}
popContext();
}
static ContextItem[] contextRoot(ContextItem[] c1, ContextItem[] c2)
{
static bool uninteresting(ContextItem[] c)
{
// Do some validation while we're at it
foreach (cc; c)
assert(cc.type != ContextItem.Type.Group, "Groups should be expanded by now");
return
(c.length==1 && c[0].type==ContextItem.Type.String && c[0].str.startsWith("script_") && c[0].str.endsWith("_sinit")) ||
(c.length==1 && c[0].type==ContextItem.Type.String && c[0].str.startsWith("orphan_method_")) ||
false;
}
if (uninteresting(c1)) return c2;
if (uninteresting(c2)) return c1;
ContextItem[] c;
while (c.length<c1.length && c.length<c2.length)
{
auto root = ContextItem.commonRoot(c1[c.length], c2[c.length]);
assert(root.length <= 1);
if (root.length)
c ~= root;
else
break;
}
return c;
}
bool[uint] possibleOrphanPrivateNamespaces;
void visitNamespace(ASProgram.Namespace ns, ContextPriority priority)
{
if (ns is null) return;
// Add to homonyms
addHomonym(ns);
// Add to namespaces (for context)
assert(context.length > 0, "No context");
auto myPos = context.length;
foreach (i, ref item; context)
if (item.type == ContextItem.Type.Multiname && item.multiname.kind == ASType.QName && item.multiname.vQName.ns == ns)
{
myPos = i;
break;
}
if (ns.kind == ASType.PrivateNamespace && myPos == 0)
{
possibleOrphanPrivateNamespaces[ns.id] = true;
return;
}
auto myContext = context[0..myPos];
namespaces[ns.kind].add(ns.id, myContext, priority);
}
void visitNamespaceSet(ASProgram.Namespace[] nsSet, ContextPriority priority)
{
foreach (ns; nsSet)
visitNamespace(ns, priority);
}
void visitMultiname(ASProgram.Multiname m, ContextPriority priority)
{
if (m is null) return;
with (m)
switch (kind)
{
case ASType.QName:
case ASType.QNameA:
visitNamespace(vQName.ns, priority);
break;
case ASType.Multiname:
case ASType.MultinameA:
visitNamespaceSet(vMultiname.nsSet, priority);
break;
case ASType.MultinameL:
case ASType.MultinameLA:
visitNamespaceSet(vMultinameL.nsSet, priority);
break;
case ASType.TypeName:
visitMultiname(vTypeName.name, priority);
foreach (param; vTypeName.params)
visitMultiname(param, priority);
break;
default:
break;
}
}
void visitMethodBody(ASProgram.MethodBody b)
{
foreach (ref instruction; b.instructions)
foreach (i, type; opcodeInfo[instruction.opcode].argumentTypes)
switch (type)
{
case OpcodeArgumentType.Namespace:
visitNamespace(instruction.arguments[i].namespacev, ContextPriority.usage);
break;
case OpcodeArgumentType.Multiname:
visitMultiname(instruction.arguments[i].multinamev, ContextPriority.usage);
break;
case OpcodeArgumentType.Class:
pushContext("inline_class");
if (isOrphan(instruction.arguments[i].classv))
addClass(instruction.arguments[i].classv, ContextPriority.usage);
popContext();
break;
case OpcodeArgumentType.Method:
pushContext("inline_method");
if (isOrphan(instruction.arguments[i].methodv))
addMethod(instruction.arguments[i].methodv, ContextPriority.usage);
popContext();
break;
default:
break;
}
}
string contextToString(ContextItem[] context, bool filename)
in
{
debug(CONTEXTS) std.stdio.writefln("Stringizing:\n\t%s\n", context);
}
out(result)
{
debug(CONTEXTS) std.stdio.writefln("Stringized:\n\t%s\nto\n\t%s\n------------------\n", context, result);
}
body
{
context = ContextItem.expand(this, context);
if (!context.length)
return null;
foreach_reverse (i; 0..context.length-1)
{
auto root = ContextItem.deduplicate(context[i], context[i+1]);
if (root.length)
context = context[0..i] ~ root ~ context[i+2..$];
}
ContextItem.Segment[] segments;
foreach (ci; context)
segments ~= ci.toSegments(this, filename);
string escape(string s)
{
if (!filename)
return s;
string result;
foreach (c; s)
if (c == '.' || c == ':')
result ~= '/';
else
if (c == '\\' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|' || c < 0x20 || c >= 0x7F || c == ' ' || c == '%')
result ~= format("%%%02X", c);
else
result ~= c;
auto pathSegments = result.split("/");
if (!pathSegments.length)
pathSegments = [""];
foreach (ref pathSegment; pathSegments)
{
if (pathSegment == "")
pathSegment = "%";
static const reservedNames = ["CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"];
auto pathSegmentU = pathSegment.toUpper();
foreach (reservedName; reservedNames)
if (pathSegmentU.startsWith(reservedName) && (pathSegmentU.length == reservedName.length || pathSegmentU[reservedName.length]=='.'))
{
pathSegment = "%" ~ pathSegment;
break;
}
if (pathSegment.length > 240)
pathSegment = assumeUnique(pathSegment[0..200] ~ '-' ~ toHexString(md5Of(pathSegment)));
}
return arrayJoin(pathSegments, "/");
}
string[] strings = new string[segments.length];
foreach (i, ref s; segments)
strings[i] = (i>0 ? cast(string)[s.delim] : null) ~ escape(s.str);
return arrayJoin(strings);
}
bool addObject(T)(T obj, ContextPriority priority) { return objects.add(obj, context, priority); }
void addClass(ASProgram.Class vclass, ContextPriority priority)
{
addObject(vclass, priority);
pushContext("class", true);
pushContext("init", true);
addMethod(vclass.cinit, ContextPriority.declaration);
popContext(); // init
popContext(); // class
pushContext("instance", true);
pushContext("init", true);
addMethod(vclass.instance.iinit, ContextPriority.declaration);
popContext(); // init
visitMultiname(vclass.instance.name, ContextPriority.declaration);
visitMultiname(vclass.instance.superName, ContextPriority.usage);
visitNamespace(vclass.instance.protectedNs, ContextPriority.declaration);
foreach (iface; vclass.instance.interfaces)
visitMultiname(iface, ContextPriority.usage);
popContext(); // instance
}
void addMethod(ASProgram.Method method, ContextPriority priority)
{
if (addObject(method, priority))
{