-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompiler.html
2822 lines (2821 loc) · 122 KB
/
compiler.html
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
<html lang="en">
<head>
<!-- Osnovni SEO za Bing i Google. -->
<meta name="author" content="Teo Samarzija" />
<meta
name="description"
content="A web-app that converts arithmetic expressions to i486-compatible assembly compilable using FlatAssembler, works even in Internet Explorer 6."
/>
<meta
name="keywords"
content="Compiler Theory, Assembly, FlatAssembler, Arithmetic Expressions, Retrocomputing, i486"
/>
<meta
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
name="viewport"
/>
<title>Arithmetic Expression Compiler</title>
<style type="text/css">
#noScriptBackGround {
display: table;
z-index: 100;
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
background-color: #000000;
filter: alpha(opacity=90);
opacity: 0.9;
text-align: center;
}
#noScriptText {
color: white;
font-size: 22px;
display: table-cell;
text-align: center;
width: 100%;
vertical-align: middle;
padding-left: 10px;
padding-right: 10px;
}
.gornjaDesnaTipka {
height: 20px;
width: 15px;
font-size: 15px;
font-weight: bold;
top: 8px;
cursor: pointer;
text-align: center;
border-style: groove;
border-width: 3px;
color: #aaaaaa;
font-family: Courier;
background: #777777;
position: absolute;
}
#titleBar {
position: absolute;
top: 8px;
margin: 0px;
left: 8px;
height: 20px;
background: #0077aa;
color: white;
font-family: Arial;
font-size: 12px;
line-height: 20px;
padding-left: 20px;
padding-right: 5px;
font-weight: bold;
border-style: groove;
border-width: 3px;
cursor: move;
border-bottom-style: none;
}
#content {
position: absolute;
top: 28px;
left: 8px;
border-style: groove;
padding: 5px;
overflow: scroll;
background: #ffffdd;
border-width: 3px;
}
nav {
display: none;
position: absolute;
z-index: 100;
width: 250px;
background: white;
border-style: solid none none none;
border-width: 2px;
overflow: hidden;
}
#assembly {
font-family: monospace;
font-size: 1.5em;
background-color: #eeeeee;
width: 100%;
overflow: scroll;
max-height: 85%;
white-space: nowrap;
}
#diagramSpan {
display: none;
width: 100%;
height: 300px;
overflow: scroll;
background: white;
}
#ikona {
text-align: center;
display: none;
position: absolute;
color: white;
font-family: Arial;
font-size: 10px;
}
#favicon {
width: 15px;
height: 15px;
position: absolute;
top: 13px;
left: 13px;
cursor: pointer;
}
.LineNumber {
color: #772200;
font-weight: normal;
}
.Type {
color: #775500;
font-weight: bold;
}
.Keyword {
color: #770000;
font-weight: bold;
}
.Comment {
color: #004444;
font-weight: bold;
}
.Parenthesis {
color: #333322;
font-weight: bold;
}
.Operator {
color: #770077;
font-weight: bold;
}
.Constant {
color: #006600;
font-weight: bold;
}
.String {
color: #003377;
}
</style>
<!--[if IE lt 9]>
To the programs we've left behind, fixed forever in their time... Lest we
forget the Browser Wars!
<style type="text/css">
#noScriptBackGround {
position: absolute; //Zato sto ce stariji Internet Exploreri na onakav kod gore pokusati emulirati Internet Explorer 5, koji nije podrzavao "fixed"...
left: 8px; //... i, naravno, nece ispravno postaviti pozadinu.
top: 8px;
padding-top: 25%; //Ovo radi zbog CSS Box-Model-Buga.
}
</style>
<![endif]-->
<script type="text/javascript">
//HTML elementi koji se ovdje koriste, a koje neki stariji preglednici ne prepoznaju. Najavimo ih da usprkos tomu ispravno parsiraju kod.
document.createElement("nav");
document.createElement("mark");
</script>
</head>
<body style="background: #007777">
<noscript>
<span id="noScriptBackGround">
<span id="noScriptText">
Your browser doesn't appear to have a JavaScript interpreter. The
compiler relies on your browser built-in JavaScript interpreter to
work. Please run this in a modern or a semi-modern browser (the basic
functionality is available even in Internet Explorer 6). If you are
already using a modern browser, enable JavaScript (if you are using
Internet Explorer, you may need to also enable ActiveX controls) and
refresh the web-page.
</span>
</span>
</noscript>
<div id="shareIt">
Please share this web-app with as many people interested in Assembly or
the compiler theory (or even just retroinformatics) as you can. I've put a
lot of effort into making it.
</div>
<h1 id="titleBar">
Arithmetic Expression Compiler<span
id="AJAXmessage"
style="display: none"
>
- connecting to the server...</span
>
</h1>
<div id="smanji" class="gornjaDesnaTipka" style="font-size: 14px">_</div>
<div id="povecaj" class="gornjaDesnaTipka">▢</div>
<div
id="zatvori"
class="gornjaDesnaTipka"
style="font-family: Arial"
onclick="history.back()"
>
x
</div>
<img
src="https://www.theflatearthsociety.org/forum/avr/avatar_1461509_1483220545.png"
onclick="document.getElementsByTagName('nav')[0].style.display = 'block'"
alt="AEC"
id="favicon"
/>
<nav onmouseleave="this.style.display='none'">
<mark id="about">About</mark>
<mark id="mailMe">E-mail Teo Samarzija</mark>
<mark id="download">Download FlatAssembler</mark>
<mark id="mailTomasz">E-mail Tomasz Grysztar</mark>
<mark id="backEndReset"><del>Reset the Back-End</del></mark>
<mark id="exit">Exit</mark>
</nav>
<div id="content">
<button id="showMenu" style="display: none">Show menu</button>
Enter an arithmetic expression here:<br />
<input
type="text"
id="input"
value="((abs(-(pow(sin(alpha),2)+pow(cos(alpha),2))-(-1))<1/1000)&((2+2=5)|(3+1>3.5))&(not(abs(arcsin(45)-mod(15/2,1))<1/1000)))+(2+2>5?3+3<7?1:-2:2+2-4<1?0:2+2<4?-1:-3)+('A'+2='C'?0:-1) ;This should always output '1' (However, because the 'pow' in i486 Assembly doesn't support negative bases, this works only for 0<alpha<90.)."
style="width: 100%"
/><br />
<button onclick="compile()" style="float: left">Compile!</button>
<button onclick="interpret()" style="float: right">Interpret</button
><br /><br />
Choose the Assembly syntax:
<input type="radio" id="GAS" name="syntax" value="gas" />
<label for="GAS"
><a href="https://www.gnu.org/software/binutils/"
>GNU Assembler</a
></label
>
<input type="radio" id="FASM" name="syntax" value="fasm" checked />
<label for="FASM"
><a href="https://flatassembler.net/">FlatAssembler</a></label
><br />
Verbose output: <input type="checkbox" id="verbose" /><label for="verbose"
>Print
<a href="https://www.britannica.com/technology/LISP-computer-language"
>LISP-style</a
>
S-Expressions inside Assembly.</label
><br /><br />
Tokenized:<br />
<div
id="tokenized"
style="font-family: monospace; font-size: 1.5em"
></div>
<br />
Parsed (AST converted to an
<a href="https://en.wikipedia.org/wiki/S-expression">S-expression</a
>):<br />
<div id="LISP" style="font-family: monospace; font-size: 1.5em"></div>
<br />
Compiled (to x86 assembly<del
>, apparently
<a href="https://www.vogons.org/viewtopic.php?f=31&t=74881"
>runnable only on Pentium Pro and newer processors</a
></del
>, Intel Syntax):<br />
<div id="assembly"></div>
<br />
Interpreter output:
<span id="interpreter" style="font-family: "Courier New""
>null</span
><br /><br />
WARNING: The tokenizer, the parser and the compiler appear to generate
correct results, but they haven't been rigorously tested. Also, no
optimization is being performed (aside from perhaps the code being the one
it's easiest to compile into). If you want a web-app that uses well-tested
compilation algorithms and optimizes the assembly code it outputs, try
<a href="https://godbolt.org/">GodBolt</a>.
<del
>To test the code the compiler generates, you can download the
fully-prepared project file (for your arithmetic expression) that can be
compiled using FlatAssembler on Windows by clicking
<a
href="javascript:void(0)"
onclick="try{downloadAJAX();}catch(e){alert('Emitter error: '+e.message+' (this message was generated by your browser).');}"
>here</a
>
<!-- Morao sam koristiti try/catch ovdje jer Android Stock Browser inace nije hvatao neki exception koji je bacao. -->
(although it works in Internet Explorer 6, it doesn't work in some later
browsers).</del
>
<i
>(UPDATE: Now that this website is hosted at GitHub, it won't work in
any browser because GitHub doesn't let me run my PHP on their
servers.)</i
>
<del>In case that doesn't work,</del> you can download an example testing
project <a href="test.ASM">here</a> (comments are in Croatian). If you
want to have a command-line app with the same functionality and some more
(<i
>if-else, while-loops, arrays,
<del
>the support for the assembly language compilers that don't support
automatic floating-point-to-<a
href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format"
>IEEE754</a
>
conversion</del
>...</i
>), you can download the source code of the version of this app runnable
in <a href="https://duktape.org/">Duktape</a> (a lightweight and
easy-to-use alternative to NodeJS, it's written in C99 and basically
requires only a modern C compiler to work, it also works under
<a href="http://www.freedos.org/">FreeDOS</a>)
<a href="Duktape.zip">here</a> (or, if you are willing to risk getting
viruses from my computer, you can download the executable files for 32-bit
Windows, 32-bit Linux and FreeDOS from GitHub
<a
href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/ArithmeticExpressionCompiler.zip"
>here</a
>.).
<i
>(UPDATE: If you just need the automatic decimal-number-to-IEEE754
conversion, you don't actually need to download it, you only need to run
this web-page in a modern browser (that supports
<span style="font-family: Monospace; font-style: normal"
>ArrayBuffer</span
>). Also, now there is a version that can be run in
<a href="https://nodejs.org/en/">NodeJS</a>, it can be downloaded
<a
href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/releases/download/1.4/aec.js"
>here</a
>, maybe it comes useful to somebody. Thanks to supporting GNU
Assembler, which is a, if you ask me, a rather bad assembler, but it's
used by <a href="https://gcc.gnu.org/">GNU Compiler Collection</a>, it's
relatively easy to write a part of the program in the
ArithmeticExpressionCompiler language and a part of it in, for example,
C++. You can see an example of a complicated
<a
href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/recursive_HybridSort/hybrid_sort.aec"
>algorithm</a
>
implemented in ArithmeticExpressionCompiler, its example
<a
href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/recursive_HybridSort/randomly_generate_numbers.cpp"
>C++ wrapper</a
>
and download the
<a
href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/recursive_HybridSort/RecursiveHybridSortExecutables.zip"
>executable files</a
>
for Linux, FreeDOS and Windows. Comments are in Croatian, because it was
intended for specific Croatian-speaking audience. You can also see
step-by-step instructions for compiling ArithmeticExpressionCompiler
programs in this <a href="https://youtu.be/N2C1i8CW7Io">video</a>.)</i
>
You can also download a Notepad++ script for syntax-highlighting of that
language <a href="Arth.xml">here</a>.
<del
>Neither do I, nor do the creators of FlatAssembler, nor does 000webhost
(a Cyprus-based company hosting this website,</del
>
<i
>(UPDATE: 000webhost has banned me for "hate speech", so I moved my site
to GitHub.)</i
><del
>), claim any liability for the damage those programs may do to your
computer. It's a part of the Terms of Service for me not to make scripts
that install executable files to your computer. Scripts that produce
compilable Assembly language files do not violate the Terms of Service
as they are not executable files themselves. However, once they are
compiled using FlatAssembler, nobody can guarantee you (including the
antivirus software) they won't do any damage to your computer.</del
>
It is not my intention to damage your device, but remember that if you
compile the files you download here (using FlatAssembler or GNU
Assembler), you will be running arbitrary Assembly language code on your
computer, and be careful with it (for maximal security, I'd recommend
using some virtual machine software<del
>, but notice that DosBox does not emulate Pentium Pro</del
>).<br />By the way, if you ever find yourself having to use a programming
language without a built-in math library, <a href="math.rs">here</a> is an
example of how to make a simple math library in less than 150 lines of
code. You can also see a <a href="math.rs.png">diagram</a> showing how
accurate the functions there are for various inputs.
<i
>(I had to do that in my programming language when writing
<a href="analogClock.html">Analog Clock for WebAssembly</a>, because
WebAssembly doesn't provide
<font face="monospace" style="font-style: normal">fsin</font> and
similar instructions.)</i
>
<br />
<br />
UPDATE on 15/10/2018: You can download my presentation (in Croatian) about
how the compilers work <a href="prezentacija.zip">here</a> (It's a ZIP
archive containing an ODP file, a PPT file and a PDF file, all saved from
Impress. Hopefully, your computer can usefully open at least one of those
files!). (<i
>UPDATE: A way better version, written more than a year later, is
available
<a
href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/seminar/PojednostavljeniSeminar.pdf"
>here</a
>.</i
>) (<i
>UPDATE: About a year later, I've written an
<a href="compiler_theory.zip">English-language version</a>. You can see
a <a href="https://youtu.be/Br6Zh3Rczig">YouTube video</a>, and, if your
browser does not support streaming MP4 videos, you can download
<a href="compiler_theory.mp4">an MP4 file</a> and open it in
<a href="https://www.videolan.org/vlc/">VLC</a> or something like
that.</i
>)<br /><br />
UPDATE on 18/10/2018: If you have a modern browser, you can see the
<abbr title="Abstract Syntax Tree">AST</abbr>
diagram (tree diagram, also known as syntax tree) by clicking
<a href="javascript:void(0)" onclick="showAST()">here</a> (it requires a
relatively advanced SVG support, seen in, for example, Internet Explorer
11). If you don't have, don't worry, graphical representations of complex
(that can't be done by hand) ASTs are useless (the maximal depth of a
useful graphical AST is probably around 5).<br />
<div id="diagramSpan">
<svg id="diagram" style="overflow: visible"></svg>
</div>
<br />
UPDATE on 03/08/2020: I've started to develop a version of this program
which doesn't target x86 processors, but
<a href="https://webassembly.org/">WebAssembly</a> (the JavaScript
bytecode, which Mozilla has been pushing to get standardized since 2015,
so that people can run programming languages better than JavaScript in a
browser). Right now, it's in the very early stages of development, but you
can see a <a href="arithmeticOperatorsTest.html">program</a> I've made
today in it. My new compiler is only compatible with very modern browsers,
which not only support WebAssembly, but also support
<code>WebAssembly.Global</code>. Those are Firefox 62, released
05/09/2018, and Chrome 69, released 04/09/2018. Thus, the code it produces
cannot be run in any browser compatible with Windows XP. I have been
rewriting
<a href="https://github.com/FlatAssembler/AECforWebAssembly"
>the compiler</a
>
from scratch in C++, because most experienced programmers consider it to
be a better language than JavaScript.<br /><br />
UPDATE on 07/08/2020: Perhaps a lot better proof of the concept that my
programming language can be used on the web is my implementation of the
<a href="https://flatassembler.github.io/permutationsTest.html"
>permutations algorithm</a
>
in it.<br /><br />
UPDATE on 30/08/2020: I've written an informal
<a href="AEC_specification.html">specification</a>
for my programming language.<br /><br />
UPDATE on 01/11/2020: As a part of an university project, I've began to
write a <a href="PicoBlaze/PicoBlaze.html">PicoBlaze simulator</a> (more
accurately: an assembler and an emulator) in JavaScript (which can be run
in a browser). So, if you want to try non-x86 assembly language
programming to better understand how computers work, there might be no
better way to do that than to try that app. It runs in Firefox 52 (the
last version of Firefox to run on Windows XP, and also the version of
Firefox that comes with Solaris 11.4) and newer browsers.<br /><br />
UPDATE on 19/07/2021: Please note that this compiler has a
<a href="AEC_specification#ternary_operator_bug"
>bug related to the way the ternary conditional operator
<code>?:</code> is compiled</a
>. In short, do not use it as to protect yourself against the division by
zero and similar errors, it will not work then, because the second and the
third operand are computed before the first operand that is the condition.
I am sorry about that, but, given the way this compiler is structured
(because I made the core of it back when I was only 18), there does not
appear to be a simple solution. The compiler for my programming language
that is targetting WebAssembly is significantly more professionally
made.<br /><br />
UPDATE on 18/01/2023: I've written a shell script so that you can more
easily try out this compiler in a Unix shell:
<pre style="background-color: #eeeeee; overflow: scroll; width: 100%">
mkdir ArithmeticExpressionCompiler
cd ArithmeticExpressionCompiler
<span class="Keyword">if</span> <span class="Parenthesis">[</span> <span class="Operator">$</span><span class="Parenthesis">(</span>command -v wget <span class="Operator">></span> /dev/null <span class="Constant">2</span><span class="Operator">>&</span><span class="Constant">1</span> <span class="Operator">;</span> echo <span class="Operator">$</span>?<span class="Parenthesis">)</span> <span class="Keyword">-eq</span> <span class="Constant">0</span> <span class="Parenthesis">]</span> <span class="Comment"># Check if "wget" exists, see those StackOverflow answers for more details:
# <a href="https://stackoverflow.com/a/75103891/8902065">https://stackoverflow.com/a/75103891/8902065</a>
# <a href="https://stackoverflow.com/a/75103209/8902065">https://stackoverflow.com/a/75103209/8902065</a></span>
<span class="Keyword">then</span>
wget <a href="https://flatassembler.github.io/Duktape.zip">https://flatassembler.github.io/Duktape.zip</a>
<span class="Keyword">else</span>
curl -o Duktape.zip <a href="https://flatassembler.github.io/Duktape.zip">https://flatassembler.github.io/Duktape.zip</a>
<span class="Keyword">fi</span>
unzip Duktape.zip
<span class="Keyword">if</span> <span class="Parenthesis">[</span> <span class="Operator">$</span><span class="Parenthesis">(</span>command -v clang <span class="Operator">></span> /dev/null <span class="Constant">2</span><span class="Operator">>&</span><span class="Constant">1</span> <span class="Operator">;</span> echo <span class="Operator">$</span>?<span class="Parenthesis">)</span> <span class="Keyword">-eq</span> <span class="Constant">0</span> <span class="Parenthesis">]</span> <span class="Comment"># We prefer "clang" to "gcc" because... what if somebody tries to run this in CygWin terminal? GCC will not work then, CLANG might.</span>
<span class="Keyword">then</span>
c_compiler<span class="Operator">=</span><span class="String">"clang"</span>
<span class="Keyword">else</span>
c_compiler<span class="Operator">=</span><span class="String">"gcc"</span>
<span class="Keyword">fi</span>
$c_compiler -o aec aec.c duktape.c -lm <span class="Comment"># The linker that comes with recent versions of Debian Linux insists that "-lm" is put AFTER the source files, or else it outputs some confusing error message.</span>
<span class="Keyword">if</span> <span class="Parenthesis">[</span> <span class="String">"<i>$OS</i>"</span> <span class="Operator">=</span> <span class="String">"Windows_NT"</span> <span class="Parenthesis">]</span>
<span class="Keyword">then</span>
./aec analogClockForWindows.aec
$c_compiler -o analogClockForWindows analogClockForWindows.s -m32
./analogClockForWindows
<span class="Keyword">else</span>
./aec analogClock.aec
$c_compiler -o analogClock analogClock.s -m32
./analogClock
<span class="Keyword">fi</span>
</pre>
If everything is fine, the Analog Clock program should now print the
current time in the terminal. I think this would work on the vast majority
of Linux machines, as well as on many non-Linux (FreeBSD, Solaris...)
machines, and on some Windows machines with a Unix shell (such as Git
Bash).
</div>
<div id="ikona">
<img
id="avatar"
src="https://www.theflatearthsociety.org/forum/avr/avatar_1461509_1483220545.png"
alt="AEC"
style="width: 75px; height: 60px"
draggable="false"
/><br />
<span id="opis">Arithmetic<br />Expression<br />Compiler</span>
</div>
<script type="text/javascript">
/*i486 i noviji procesori iz x86 familije imaju FPU stog od 8 bitseta po 80 bitova.
Ovaj se program oslanja na njega. 8 bitseta je u vecini slucajeva dovoljno.
Ako bismo zeljeli da moze jos kompliciranije stvari raditi (ili ga uciniti portabilnim),
trebali bismo napraviti svoj stog. Da program bude lakse tako izmijeniti, pokusao sam
sto vise ne pristupati stogu izravno, nego preko funkcija.*/
function finit() {
//Inicijalizira FPU stog kad je se pozove prvi put u programu, inace brise sve brojeve na njemu
asm("finit");
}
function faddp() {
//Dodaje pretposljednjem broju posljednji broj na FPU stogu i brise posljednji broj
asm("faddp");
}
function fsubp() {
//Oduzima posljednji broj od pretposljednjeg te brise posljednji broj na stogu
asm("fsubp");
}
function fmulp() {
//Mnozi zadnja dva broja na FPU stogu, uklanja ih sa stoga, te rezultat dodaje na vrh stoga
asm("fmulp");
}
function fdivp() {
//Dijeli pretposljednji broj na FPU stogu s posljednjim, brise sa stoga ta dva broja te rezultat dodaje na stog
asm("fdivp");
}
function fsinp() {
//Zamijenjuje zadnji broj na stogu njegovim sinusom (radijani)
asm("fsin");
}
function fcosp() {
//Zamijenjuje zadnji broj na stogu njegovim kosinusom (radijani)
asm("fcos");
}
function ftanp() {
//-||- tangensom -||-, po formuli tan(x)=sin(x)/cos(x)
asm("fsincos");
fdivp();
}
function fsqrt() {
//-||- kvardatnim korijenom
asm("fsqrt");
}
function fatanp() {
//-||- arkus tangensom
asm("fld1");
fatan2();
}
function fatan2() {
//Racuna arkus tangens kolicnika predzadnjeg i zadnjeg broja, brise te brojeve, te dodaje rezultat na stog
asm("fpatan");
}
function fasinp() {
//-||- arkus sinus (po formuli arctan(x/sqrt(1-x*x)))
fstp();
fld();
asm("fld1");
fld();
fld();
fmulp();
fsubp();
fsqrt();
fdivp();
fatanp();
}
function facosp() {
// -||- arkus kosinus (po formuli pi/2-arcsin(x))
fstp();
asm("fldpi");
asm("fld1");
asm("fld1");
faddp();
fdivp();
fld();
fasinp();
fsubp();
}
function flnp() {
// Zamijenjuje zadnji broj na stogu njegovim prirodnim logaritmom
asm("fld1");
asm("fxch");
asm("fyl2x");
asm("fldl2e");
fdivp();
}
function fexpp() {
// Zamijenjuje zadnji broj na stogu s e^x, gdje je 'e' baza prirodnog logaritma.
asm("fldl2e");
fmulp();
asm("fld1");
asm("fscale");
asm("fxch");
asm("fld1");
asm("fxch");
asm("fprem");
asm("f2xm1");
faddp();
fmulp();
}
function flogp() {
// -||- dekadskim logaritmom (po formuli ln(x)/ln(10))
flnp();
asm(
"mov dword [result]," +
(highlight ? '<span style="color:#007700">' : "") +
"10" +
(highlight ? "</span>" : "")
);
fild();
flnp();
fdivp();
}
function fpowp() {
//Zamijenjuje zadnja dva broja na stogu njihovom potencijom (po formuli exp(ln(x)*y)).
asm("fxch");
flnp();
fmulp();
fexpp();
}
function fabsp() {
// Zamijenjuje zadnji broj na stogu njegovom apsolutnom vrijednoscu
asm("fabs");
}
function fpmod() {
//Zamijenjuje zadnja dva broja na stogu ostatkom pri dijeljenju zadnjeg s predzadnjim.
asm("fxch");
asm("fprem");
asm("fxch");
fstp();
}
function fcomip() {
//Usporedi dva broja na vrhu stoga i postavi CPU-ove zastavice da oznacuju rezultat usporedbe.
//"fcomip" postoji samo na i686 i novijim x86 procesorima, a mi ciljamo na i486.
//https://www.vogons.org/viewtopic.php?p=1130626#p1130626
asm("fcomp");
asm(
"push " +
(highlight ? '<span style="color:#007777">' : "") +
"ax" +
(highlight ? "</span>" : "")
);
asm(
"fstsw " +
(highlight ? '<span style="color:#007777">' : "") +
"ax" +
(highlight ? "</span>" : "")
);
asm(
"mov " +
(highlight ? '<span style="color:#007777">' : "") +
"al" +
(highlight ? "</span>" : "") +
"," +
(highlight ? '<span style="color:#007777">' : "") +
"ah" +
(highlight ? "</span>" : "")
);
asm("lahf");
asm(
"and " +
(highlight ? '<span style="color:#007777">' : "") +
"ax" +
(highlight ? "</span>" : "") +
"," +
(highlight ? '<span style="color:#007700">' : "") +
"0xba45" +
(highlight ? "</span>" : "") +
" " +
(highlight ? '<span style="color:#777777">' : "") +
(syntax == "fasm" ? ";" : "#") +
(highlight
? '<a href="https://www.vogons.org/viewtopic.php?p=1130827#p1130827">'
: "") +
"https://www.vogons.org/viewtopic.php?p=1130827#p1130827" +
(highlight ? "</a></span>" : "")
);
asm(
"or " +
(highlight ? '<span style="color:#007777">' : "") +
"ah" +
(highlight ? "</span>" : "") +
"," +
(highlight ? '<span style="color:#007777">' : "") +
"al" +
(highlight ? "</span>" : "")
);
asm("sahf");
asm(
"pop " +
(highlight ? '<span style="color:#007777">' : "") +
"ax" +
(highlight ? "</span>" : "")
);
}
function fstp() {
//Obrisi broj na vrhu stoga i stavi ga u "result".
if (syntax == "fasm") asm("fstp dword [result]");
else if (syntax == "gas") asm("fstp dword ptr [result]");
else throw "Invalid syntax name!";
}
function fld() {
//Stavi broj iz varijable "result" na vrh stoga.
if (syntax == "fasm") asm("fld dword [result]");
else if (syntax == "gas") asm("fld dword ptr [result]");
else throw "Invalid syntax name!";
}
function fild() {
//Pretpostavi da je u "result"-u cijeli broj, pretvori ga u decimalni i stavi na stog.
if (syntax == "fasm") asm("fild dword [result]");
else if (syntax == "gas") asm("fild dword ptr [result]");
else throw "Invalid syntax name!";
}
function fistp() {
//Pretvori broj na vrhu stoga u cijeli broj, spremi ga u "result" i obrisi sa stoga.
if (syntax == "fasm") asm("fistp dword [result]");
else if (syntax == "gas") asm("fistp dword ptr [result]");
else throw "Invalid syntax name!";
}
var syntax = "fasm";
var verboseMode = false;
var varijable = new Object(); //Globalni objekt pomocu kojeg ce komunicirati strukture koje konstruira "Token", u C++-u bi to bio std::map<std::string,float>.
var alerted; //Prikazuje se samo jedna greska u svakom pokusaju interpretiranja ili compiliranja.
var highlight = typeof window != "undefined"; //Hocemo li sintaksno bojati Assembler (jer pokusaj da se to radi u Nashornu ili Rhinu, koji se pokrecu iz komandne linije, samo pravi probleme)?
if (typeof window == "undefined") {
//Nashorn, Rhino, Duktape i slicni JavaScript interpreteri...
eval("var alert=function(x){throw String(x);};"); //Ironicno, ali izgleda da je ovo nacin ispisivanja stringa na konzolu koji podrzava najvise JavaScript iterpretera (iako tome to uopce nije namijenjeno).
eval("var prompt=function(x){return null;};"); //Imate bolju ideju? Stvarno neobicno da JavaScript nema standardnu funkciju za ulaz sa standardnog ulaza, ali ima za ulaz sa prompt-boxa ako je pokrenut u GUI-u.
}
if (
typeof ArrayBuffer != "undefined" &&
typeof Float32Array != "undefined"
) {
//Moderni JavaScript interpreteri (koji podrzavaju naredbe "ArrayBuffer" i "Float32Array") mogu relativno jednostavno pretvarati decimalne brojeve u IEEE754 zapis.
getIEEE754 = function (decimalNumber) {
var floatArray = new Float32Array([decimalNumber]);
var buffer = floatArray.buffer;
var intArray = new Int32Array(buffer);
return (
(highlight ? '<span style="color:#007700">' : "") +
"0x" +
intArray[0].toString(16) +
(highlight ? "<\/span>" : "")
);
};
}
if (!Array.prototype.includes)
//Dirty-fix za starije preglednike koji ne podrzavaju JavaScript naredbu Array.includes (kao sto je Internet Explorer 6).
Array.prototype.includes = function (x) {
for (var i = 0; i < this.length; i++) if (this[i] == x) return true;
return false;
};
var boolean = [0, 1, "<", "=", ">", "&", "|", "not("]; // Sto sve vraca logicku vrijednost, a ne broj.
if (eval("0=='+'")) {
//https://github.com/svaarala/duktape/issues/2019
boolean[0] = "0"; //Imate bolju ideju?
boolean[1] = "1";
}
function Token(tmp) {
//Konstruktor strukture koju koristi parser
var ret = new Object();
ret.operands = [];
ret.text = tmp;
ret.depth = 0;
ret.DFS =
function () // Pokusat cu izbjeci stack overflow tako da se prvo kompajliraju "dublji" izrazi.
{
if (this.depth) return this.depth;
if (!this.operands.length) this.depth = 1;
else
for (var i = 0; i < this.operands.length; i++)
this.depth = Math.max(this.depth, this.operands[i].DFS() + 1);
return this.depth;
};
ret.toLisp = function () {
this.name = this.text;
if (
this.text.charAt(this.text.length - 1) == "(" ||
this.text.charAt(this.text.length - 1) == "["
)
this.name = this.text.slice(0, this.text.length - 1);
if (this.operands.length) {
var ret = "(" + this.name + " ";
for (var i = 0; i < this.operands.length; i++)
ret +=
this.operands[i].toLisp() +
(i == this.operands.length - 1 ? "" : " ");
ret += ")";
return ret.replace(/\)\s\)/g, "))");
} else return this.text.replace(/\)\s\)/g, "))");
};
ret.interpret = function () {
if (alerted) return 0 / 0;
else if (this.text == "+" && !this.operands.length)
//Ako netko unese "c++"
return 1;
else if (this.text.charAt(0) >= "0" && this.text.charAt(0) <= "9")
return this.text * 1;
else if (this.text == "?:")
return this.operands[0].interpret()
? this.operands[1].interpret()
: this.operands[2].interpret();
else if (this.text == "+")
return this.operands[0].interpret() + this.operands[1].interpret();
else if (this.text == "-")
return this.operands[0].interpret() - this.operands[1].interpret();
else if (this.text == "/")
return this.operands[0].interpret() / this.operands[1].interpret();
else if (this.text == "\\")
return this.operands[1].interpret() / this.operands[0].interpret();
else if (this.text == "*")
return this.operands[0].interpret() * this.operands[1].interpret();
else if (this.text == "sin(")
return Math.sin(this.operands[0].interpret());
else if (this.text == "cos(")
return Math.cos(this.operands[0].interpret());
else if (this.text == "tan(")
return Math.tan(this.operands[0].interpret());
else if (this.text == "atan2(")
return Math.atan2(
this.operands[0].interpret(),
this.operands[1].interpret()
);
else if (this.text == "arctan(")
return Math.atan(this.operands[0].interpret());
else if (this.text == "ctg(")
return 1 / Math.tan(this.operands[0].interpret());
else if (this.text == "arcctg(")
return Math.PI / 2 - Math.atan(this.operands[0].interpret());
else if (this.text == "sqrt(")
return Math.sqrt(this.operands[0].interpret());
else if (this.text == "arcsin(")
return Math.asin(this.operands[0].interpret());
else if (this.text == "arccos(")
return Math.acos(this.operands[0].interpret());
else if (this.text == "ln(")
return Math.log(this.operands[0].interpret());
else if (this.text == "log(")
return Math.log(this.operands[0].interpret()) / Math.log(10);
else if (this.text == "exp(")
return Math.exp(this.operands[0].interpret());
else if (this.text == "pow(")
return Math.pow(
this.operands[0].interpret(),
this.operands[1].interpret()
);
else if (this.text == "abs(")
return Math.abs(this.operands[0].interpret());
else if (this.text == "mod(")
return this.operands[0].interpret() % this.operands[1].interpret();
//U JavaScriptu, za razliku od C-a, operator '%' podrzava decimalne brojeve.
else if (this.text == "=")
return (
(this.operands[0].interpret() == this.operands[1].interpret()) * 1
);
else if (this.text == "<")
return (
(this.operands[0].interpret() < this.operands[1].interpret()) * 1
);
else if (this.text == ">")
return (
(this.operands[0].interpret() > this.operands[1].interpret()) * 1
);
else if (this.text == "not(") {
if (!boolean.includes(this.operands[0].text))
alert(
"Interpreter warning: Casting a non-Boolean number into Boolean, may cause undefined behaviour."
);
return !this.operands[0].interpret() * 1;
} else if (this.text == "&") {
if (
!boolean.includes(this.operands[0].text) ||
!boolean.includes(this.operands[1].text)
)
alert(
"Interpreter warning: Casting a non-Boolean number into Boolean, may cause undefined behaviour."
);
return (
(this.operands[0].interpret() && this.operands[1].interpret()) * 1
);
} else if (this.text == "|") {
if (
!boolean.includes(this.operands[0].text) ||
!boolean.includes(this.operands[1].text)
)
alert(
"Interpreter warning: Casting a non-Boolean number into Boolean, may cause undefined behaviour."
);
return (
(this.operands[0].interpret() || this.operands[1].interpret()) * 1
);
} else if (this.text.charAt(this.text.length - 1) == "(") {
alerted = 1;
alert(
"Interpreter error: Unrecognized function name '" +
this.text.slice(0, this.text.length - 1) +
"'."
);
return 0 / 0;
}
if (varijable[this.text] == null)
if (typeof window != "undefined")
/*U Duktapeu (JavaScript engineu
napisanom u cijelosti u C99,
ima znatno manje sposobnosti
optimizacije nego sto imaju Rhino
ili Nashorn, ali njegov se optimizator
barem ne rusi ako se pokrene na "manje
popularnim" platformama poput Androida),
Nashornu i Rhinu vjerojatno je najbolje
rjesenje traziti od vanjskog programa da
deklarira varijable i ispisati poruku o
pogresci ako on to nije napravio. Sto da
kazem o tim engineima, ja imam dojam
da su sporiji (a vjerojatno i bugovitiji) cak i
od Internet Explorera 6. Mislim, on mora ne
samo izvrsiti JavaScript, nego i CSS i parsirati
HTML, i kao da to sve skupa radi brze no sto Rhino i
Duktape izvrsavaju JavaScript, barem na Androidu.*/
varijable[this.text] = prompt(
"Enter the value of the variable '" + this.text + "'"
);
else
alert(
"Interpreter error: Variable '" +
this.text +
"' is not declared."
);
return varijable[this.text] * 1;
};
ret.commentedLispExpression = function () {
var commentedLispExpression = syntax == "gas" ? "#" : ";";
if (highlight)
commentedLispExpression =
'<span style="color:#777777">' +
commentedLispExpression +
"<\/span>";
var lispExpression =
'Pushing "' + this.toLisp() + '" to the FPU stack...';
for (var i = 0; i < lispExpression.length; i++) {
var currentChar = lispExpression.charAt(i);
if (highlight) {
if (currentChar == "&") currentChar = "&";
if (currentChar == "<") currentChar = "<";
if (currentChar == ">") currentChar = ">";
}
if (highlight)
commentedLispExpression +=
'<span style="color:#777777">' + currentChar + "<\/span>";
else commentedLispExpression += currentChar;
}
return commentedLispExpression;
};
ret.compile = function () {
if (this.text == " ") return;
if (this.text == "+" && !this.operands.length)
//Ako netko unese, na primjer, "c++".
this.text = "1";
//Problem: Sto ako netko unese "c--"? Da to rijesimo, morali bismo nekako izmijeniti parser, ako ne i tokenizer.
if (this.text == "?:") {
//Ako je rekurzija dosla na cvor u AST-u s uvijetnim operatorom.
this.operands[2].compile(); //Prevedi prvo treci operand na asemblerski...
this.operands[1].compile(); //...zatim prevedi drugi operand...
this.operands[0].compile(); //...te konacno prevedi uvijet.
//Sada je uvijet na vrhu FPU stoga.
if (verboseMode) asm(this.commentedLispExpression());
fistp(); //Prebaci taj uvijet u varijablu "rezultat".
asm("xor eax,eax"); //Obrisi sadrzaj CPU registra.
if (syntax == "fasm") asm("cmp dword [result],eax");