forked from Co-dfns/Co-dfns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodfns.nw
3457 lines (2826 loc) · 120 KB
/
codfns.nw
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
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{noweb}
\pagestyle{noweb}
\noweboptions{longxref}
\usepackage{fontspec}
\usepackage{unicode-math}
\setmainfont[Ligatures=TeX]{Libre Baskerville}
\setsansfont[Ligatures=TeX]{Lucida Sans Unicode}
\setmonofont{APL385 Unicode}
\setmathfont{Cambria Math}
\usepackage{polyglossia}
\setdefaultlanguage[variant=american]{english}
\usepackage{hyperref}
\usepackage{booktabs}
\begin{document}
@
\title{The Co-dfns Compiler}
\author{Aaron W. Hsu}
\maketitle
\vfill
\noindent
Co-dfns Compiler: High-performance, Parallel APL Compiler\\
Copyright $\copyright$ 2011-2022 Aaron W. Hsu <[email protected]>
\medskip
\noindent
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
\medskip
\noindent
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 Affero General Public License for more details.\medskip
\noindent
You should have received a copy of the GNU Affero General Public License
along with this program.
If not, see http://gnu.org/licenses.
\medskip
\noindent
\emph{This program is available under other license terms. Please contact
Aaron W. Hsu <[email protected]> for more information.}
\clearpage
\tableofcontents
\clearpage
\section{Introduction}
\subsection{How to Read a WEB}
\section{User's Guide}
\section{Co-dfns Architecture}
This section describes the ``big picture'' parts of the Co-dfns compiler.
The intent here is to try to show how all of the various moving parts
of the compiler fit together,
to provide a sort of road map that will give you a precise plan
for understanding how the various components affect one another.
One of the most important things to understand in any compiler
is the net effect a local change in the code
can have on the rest of the system,
so I hope that this section will help to clarify this.
The design of the Co-dfns compiler is one of austerity and minimalism.
My intent is, was, and hopefully shall remain that of producing an
exceptionally clear design that avoids or eliminates unnecessary
code and complexity within the design.
I attack this problem in many ways, but I primarily attempt to do
this by both reducing the size of the code surface in total,
that is, write less code, as well as reducing the number of entry
points and paths through that code.
In other words, my ideal design is one in which you enter the
compiler in some limited, but well defined and useful set of entry
points, and then proceed in a linear fashion through the code as the
execution path, resulting finally in your result.
This is the ``ultimate'' in data flow, functionally oriented programming.
The ramifications of this design choice implies a few important things.
Firstly, it implies that I reduce and eliminate any code
that represents boilerplate or that does not actively contribute
to the ``big picture'' of the code.
This is required in an extreme degree if I am to reduce the overall
complexity of the design.
This also implies that there is very little intentional redundancy in
the shape and style of the source,
making it very terse and compact.
Since there are intentionally very few entry and exit points through
the control flow of the code,
this reduces the number of dependencies for me to be aware of when
dealing with a single piece of code,
but this also comes at the cost of not being able to see many examples
of the interfaces with that code.
Often, there will be one, and only one place, in which a given piece
of code is used, and I do not want the code to needlessly store
excess information in its source that doesn't need to be there.
This all culminates in something that can be quite shocking at first:
making a change to the source is almost always a big deal.
If all the source code is meaningful and carefully constructed,
this also means that changing this code is almost always
non-trivial, because if the code represented something trivial,
I would have tried to remove it from the code so that only the
``big things'' were in the code itself.
Thus, anyone who wishes to view and read the compiler code should
take it upon themselves to appreciate the way in which the code flows
together,
and how the flow of the program runs,
as doing so will be essential to understanding how to make changes to
the source without breaking something.
Fortunately, this does come with the intended benefits of a very
short and simple codebase that has clear flow through the system,
it just means that if you want to change something,
make sure you realize that you are almost always likely to be working
at the ``architectural'' level, rather than at the small and trivial
level of details.
The compiler is designed to fit into a single Dyalog APL namespace,
and importantly, we do not define additional nested namespaces or
other forms of name hiding.
I intentionally want to restrict the namespace to a single global one.
This single global namespace should therefore contain the carefully
curated names that matter, and any that do not matter should, ideally,
not be defined or used.
The namespace itself can be divided into three main groupings:
the public facing entry-points into the system,
the compiler logic itself,
and the utilities or other elements that serve to support the others.
This gives use the following code outline.
<<*>>=
:Namespace codfns
<<Global Settings>>
<<The Fix API>>
<<User-command API>>
<<Parser>>
<<Compiler>>
<<Code Generator>>
<<Interface to the backend C compiler>>
<<Linking with Dyalog>>
<<Must Have APL Utilities>>
<<Basic [[tie]] and [[put]] utilities>>
<<The [[opsys]] utility>>
<<AST Record Structure>>
<<Converters between parent and depth vectors>>
<<XML Rendering>>
<<Pretty-printing AST trees>>
:EndNamespace
@ %def codfns
This [[<<*>>]] chunk is meant to be stored to a file.
We have a build system for doing this that depends
on the contents of the [[<<Tangle Commands>>]] chunk.
Thus, we follow the convention here of updating the contents of
the [[<<Tangle Commands>>]] chunk each time that we initially define
a new chunk that is intended to be output to a file during the
tangling process.
See more about the build infrastructure later in this document.
<<Tangle Commands>>=
echo "Tangling codfns.apln..."
notangle codfns.nw > src/codfns.apln
@ %def codfns.apln
The primary user-facing interfaces into the compiler are
[[<<The Fix API>>]] and the [[<<User-command API>>]].
These are the ways that you primarily drive the entire compiler.
I intentionally expose the rest of the compiler interfaces
without hiding them so that people who wish to leverage these
other parts of the system without using the ``entire'' compiler
pipeline are able to do so, but I do not consider this a public
interface.
This distinction matters because of our testing philosophy and our
version numbering.
Generally speaking, our version numbering scheme only tracks a major
or minor change in the compiler when the externally facing interfaces
receive some fundamental changes.
Changes to the internal changes are \emph{not} considered for this
versioning scheme.
Moreover, since I intend for there to be great freedom in changing
and altering the behavior of these internal pipeline interfaces,
these interfaces are not directly tested,
and the test suite should \emph{not} include testing against these
internal interfaces.
We philosophically only test against the external interfaces,
and eschew internal unit tests.%
\footnote{You can read more of my opinions on this matter
in my article,
\href{https://www.sacrideo.us/the-fallacy-of-unit-testing/}
{``The Fallacy of Unit Testing''}.}
The utility functions defined below the core compiler pipeline
represent functionality that is tangential to the main compiler
operation.
However, these utilities also tend to represent some specific
insight into the design of the compiler.
Understanding the core AST structure and design as well as
getting a grip on how to manipulate the core tree manipulation
structures are vital to understanding the rest of the code.
Therefore, this section spends more time on discussing these
topics before the upcoming sections dealing with a more detailed
exposition of the compiler itself.
However, there are utilities that we consider more advanced,
such as the pretty-printing functions and XML rendering
that are topics of interest to advanced users of the compiler,
but which are not part of the main compiler pipeline.
Even though these functions have intentionally general
application and are likely to be useful not only to those
working on the compiler itself but also to those who are using
more advanced compiler features,
these utilities are not critical to a deep understanding
of the compiler,
so these are not discussed in this section.
Instead, we discuss those topics in the section on developer
tooling and infrastructure concerns.
The remaining parts of this section will describe the external
facing interfaces to the compiler as well as the core underlying
data structures and idioms that form the underlying skeleton and
foundation for writing and working with any aspect of the compiler.
These are all feature and component agnostic elements of the system
that do not belong solely to only a single part,
but that impact all other elements of the compiler source code,
and so it pays especially well to pay attention and understand
this code to a high degree.
@ \subsection{Global Settings}
There are some global options that we assume to exist throughout
the compiler.
These set the standard behaviors as well as serve as knobs that
can be tweaked in some cases to identify what behaviors we want
from the rest of the compiler.
First, we have a set of read-only global constants that are defined
to configure our APL environment.
These are the typical ones, and we try to stick to the defaults,
except that we are sane, and thus we use [[⎕IO]] set to [[0]].
<<Global Settings>>=
⎕IO ⎕ML ⎕WX←0 1 3
@ %def ⎕IO ⎕ML ⎕WX
\noindent
Additionally, we set a [[VERSION]] constant to track changes to the
system through the distributions.
We use semantic versioning%
\footnote{\href{https://semver.org/}{https://semver.org/}}
as our versioning scheme.
That being said, we also do not have particular qualms about changing
the public API at a rapid pace, provided that we document this.
<<Global Settings>>=
VERSION←4 1 0
@ %def VERSION
\noindent
We depend on ArrayFire%
\footnote{\href{https://arrayfire.com/}{https://arrayfire.com/}}
for much of our GPU backend functionality.
This means we need to know two things,
where ArrayFire is installed
and which ArrayFire backend we should use when compiling.
We only really need to know where ArrayFire is installed on UNIX
style systems, as these systems seem to be much more variable in
this regard, and there is an environment variable that we can use
in Windows to find out where ArrayFire is installed more conveniently
on that platform.
We default to using [['cuda']] as our main option, but we also
support the following options for [[AF∆LIB]]:
\begin{verbatim}
cuda opencl cpu
\end{verbatim}
\noindent
Using [['']] for [[AF∆LIB]] will use ArrayFire's unified backend,
but we don't default to this because we have seen some issues on
some platforms with reliability problems.
To avoid this, we choose to use [[cuda]] as the default,
which tends to either work or fail explicitly,
which allows the user to respond rather than crashing
ungracefully in the case of the unified backend.
The least reliable backend we have seen is the [[opencl]] one,
which seems to be more hit or miss depending on the underlying
stability of the OpenCL drivers that are installed on the user's
system.
In particular, some Linux OpenCL installations seem to be
particularly fragile.
In such cases, always make sure that a good, solid OpenCL library
is being used.
<<Global Settings>>=
AF∆PREFIX←'/opt/arrayfire'
AF∆LIB←'cuda'
@ %def AF∆PREFIX AF∆LIB
\noindent
On Windows, we rely on the Visual Studio C/C++ compiler to build
our runtime and user code.
We have settled on trying to stay as up to date with this as
possible.
However, there are many different installation paths used by
Visual Studio, which can make it difficult to know where to look
unless we hardcode each location.
Instead, we assume that Visual Studio will not be a primary
interest to our users,
making it likely that they will be installing Visual Studio
only as a dependency for using Co-dfns.
In this case, it is likely that they will be using the Community
version.
Thus, we default to using the latest version of Visual Studio
of which we are aware and using the Community version of this,
which Microsoft does not charge for.
If a different version of Visual Studio is installed, then it is
important to figure out what the right path should be to locate
the Visual Studio installation.
The main thing we need to get from this path is access
to the [[vcvarsall.bat]] batch file.
This file configures the [[cmd.exe]] environment to be able to
find the Visual Studio compiler and work in the right way.
In the 2002 Community addition, and apparently most new versions
of Visual Studio, this is located in the [[VC\Auxiliary\Build\]]
subdirectory of the main installation folder.
When changing this path, we want to make sure that the following
path points to the correct [[vcvarsall.bat]] file:
\begin{verbatim}
VS∆PATH,'\VC\Auxiliary\Build\vcvarsall.bat'
\end{verbatim}
\noindent
Most users will simply need to alter [[Community]] to match the
edition of Visual Studio 2022 that they have installed on their
system.
<<Global Settings>>=
VS∆PATH←'\Program Files\Microsoft Visual Studio'
VS∆PATH,←'\2022\Community'
@ %def VS∆PATH
\subsection{The Fix API}
One of the core entry points into the compiler is through the [[Fix]]
function.
This function is designed to mimic and more or less replace the
use of the [[⎕FIX]] function found in Dyalog APL.
Its design models that behavior, and it is important as an entry-point
because it exercises most of the core elements of the compiler.
In particular, the design of the compiler's pipeline is demonstrated
most fully in this function.
$$Parse → Compile → Generate → Backend → Link$$
\noindent
The interfaces to the [[⎕FIX]] function and the Co-dfns [[Fix]]
function differ in a few key ways.
The left argument to [[Fix]] is a character vector giving the name
to use when generating files and other artifacts.
This does \emph{not} affect the name of the resulting namespace,
since that is defined, if at all, in the file source itself.
The [[⍺]] argument only affects the name of the files and other
outputs that [[Fix]] generates.
We also print out which part of the compiler we are in when we
enter that ``phase''. Doing this helps to give us an intuitive sense
of how fast each phase is and whether one phase is taking an
abnormally long time or not.
It also helps in debugging.
<<The Fix API>>=
Fix←{
_←a n s src←PS ⍵⊣⍞←'P'
_← TT _⊣⍞←'C'
_← GC _⊣⍞←'G'
_← ⍺ CC _⊣⍞←'B'
n NS _⊣⍞←'L'
}
@ %def Fix
The input requirements for [[Fix]] are not listed in the definition
itself, because both the parser [[PS]] and the [[Fix]] function
need to use the same basic checks,
and since the [[Fix]] function calls the parser
as its first entry point,
it doesn't make much sense to
duplicate that work in both places.
The requirements are as follows:
\begin{itemize}
\item Scalar/Vector
\item Character type
\item Simple or Vector of Vectors
\end{itemize}
\noindent
We generate a [[DOMAIN ERROR]] if the inputs are not well-formed.
<<Verify source input [[⍵]], set [[IN]]>>=
IN←⍵
err←'PARSER EXPECTS SCALAR OR VECTOR INPUT'
1<≢⍴IN:err ⎕SIGNAL 11
err←'PARSER EXPECTS SIMPLE OR VECTOR OF VECTOR INPUT'
2<|≡IN:err ⎕SIGNAL 11
<<Normalize the input formatting>>
err←'PARSER EXPECTS CHARACTER ARRAY'
0≠10|⎕DR IN:err ⎕SIGNAL 11
@
The input formatting that is accepted means that newlines could be
denoted either with [[LF]], [[CR]], or [[CRLF]]
sequences inside of the vectors
themselves or they could be denoted by having separate vectors
for the various lines,
or even a mixture of both.
To simplify this situation we want to normalize them so that we are
always dealing with some combination of [[LF]], [[CR]], and [[CRLF]]
sequences
within the file itself, rather than dealing with the nested
situation.
This ensures that after verification of the input,
everything will work off of the same format.
We intentionally put a newline at the end of the file even if we
may not require one because it is possible that we are dealing
with a file that is missing its final newline.
By always adding one, we ensure that every line in the input
is always terminated by a line ending.
Life is also simpler if we just use LF as our line ending instead
of something else,
this means that future code must be aware that there could be mixed
line endings in the file.
<<Normalize the input formatting>>=
IN←∊(⊆IN),¨⎕UCS 10
@
\subsection{The User Command API}
<<User-command API>>=
∇Z←Help _
Z←'Usage: <object> <target> [-af={cpu,opencl,cuda}]'
∇
∇r←List
r←⎕NS¨1⍴⊂⍬ ⋄ r.Name←,¨⊂'Compile' ⋄ r.Group←⊂'CODFNS'
r[0].Desc←'Compile an object using Co-dfns'
r.Parse←⊂'2S -af=cpu opencl cuda '
∇
∇ Run(C I);Convert;in;out
⍝ Parameters
⍝ AF∆LIB ArrayFire backend to use
Convert←{⍺(⎕SE.SALT.Load'[SALT]/lib/NStoScript -noname').ntgennscode ⍵}
in out←I.Arguments ⋄ AF∆LIB←I.af''⊃⍨I.af≡0
S←(⊂':Namespace ',out),2↓0 0 0 out Convert ##.THIS.⍎in
→0⌿⍨'Compile'≢C
{##.THIS.⍎out,'←⍵'}out Fix S⊣⎕EX'##.THIS.',out
∇
@
\subsection{AST Record Structure}
<<AST Record Structure>>=
f∆←'ptknfsrdx'
N∆←'ABCEFGKLMNOPSVZ'
A B C E F G K L M N O P S V Z←1+⍳15
@
\subsection{Converters between parent and depth vectors}
<<Converters between parent and depth vectors>>=
P2D←{z←⍪⍳≢⍵ ⋄ d←⍵≠,z ⋄ _←{p⊣d+←⍵≠p←⍺[z,←⍵]}⍣≡⍨⍵ ⋄ d(⍋(-1+d)↑⍤0 1⊢⌽z)}
D2P←{0=≢⍵:⍬ ⋄ p⊣2{p[⍵]←⍺[⍺⍸⍵]}⌿⊢∘⊂⌸⍵⊣p←⍳≢⍵}
@
\section{Testing}
We use the \href{https://github.com/Co-dfns/APLUnit}{APLUnit}
testing framework to facilitate our testing of the Co-dfns compiler.
The test harness is designed around a testing philosophy in which we
ever only write black-box tests that work on the whole compiler
using inputs that could be created or are expected to be creatable
by end-users.
That is, we do no ``unit testing'' of our source code,
but only whole program testing.
The testing framework is provided by the [[ut.apln]] file,
which is not part of this literate program and so is not included in
this document.
In order to make some of the testing more convenient,
we define the function [[TEST]] to run the tests
that exist in the [[tests\]] subdirectory.
Each of these tests has a specific number which defines the test,
and we refer to the tests by number when running them.
Both of these testing functions assume that we are running inside
of the [[tests\]] directory or one configured identically to it.
The [[TEST]] function takes either [['ALL']] as its input or a test
number in the form of an integer.
Given an integer, we call the test matching that number in the
current working directory.
The [['ALL']] option causes [[TEST]] to run all of the tests that are
defined in the current working directory.
This command is a nicety, since we can technically do all of this
by iterating the [[TEST]] function over the range of test numbers,
but this would not create the aggregate statistics that we would
like to see at the end of the testing report.
By using [['ALL']] we get to see a complete summary of the
results of testing all the code,
rather than just the individual testing results on a per testing
group/number basis.
<<[[TEST]]>>=
TEST←{
#.UT.(print_passed print_summary)←1
'ALL'≡⍵:#.UT.run './'
path←'./t',(1 0⍕(4⍴10)⊤⍵),'_*_tests.dyalog'
#.UT.run ⊃⊃0⎕NINFO⍠1⊢path
}
@ %def TEST
The [[TEST]] function is part of the utilities that exist outside
of the [[codfns]] namespace,
so we define a file for it.
<<Tangle Commands>>=
echo "Tangling src/TEST.aplf..."
notangle -R'[[TEST]]' codfns.nw > src/TEST.aplf
@ %def TEST.aplf
\section{Co-dfns Compiler}
\subsection{Parser}
The first, and in many ways, the most complex element of the
compiler is the parser.
APL has a number of unique issues when it comes to adequately
parsing the language,
but the most important is handling the context-sensitive
nature of parsing variables: depending on the type of a variable,
the parse tree can look very different.
To manage this, we make use of a linear, multi-pass style of
parser in which the parsing process consists of numerous small
passes over the input, each time refining the input into something
more like the final result.
The parser should take some input that matches the input requirements
of the [[Fix]] function and produce a suitable output AST.
$$PS :: Source → AST × ExportTypes × SymbolTable × Source$$
\noindent
We can think of the parser as starting with a forest of trees,
each of which contains a single root node that represents a single
character in from the input source,
with all trees arranged in the source order.
During each pass of the parser, we progressively combine these
trees into more complex trees until we end up at the end with a
single tree per parsed module.
In other words, we take a fully flat forest of single-node trees
and progressively increase the depth while reducing the number of
root-nodes until we have our desired AST structure.
We divide the parsing roughly into two main phases,
the tokenization phase and the parsing phase.
Unlike most compilers, we don't have a strict division in these
two phases, so, as they say, think of them more like guidelines
than actual rules%
\footnote{
\href{https://www.youtube.com/watch?v=WJVBvvS57j0}
{https://www.youtube.com/watch?v=WJVBvvS57j0}
}.
<<Parser>>=
PS←{
<<Verify source input [[⍵]], set [[IN]]>>
<<Parsing Constants>>
<<Line and error reporting utilities>>
<<Tokenize input>>
<<Parse token stream>>
<<Compute parser exports>>
<<Adjust AST for output>>
}
@ %def PS
When parsing, it's very helpful to have names for line endings.
<<Parsing Constants>>=
CR LF←⎕UCS 13 10
@
\subsubsection{Output of the Parser}
After we finish all of our parsing,
we need to take the resulting AST and convert that into something
that is suitable for output to the rest of the system.
We do this in a few ways.
When we finish parsing, we expect the following fields:
\begin{center}
\begin{tabular}{cl}
\toprule
Field & Description\\
\midrule
[[d]] & Depth vector\\
[[t]] & Node type\\
[[k]] & Node sub-class or ``kind''\\
[[n]] & Name/value field\\
[[pos]] & Starting index for source position\\
[[end]] & Exclussive index for source end position\\
[[xn]] & Names of top-level exported bindings\\
[[xt]] & Types of top-level exported bindings\\
[[sym]] & Symbol Table\\
[[IN]] & Canonical source code\\
\bottomrule
\end{tabular}
\par\end{center}
@ On parser output,
we want to convert the AST to an order that follows a
depth-first, preorder traversal order,
so that we can switch from using the parent vector to the depth
vector.
We use this output as our main output because it is space efficient
for storage, and it works well as a canonical form to use.
Because applications may want to only use the parser and not the
rest of the compiler,
we want to choose an output format that is suitable for external
as well as internal use.
This has some performance overheads,
but it is probably worth it regardless,
as reordering at this point to allow a depth vector enables some
nice assumptions in the rest of the compiler.
We use the [[P2D]] utility to reorder all of our AST columns.
Note that things like the exported bindings and the symbol table
are not strictly part of the AST structure, because they are of a
different length and type than the other columns.
<<Adjust AST for output>>=
d i←P2D p ⋄ d n t k pos end I∘⊢←⊂i
@
There is an inefficiency in the AST representation at this point,
where the [[n]] field contains character vectors.
This inefficiency was necessary while building up the AST because
we were not sure what symbols would be created
before we parsed them,
but at this point, we know the full set of symbols that we have in
the AST.
This means that we can convert the [[n]] field to a symbol table
representation.
In this case, we want the [[n]] field to pair with a [[sym]] list
that contains all the unique symbols in the source.
We want [[old_n≡sym[|new_n]]] to hold for this new [[n]] field.
In other words, we want the new [[n]] field to contain negative
integers whose magnitudes are valid indices into the [[sym]]
symbol table.
This means that there is only one character vector per unique symbol
or numeric literal in the source code, which can greatly reduce
memory usage.
Moreover, it is much faster to compare symbols that are represented by
numeric index rather than character vector.
Most of the work we expect to be done on the [[n]] field, so that we
never have to pull in [[sym]] unless we want to know the actual value
of the symbol.
This actually mimics the feature of symbols in other languages
like Scheme,
but it comes with an additional efficiency benefit in that we do not
require the use of a full generalized pointer to represent a symbol
if we have fewer symbols.
This means that we are very likely only going to need a single byte
or a couple of bytes per symbol to represent it in the [[n]] field.
The choice to make all of our symbols negative in value is somewhat
strange, but we have a good reason for doing so.
The [[n]] field is a single field that we use to contain general
data for every node, and as such, it represents a sort of union
type of all sorts of different data.
In particular, we also want to be able to support using the [[n]]
field to point to other nodes in the AST, which is a feature we
rely heavily on in the compiler transformations.
However, this feature would conflict with using the [[n]] field as an
index into the [[sym]] table, rather than as an index into the AST.
By making symbol pointers negative, we put them into a separate
space than the positive AST node pointers, allowing us to store
both pointers in the same field. This may seem like a little bit of
a strange hack, but it actually makes reasoning about things a little
easier, because we can tend to think of [[n]] as a name, even if that
name is pointing to an AST or a symbol, and avoids needless space
duplication or the need to remember to update multiple fields that are
only relevant for some nodes.
We map the $0$th index to be a null or empty symbol.
We also want to reserve the first four symbol slots $[1,4]$
so that they will \emph{always} refer to the same symbols,
namely, [[⍵]], [[⍺]], [[⍺⍺]], and [[⍵⍵]].
This gives us the following definitions for [[sym]] and [[n]].
<<Adjust AST for output>>=
sym←∪('')(,'⍵')(,'⍺')'⍺⍺' '⍵⍵',n
n←-sym⍳n
@
Finally, we want to return our AST structure in a meaningful way.
Logically, we have the AST proper, which consists of these fields:
\begin{verbatim}
d t k n pos end
\end{verbatim}
\noindent
The above fields are returned as an inverted table,
where each column is a vector of the same length.
We also want to return the variable environment,
which gives the names of our top-level bindings and their types,
also as an inverted table.
Finally, we must return a canonical representation of the source
code that is suitable as an indexing target for the [[pos]] and [[end]]
fields, as well as the symbol table.
Thus, we have a four element vector as the return value:
\begin{verbatim}
AST TopBindingTypes SymbolTable InputSource
\end{verbatim}
\noindent
Which gives us the following return value.
<<Adjust AST for output>>=
(d t k n pos end)(xn xt)sym IN
@
\subsubsection{Handling Parsing Errors}
<<Line and error reporting utilities>>=
linestarts←(⍸1⍪2>⌿IN∊CR LF)⍪≢IN
mkdm←{⍺←2 ⋄ line←linestarts⍸⍵ ⋄ no←'[',(⍕1+line),'] '
i←(~IN[i]∊CR LF)⌿i←beg+⍳linestarts[line+1]-beg←linestarts[line]
(⎕EM ⍺)(no,IN[i])(' ^'[i∊⍵],⍨' '⍴⍨≢no)}
quotelines←{
lines←∪linestarts⍸⍵
nos←(1 0⍴⍨2×≢lines)⍀'[',(⍕⍪1+lines),⍤1⊢'] '
beg←linestarts[lines] ⋄ end←linestarts[lines+1]
m←∊∘⍵¨i←beg+⍳¨end-beg
¯1↓∊nos,(~∘CR LF¨⍪,(IN∘I¨i),⍪' ▔'∘I¨m),CR}
SIGNAL←{⍺←2 '' ⋄ en msg←⍺ ⋄ EN∘←en ⋄ DM∘←en mkdm ⊃⍵
dmx←('EN' en)('Category' 'Compiler')('Vendor' 'Co-dfns')
dmx,←⊂'Message'(msg,CR,quotelines ⍵)
⎕SIGNAL⊂dmx}
@ %def SIGNAL quotelines mkdm linestarts
\subsubsection{Tokenizing the Input}
<<Tokenize input>>=
⍝ Group input into lines as a nested vector
pos←(⍳≢IN)⊆⍨~IN∊CR LF
<<Check and mask the strings>>
<<Unify whitespace and comments>>
<<Tokenize strings>>
<<Verify that all open characters are valid>>
<<Tokenize numbers>>
<<Tokenize variables>>
<<Tokenize primitives and atoms>>
<<Compute dfns regions and type, with [[}]] as a child>>
<<Check for out of context dfns formals>>
<<Compute trad-fns regions>>
<<Identify label colons vs. others>>
<<Tokenize keywords>>
<<Tokenize system variables>>
⍝ Delete all characters we no longer need from the tree
d tm t pos end(⌿⍨)←⊂(t≠0)∨x∊'()[]{}:;'
<<Tokenize labels>>
@
\subsubsection{Parsing Token Stream}
<<Parse token stream>>=
⍝ Now that all compound data is tokenized, reify n field before tree-building
n←{1↓⍎¨'0',⍵}@{t=N}(⊂'')@{t∊Z F}1 ⎕C@{t∊K S}IN∘I¨pos+⍳¨end-pos
<<Check that all keywords are valid>>
<<Check that namespaces are at the top level>>
<<Verify that all structured statements appear within trad-fns>>
<<Verify that system variables are defined>>
⍝ Compute parent vector from d
p←D2P d
<<Compute the nameclass of dfns>>
⍝ We will often wrap a set of nodes as children under a Z node
gz←{
z←⍵↑⍨-0≠≢⍵ ⋄ ks←¯1↓⍵
t[z]←Z ⋄ p[ks]←⊃z ⋄ pos[z]←pos[⊃⍵] ⋄ end[z]←end[⊃⌽z,ks]
z
}
<<Nest top-level root lines as [[Z]] nodes>>
<<Wrap all dfns expression bodies as [[Z]] nodes>>
⍝ Drop/eliminate any Z nodes that are empty or blank
_←p[i]{msk[⍺,⍵]←~∧⌿IN[pos[⍵]]∊WS}⌸i←⍸(t[p]=Z)∧p≠⍳≢p⊣msk←t≠Z
tm n t k pos end(⌿⍨)←⊂msk ⋄ p←(⍸~msk)(⊢-1+⍸)msk⌿p
<<Parse [[:Namespace]] syntax>>
<<Parse guards to [[(G (Z ...) (Z ...))]]>>
<<Parse brackets and parentheses into [[¯1]] and [[Z]] nodes>>
<<Convert [[;]] groups within brackets into [[Z]] nodes>>
<<Parse Binding nodes>>
<<Mark system variables as [[P]] nodes with appropriate kinds>>
<<Mark atoms, characters, and numbers as kind [[1]]>>
<<Mark APL primitives with appropriate kinds>>
<<Anchor variables to earliest binding in the matching frame>>
<<Convert [[M]] nodes to [[F0]] nodes>>
<<Convert [[⍺]] and [[⍵]] to [[V]] nodes>>
<<Convert [[⍺⍺]] and [[⍵⍵]] to [[P2]] nodes>>
<<Infer the type of bindings, groups, and variables>>
<<Strand arrays into atoms>>
<<Parse dyadic operator bindings>>
<<Rationalize [[F[X]]] syntax>>
<<Group function and value expressions>>
<<Parse function expressions>>
<<Parse assignments>>
<<Enclose [[V[X;...]]] for expression parsing>>
<<Parse trains>>
<<Parse value expressions>>
<<Rationalize [[V[X;...]]]>>
⍝ Sanity check
ERR←'INVARIANT ERROR: Z node with multiple children'
ERR assert(+⌿(t[p]=Z)∧p≠⍳≢p)=+⌿t=Z:
⍝ Count parentheses in source information
ip←p[i←⍸(t[p]=Z)∧n[p]∊⊂,'('] ⋄ pos[i]←pos[ip] ⋄ end[i]←end[ip]
⍝ VERIFY Z/B NODE TYPES MATCH ACTUAL TYPE
⍝ Eliminate Z nodes from the tree
zi←p I@{t[p[⍵]]=Z}⍣≡ki←⍸msk←(t[p]=Z)∧t≠Z
p←(zi@ki⍳≢p)[p] ⋄ t k n pos end(⊣@zi⍨)←t k n pos end I¨⊂ki
t k n pos end⌿⍨←⊂msk←~msk∨t=Z ⋄ p←(⍸~msk)(⊢-1+⍸)msk⌿p
@
\subsection{Compiler Transformations}
<<Compiler>>=
TT←{
((d t k n ss se)exp sym src)←⍵
⍝ Compute parent vector and reference scope
r←I@{t[⍵]≠F}⍣≡⍨p⊣2{p[⍵]←⍺[⍺⍸⍵]}⌿⊢∘⊂⌸d⊣p←⍳≢d
<<Lift dfns to the top-level>>
<<Wrap expressions as binding or return statements>>
<<Lift guard tests>>
<<Count strand and indexing children>>
<<Lift and flatten expressions>>
<<Compute slots and frames>>
<<Record exported top-level bindings>>
p t k n f s r d xi sym
}
@
\subsection{Code Generator}
<<Map generators over the linearized AST; return>>=
d i←P2D p ⋄ ast←(⍉↑d p t k n(⍳≢p)fr sl fd)[i;] ⋄ ks←{⍵⊂[0]⍨(⊃⍵)=⍵[;0]}
NOTFOUND←{('[GC] UNSUPPORTED NODE TYPE ',N∆[⊃⍵],⍕⊃⌽⍵)⎕SIGNAL 16}
dis←{0=2⊃h←,1↑⍵:'' ⋄ (≢gck)=i←gck⍳⊂h[2 3]:NOTFOUND h[2 3] ⋄ h(⍎i⊃gcv)ks 1↓⍵}
∊,∘(⎕UCS 13 10)¨pref,⊃,⌿(,⌿Zp¨⍸t=F),(,⌿Zx¨xi),(⊂⊂''),dis¨ks ast
@
<<Symbol $\longleftrightarrow$ Name mapping>>=
syms←0⍴⊂'' ⋄ nams←0⍴⊂''
@
<<Node $\longleftrightarrow$ Generator mapping>>=
gck←0⍴⊂0 0 ⋄ gcv←0⍴⊂''
@
<<Prefix code for all generated files>>=
pref ←⊂'#include "codfns.h"'
pref,←⊂''
pref,←⊂'EXPORT int'
pref,←⊂'DyalogGetInterpreterFunctions(void *p)'
pref,←⊂'{'
pref,←⊂' return set_dwafns(p);'
pref,←⊂'}'
pref,←⊂''
@
<<Node-specific code generators>>=
Zp←{
n←'fn',⍕⍵
<<Declare top-level function bindings>>
'UNKNOWN FUNCTION TYPE'⎕SIGNAL 16
}
@
<<Node-specific code generators>>=
Zx←{
n←sym⊃⍨|n[⍵] ⋄ rid←⍕rf[⍵]
k[⍵]=0:⊂''
<<Declare top-level array structures>>
<<Declare top-level closures>>
⍎'''UNKNOWN EXPORT TYPE''⎕SIGNAL 16'
}
@
<<Code Generator>>=
GC←{
p t k n fr sl rf fd xi sym←⍵
<<Symbol $\longleftrightarrow$ Name mapping>>
<<Node $\longleftrightarrow$ Generator mapping>>
<<Prefix code for all generated files>>
<<Node-specific code generators>>
<<Map generators over the linearized AST; return>>
}
@
\subsection{Backend C Compiler Interface}
<<Interface to the backend C compiler>>=
CC←{
vsbat←VS∆PATH,'\VC\Auxiliary\Build\vcvarsall.bat'
soext←{opsys'.dll' '.so' '.dylib'}
libdir←opsys ''' ' '/lib64'' ' '/lib'' '
ccf←{' -o ''',⍵,'.',⍺,''' ''',⍵,'.c'' -laf',AF∆LIB,' > ',⍵,'.log 2>&1'}
cci←{'-I''',AF∆PREFIX,'/include'' -L''',AF∆PREFIX,libdir}
cco←'-std=c99 -Ofast -g -Wall -fPIC -shared '
cco,←'-Wno-parentheses -Wno-misleading-indentation '
ucc←{⍵⍵(⎕SH ⍺⍺,' ',cco,cci,ccf)⍵}
gcc←'gcc'ucc'so'
clang←'clang'ucc'dylib'
vsco←{z←'/W3 /wd4102 /wd4275 /O2 /Zc:inline /Zi /FS /Fd"',⍵,'.pdb" '
z,←'/WX /MD /EHsc /nologo '
z,'/I"%AF_PATH%\include" /D "NOMINMAX" /D "AF_DEBUG" '}
vslo←{z←'/link /DLL /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:WINDOWS '
z,←'/LIBPATH:"%AF_PATH%\lib" /OPT:ICF /ERRORREPORT:PROMPT /TLBID:1 '
z,'/DYNAMICBASE "af', AF∆LIB, '.lib" "codfns.lib" '}
vsc0←{~⎕NEXISTS vsbat:'VISUAL C?'⎕SIGNAL 99 ⋄ '""',vsbat,'" amd64'}
vsc1←{' && cd "',(⊃⎕CMD'echo %CD%'),'" && cl ',(vsco ⍵),' "',⍵,'.c" '}
vsc2←{(vslo ⍵),'/OUT:"',⍵,'.dll" > "',⍵,'.log""'}
vsc←{⎕CMD ('%comspec% /C ',vsc0,vsc1,vsc2)⍵}
_←(⍎opsys'vsc' 'gcc' 'clang')⍺⊣⍵ put ⍺,'.c'⊣1 ⎕NDELETE f←⍺,soext⍬
⎕←⍪⊃⎕NGET(⍺,'.log')1
⎕NEXISTS f:f ⋄ 'COMPILE ERROR' ⎕SIGNAL 22}
@
\subsection{Linking with Dyalog}
<<Linking with Dyalog>>=
NS←{
MKA←{mka⊂⍵} ⋄ EXA←{exa ⍬ ⍵}
Display←{⍺←'Co-dfns' ⋄ W←w_new⊂⍺ ⋄ 777::w_del W
w_del W⊣W ⍺⍺{w_close ⍺:⍎'⎕SIGNAL 777' ⋄ ⍺ ⍺⍺ ⍵}⍣⍵⍵⊢⍵}
LoadImage←{⍺←1 ⋄ ~⎕NEXISTS ⍵:⎕SIGNAL 22 ⋄ loadimg ⍬ ⍵ ⍺}
SaveImage←{⍺←'image.png' ⋄ saveimg ⍵ ⍺}