about summary refs log tree commit diff stats
path: root/html/subx/059read-byte.subx.html
blob: eb760dd4fbb9ebe5de0ab466cf84484bccbba616 (plain) (blame)
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Mu - subx/059read-byte.subx</title>
<meta name="Generator" content="Vim/8.0">
<meta name="plugin-version" content="vim7.4_v2">
<meta name="syntax" content="none">
<meta name="settings" content="number_lines,use_css,no_foldcolumn,expand_tabs,line_ids,prevent_copy=">
<meta name="colorscheme" content="minimal">
<style type="text/css">
<!--
pre { font-family: monospace; color: #aaaaaa; background-color: #080808; }
body { font-size:12pt; font-family: monospace; color: #aaaaaa; background-color: #080808; }
.subxS2Comment a { color:inherit; }
.subxS1Comment a { color:inherit; }
.subxComment a { color:inherit; }
.subxH2Comment a { color:inherit; }
.subxH1Comment a { color:inherit; }
* { font-size:12pt; font-size: 1em; }
.subxComment { color:#16bfff; }
.subxS2Comment { color:#4466ff; }
.LineNr { color:#444444; }
.subxS1Comment { color:#2d8cff; }
.SpecialChar { color: #ff0000; }
.Constant { color:#00a0a0; }
.CommentedCode { color: #6c6c6c; }
.subxH1Comment { color:#00ffff; }
-->
</style>

<script type='text/javascript'>
<!--

/* function to open any folds containing a jumped-to line before jumping to it */
function JumpToLine()
{
  var lineNum;
  lineNum = window.location.hash;
  lineNum = lineNum.substr(1); /* strip off '#' */

  if (lineNum.indexOf('L') == -1) {
    lineNum = 'L'+lineNum;
  }
  lineElem = document.getElementById(lineNum);
  /* Always jump to new location even if the line was hidden inside a fold, or
   * we corrected the raw number to a line ID.
   */
  if (lineElem) {
    lineElem.scrollIntoView(true);
  }
  return true;
}
if ('onhashchange' in window) {
  window.onhashchange = JumpToLine;
}

-->
</script>
</head>
<body onload='JumpToLine();'>
<a href='https://github.com/akkartik/mu/blob/master/subx/059read-byte.subx'>https://github.com/akkartik/mu/blob/master/subx/059read-byte.subx</a>
<pre id='vimCodeElement'>
<span id="L1" class="LineNr">  1 </span><span class="subxComment"># read-byte: one higher-level abstraction atop 'read'.</span>
<span id="L2" class="LineNr">  2 </span><span class="subxComment">#</span>
<span id="L3" class="LineNr">  3 </span><span class="subxComment"># There are many situations where 'read' is a lot to manage, and we need</span>
<span id="L4" class="LineNr">  4 </span><span class="subxComment"># to abstract some details away. One of them is when we want to read a file</span>
<span id="L5" class="LineNr">  5 </span><span class="subxComment"># character by character. In this situation we follow C's FILE data structure,</span>
<span id="L6" class="LineNr">  6 </span><span class="subxComment"># which manages the underlying file descriptor together with the buffer it</span>
<span id="L7" class="LineNr">  7 </span><span class="subxComment"># reads into. We call our version 'buffered-file'. Should be useful with other</span>
<span id="L8" class="LineNr">  8 </span><span class="subxComment"># primitives as well, in later layers.</span>
<span id="L9" class="LineNr">  9 </span>
<span id="L10" class="LineNr"> 10 </span>== data
<span id="L11" class="LineNr"> 11 </span>
<span id="L12" class="LineNr"> 12 </span><span class="subxComment"># The buffered file for standard input. Also illustrates the layout for</span>
<span id="L13" class="LineNr"> 13 </span><span class="subxComment"># buffered-file.</span>
<span id="L14" class="LineNr"> 14 </span>
<span id="L15" class="LineNr"> 15 </span><span class="SpecialChar">Stdin</span>:
<span id="L16" class="LineNr"> 16 </span>    <span class="subxComment"># file descriptor or (address stream)</span>
<span id="L17" class="LineNr"> 17 </span>    00 00 00 00  <span class="subxComment"># 0 = standard input</span>
<span id="L18" class="LineNr"> 18 </span>    <span class="subxComment"># current write index</span>
<span id="L19" class="LineNr"> 19 </span>    00 00 00 00
<span id="L20" class="LineNr"> 20 </span>    <span class="subxComment"># current read index</span>
<span id="L21" class="LineNr"> 21 </span>    00 00 00 00
<span id="L22" class="LineNr"> 22 </span>    <span class="subxComment"># length (8)</span>
<span id="L23" class="LineNr"> 23 </span>    08 00 00 00
<span id="L24" class="LineNr"> 24 </span>    <span class="subxComment"># data</span>
<span id="L25" class="LineNr"> 25 </span>    00 00 00 00 00 00 00 00  <span class="subxComment"># 8 bytes</span>
<span id="L26" class="LineNr"> 26 </span>
<span id="L27" class="LineNr"> 27 </span><span class="subxComment"># TODO: 8 bytes is too small. We'll need to grow the buffer for efficiency.</span>
<span id="L28" class="LineNr"> 28 </span>
<span id="L29" class="LineNr"> 29 </span>== code
<span id="L30" class="LineNr"> 30 </span><span class="subxComment">#   instruction                     effective address                                                   register    displacement    immediate</span>
<span id="L31" class="LineNr"> 31 </span><span class="subxS1Comment"># . op          subop               mod             rm32          base        index         scale       r32</span>
<span id="L32" class="LineNr"> 32 </span><span class="subxS1Comment"># . 1-3 bytes   3 bits              2 bits          3 bits        3 bits      3 bits        2 bits      2 bits      0/1/2/4 bytes   0/1/2/4 bytes</span>
<span id="L33" class="LineNr"> 33 </span>
<span id="L34" class="LineNr"> 34 </span><span class="subxComment"># main:</span>
<span id="L35" class="LineNr"> 35 </span>    e8/call  run-tests/disp32  <span class="subxComment"># 'run-tests' is a function created automatically by SubX. It calls all functions that start with 'test-'.</span>
<span id="L36" class="LineNr"> 36 </span><span class="CommentedCode">#?     e8/call  test-read-byte-multiple/disp32</span>
<span id="L37" class="LineNr"> 37 </span>    <span class="subxComment"># syscall(exit, Num-test-failures)</span>
<span id="L38" class="LineNr"> 38 </span>    8b/copy                         0/mod/indirect  5/rm32/.disp32           <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>          3/r32/EBX   <span class="SpecialChar">Num-test-failures</span>/disp32          <span class="subxComment"># copy *Num-test-failures to EBX</span>
<span id="L39" class="LineNr"> 39 </span>    b8/copy-to-EAX  1/imm32
<span id="L40" class="LineNr"> 40 </span>    cd/syscall  0x80/imm8
<span id="L41" class="LineNr"> 41 </span>
<span id="L42" class="LineNr"> 42 </span><span class="subxComment"># return next byte value in EAX, with top 3 bytes cleared.</span>
<span id="L43" class="LineNr"> 43 </span><span class="subxComment"># On EOF, return 0xffffffff.</span>
<span id="L44" class="LineNr"> 44 </span>read-byte:  <span class="subxComment"># f : (address buffered-file) -&gt; byte/EAX</span>
<span id="L45" class="LineNr"> 45 </span>    <span class="subxS1Comment"># . prolog</span>
<span id="L46" class="LineNr"> 46 </span>    55/push-EBP
<span id="L47" class="LineNr"> 47 </span>    89/copy                         3/mod/direct    5/rm32/EBP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>          4/r32/ESP  <span class="CommentedCode"> . </span>             <span class="CommentedCode"> . </span>                <span class="subxComment"># copy ESP to EBP</span>
<span id="L48" class="LineNr"> 48 </span>    <span class="subxS1Comment"># . save registers</span>
<span id="L49" class="LineNr"> 49 </span>    51/push-ECX
<span id="L50" class="LineNr"> 50 </span>    56/push-ESI
<span id="L51" class="LineNr"> 51 </span>    <span class="subxComment"># ESI = f</span>
<span id="L52" class="LineNr"> 52 </span>    8b/copy                         1/mod/*+disp8   4/rm32/sib    5/base/EBP  4/index/none <span class="CommentedCode"> . </span>          6/r32/ESI   8/disp8        <span class="CommentedCode"> . </span>                <span class="subxComment"># copy *(EBP+8) to ESI</span>
<span id="L53" class="LineNr"> 53 </span>    <span class="subxComment"># ECX = f-&gt;read</span>
<span id="L54" class="LineNr"> 54 </span>    8b/copy                         1/mod/*+disp8   6/rm32/ESI   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>          1/r32/ECX   8/disp8        <span class="CommentedCode"> . </span>                <span class="subxComment"># copy *(ESI+8) to ECX</span>
<span id="L55" class="LineNr"> 55 </span>    <span class="subxComment"># if (f-&gt;read &lt; f-&gt;write) read byte from stream</span>
<span id="L56" class="LineNr"> 56 </span>    3b/compare                      1/mod/*+disp8   6/rm32/ESI   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>          1/r32/ECX   4/disp8        <span class="CommentedCode"> . </span>                <span class="subxComment"># compare ECX with *(ESI+4)</span>
<span id="L57" class="LineNr"> 57 </span>    7c/jump-if-lesser  $read-byte:from-stream/disp8
<span id="L58" class="LineNr"> 58 </span>    <span class="subxComment"># otherwise first populate stream from file</span>
<span id="L59" class="LineNr"> 59 </span>    <span class="subxS1Comment"># . clear-stream(stream = f+4)</span>
<span id="L60" class="LineNr"> 60 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L61" class="LineNr"> 61 </span>    8d/copy-address                 1/mod/*+disp8   6/rm32/ESI   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>          0/r32/EAX   4/disp8        <span class="CommentedCode"> . </span>                <span class="subxComment"># copy ESI+4 to EAX</span>
<span id="L62" class="LineNr"> 62 </span>    50/push-EAX
<span id="L63" class="LineNr"> 63 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L64" class="LineNr"> 64 </span>    e8/call  clear-stream/disp32
<span id="L65" class="LineNr"> 65 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L66" class="LineNr"> 66 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L67" class="LineNr"> 67 </span>    <span class="subxS1Comment"># . EAX = read(f-&gt;fd, stream = f+4)</span>
<span id="L68" class="LineNr"> 68 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L69" class="LineNr"> 69 </span>    50/push-EAX
<span id="L70" class="LineNr"> 70 </span>    ff          6/subop/push        0/mod/indirect  6/rm32/ESI   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>             <span class="CommentedCode"> . </span>                <span class="subxComment"># push *ESI</span>
<span id="L71" class="LineNr"> 71 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L72" class="LineNr"> 72 </span>    e8/call  read/disp32
<span id="L73" class="LineNr"> 73 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L74" class="LineNr"> 74 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              8/imm32           <span class="subxComment"># add to ESP</span>
<span id="L75" class="LineNr"> 75 </span>    <span class="subxComment"># if EAX = 0 return 0xffffffff</span>
<span id="L76" class="LineNr"> 76 </span>    81          7/subop/compare     3/mod/direct    0/rm32/EAX   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              0/imm32           <span class="subxComment"># compare EAX</span>
<span id="L77" class="LineNr"> 77 </span>    75/jump-if-not-equal  $read-byte:from-stream/disp8
<span id="L78" class="LineNr"> 78 </span>    b8/copy-to-EAX  0xffffffff/imm32
<span id="L79" class="LineNr"> 79 </span>    eb/jump  $read-byte:end/disp8
<span id="L80" class="LineNr"> 80 </span>$read-byte:from-stream:
<span id="L81" class="LineNr"> 81 </span>    <span class="subxComment"># reading from stream</span>
<span id="L82" class="LineNr"> 82 </span>    <span class="subxComment"># AL = f-&gt;data[f-&gt;read]</span>
<span id="L83" class="LineNr"> 83 </span>    31/xor                          3/mod/direct    0/rm32/EAX   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>          0/r32/EAX  <span class="CommentedCode"> . </span>             <span class="CommentedCode"> . </span>                <span class="subxComment"># clear EAX</span>
<span id="L84" class="LineNr"> 84 </span>    8a/copy-byte                    1/mod/*+disp8   4/rm32/sib    6/base/ESI  1/index/ECX  <span class="CommentedCode"> . </span>          0/r32/AL    0x10/disp8     <span class="CommentedCode"> . </span>                <span class="subxComment"># copy *(ESI+ECX+16) to AL</span>
<span id="L85" class="LineNr"> 85 </span>    <span class="subxComment"># ++f-&gt;read</span>
<span id="L86" class="LineNr"> 86 </span>    ff          0/subop/increment   1/mod/*+disp8   6/rm32/ESI   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>          8/disp8        <span class="CommentedCode"> . </span>                <span class="subxComment"># increment *(ESI+8)</span>
<span id="L87" class="LineNr"> 87 </span>$read-byte:end:
<span id="L88" class="LineNr"> 88 </span>    <span class="subxS1Comment"># . restore registers</span>
<span id="L89" class="LineNr"> 89 </span>    5e/pop-to-ESI
<span id="L90" class="LineNr"> 90 </span>    59/pop-to-ECX
<span id="L91" class="LineNr"> 91 </span>    <span class="subxS1Comment"># . epilog</span>
<span id="L92" class="LineNr"> 92 </span>    89/copy                         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>          5/r32/EBP  <span class="CommentedCode"> . </span>             <span class="CommentedCode"> . </span>                <span class="subxComment"># copy EBP to ESP</span>
<span id="L93" class="LineNr"> 93 </span>    5d/pop-to-EBP
<span id="L94" class="LineNr"> 94 </span>    c3/return
<span id="L95" class="LineNr"> 95 </span>
<span id="L96" class="LineNr"> 96 </span><span class="subxComment"># todo: how should write-byte look? What should it do when the output has no</span>
<span id="L97" class="LineNr"> 97 </span><span class="subxComment"># space remaining? Maybe return an error code.</span>
<span id="L98" class="LineNr"> 98 </span>
<span id="L99" class="LineNr"> 99 </span><span class="subxH1Comment"># - tests</span>
<span id="L100" class="LineNr">100 </span>
<span id="L101" class="LineNr">101 </span>test-read-byte-single:
<span id="L102" class="LineNr">102 </span>    <span class="subxH1Comment"># - check that read-byte returns first byte of 'file'</span>
<span id="L103" class="LineNr">103 </span>    <span class="subxComment"># setup</span>
<span id="L104" class="LineNr">104 </span>    <span class="subxS1Comment"># . clear-stream(_test-stream)</span>
<span id="L105" class="LineNr">105 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L106" class="LineNr">106 </span>    68/push  _test-stream/imm32
<span id="L107" class="LineNr">107 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L108" class="LineNr">108 </span>    e8/call  clear-stream/disp32
<span id="L109" class="LineNr">109 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L110" class="LineNr">110 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L111" class="LineNr">111 </span>    <span class="subxS1Comment"># . clear-stream(_test-buffered-file+4)</span>
<span id="L112" class="LineNr">112 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L113" class="LineNr">113 </span>    b8/copy-to-EAX  _test-buffered-file/imm32
<span id="L114" class="LineNr">114 </span>    05/add-to-EAX  4/imm32
<span id="L115" class="LineNr">115 </span>    50/push-EAX
<span id="L116" class="LineNr">116 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L117" class="LineNr">117 </span>    e8/call  clear-stream/disp32
<span id="L118" class="LineNr">118 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L119" class="LineNr">119 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L120" class="LineNr">120 </span>    <span class="subxS1Comment"># . write(_test-stream, &quot;Ab&quot;)</span>
<span id="L121" class="LineNr">121 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L122" class="LineNr">122 </span>    68/push  <span class="Constant">&quot;Ab&quot;</span>/imm32
<span id="L123" class="LineNr">123 </span>    68/push  _test-stream/imm32
<span id="L124" class="LineNr">124 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L125" class="LineNr">125 </span>    e8/call  write/disp32
<span id="L126" class="LineNr">126 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L127" class="LineNr">127 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              8/imm32           <span class="subxComment"># add to ESP</span>
<span id="L128" class="LineNr">128 </span>    <span class="subxComment"># read-byte(_test-buffered-file)</span>
<span id="L129" class="LineNr">129 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L130" class="LineNr">130 </span>    68/push  _test-buffered-file/imm32
<span id="L131" class="LineNr">131 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L132" class="LineNr">132 </span>    e8/call  read-byte/disp32
<span id="L133" class="LineNr">133 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L134" class="LineNr">134 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L135" class="LineNr">135 </span>    <span class="subxComment"># check-ints-equal(EAX, 'A')</span>
<span id="L136" class="LineNr">136 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L137" class="LineNr">137 </span>    68/push  <span class="Constant">&quot;F - test-read-byte-single&quot;</span>/imm32
<span id="L138" class="LineNr">138 </span>    68/push  0x41/imm32
<span id="L139" class="LineNr">139 </span>    50/push-EAX
<span id="L140" class="LineNr">140 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L141" class="LineNr">141 </span>    e8/call  check-ints-equal/disp32
<span id="L142" class="LineNr">142 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L143" class="LineNr">143 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              0xc/imm32         <span class="subxComment"># add to ESP</span>
<span id="L144" class="LineNr">144 </span>    <span class="subxS1Comment"># . end</span>
<span id="L145" class="LineNr">145 </span>    c3/return
<span id="L146" class="LineNr">146 </span>
<span id="L147" class="LineNr">147 </span>test-read-byte-multiple:
<span id="L148" class="LineNr">148 </span>    <span class="subxH1Comment"># - call read-byte twice, check that second call returns second byte</span>
<span id="L149" class="LineNr">149 </span>    <span class="subxComment"># setup</span>
<span id="L150" class="LineNr">150 </span>    <span class="subxS1Comment"># . clear-stream(_test-stream)</span>
<span id="L151" class="LineNr">151 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L152" class="LineNr">152 </span>    68/push  _test-stream/imm32
<span id="L153" class="LineNr">153 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L154" class="LineNr">154 </span>    e8/call  clear-stream/disp32
<span id="L155" class="LineNr">155 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L156" class="LineNr">156 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L157" class="LineNr">157 </span>    <span class="subxS1Comment"># . clear-stream(_test-buffered-file+4)</span>
<span id="L158" class="LineNr">158 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L159" class="LineNr">159 </span>    b8/copy-to-EAX  _test-buffered-file/imm32
<span id="L160" class="LineNr">160 </span>    05/add-to-EAX  4/imm32
<span id="L161" class="LineNr">161 </span>    50/push-EAX
<span id="L162" class="LineNr">162 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L163" class="LineNr">163 </span>    e8/call  clear-stream/disp32
<span id="L164" class="LineNr">164 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L165" class="LineNr">165 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L166" class="LineNr">166 </span>    <span class="subxS1Comment"># . write(_test-stream, &quot;Ab&quot;)</span>
<span id="L167" class="LineNr">167 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L168" class="LineNr">168 </span>    68/push  <span class="Constant">&quot;Ab&quot;</span>/imm32
<span id="L169" class="LineNr">169 </span>    68/push  _test-stream/imm32
<span id="L170" class="LineNr">170 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L171" class="LineNr">171 </span>    e8/call  write/disp32
<span id="L172" class="LineNr">172 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L173" class="LineNr">173 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              8/imm32           <span class="subxComment"># add to ESP</span>
<span id="L174" class="LineNr">174 </span>    <span class="subxComment"># read-byte(_test-buffered-file)</span>
<span id="L175" class="LineNr">175 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L176" class="LineNr">176 </span>    68/push  _test-buffered-file/imm32
<span id="L177" class="LineNr">177 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L178" class="LineNr">178 </span>    e8/call  read-byte/disp32
<span id="L179" class="LineNr">179 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L180" class="LineNr">180 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L181" class="LineNr">181 </span>    <span class="subxComment"># read-byte(_test-buffered-file)</span>
<span id="L182" class="LineNr">182 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L183" class="LineNr">183 </span>    68/push  _test-buffered-file/imm32
<span id="L184" class="LineNr">184 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L185" class="LineNr">185 </span>    e8/call  read-byte/disp32
<span id="L186" class="LineNr">186 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L187" class="LineNr">187 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L188" class="LineNr">188 </span>    <span class="subxComment"># check-ints-equal(EAX, 'b')</span>
<span id="L189" class="LineNr">189 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L190" class="LineNr">190 </span>    68/push  <span class="Constant">&quot;F - test-read-byte-multiple&quot;</span>/imm32
<span id="L191" class="LineNr">191 </span>    68/push  0x62/imm32
<span id="L192" class="LineNr">192 </span>    50/push-EAX
<span id="L193" class="LineNr">193 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L194" class="LineNr">194 </span>    e8/call  check-ints-equal/disp32
<span id="L195" class="LineNr">195 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L196" class="LineNr">196 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              0xc/imm32         <span class="subxComment"># add to ESP</span>
<span id="L197" class="LineNr">197 </span>    <span class="subxS1Comment"># . end</span>
<span id="L198" class="LineNr">198 </span>    c3/return
<span id="L199" class="LineNr">199 </span>
<span id="L200" class="LineNr">200 </span>test-read-byte-end-of-file:
<span id="L201" class="LineNr">201 </span>    <span class="subxH1Comment"># - call read-byte on an empty 'file', check that it returns -1</span>
<span id="L202" class="LineNr">202 </span>    <span class="subxComment"># setup</span>
<span id="L203" class="LineNr">203 </span>    <span class="subxS1Comment"># . clear-stream(_test-stream)</span>
<span id="L204" class="LineNr">204 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L205" class="LineNr">205 </span>    68/push  _test-stream/imm32
<span id="L206" class="LineNr">206 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L207" class="LineNr">207 </span>    e8/call  clear-stream/disp32
<span id="L208" class="LineNr">208 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L209" class="LineNr">209 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L210" class="LineNr">210 </span>    <span class="subxS1Comment"># . clear-stream(_test-buffered-file+4)</span>
<span id="L211" class="LineNr">211 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L212" class="LineNr">212 </span>    b8/copy-to-EAX  _test-buffered-file/imm32
<span id="L213" class="LineNr">213 </span>    05/add-to-EAX  4/imm32
<span id="L214" class="LineNr">214 </span>    50/push-EAX
<span id="L215" class="LineNr">215 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L216" class="LineNr">216 </span>    e8/call  clear-stream/disp32
<span id="L217" class="LineNr">217 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L218" class="LineNr">218 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L219" class="LineNr">219 </span>    <span class="subxComment"># read-byte(_test-buffered-file)</span>
<span id="L220" class="LineNr">220 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L221" class="LineNr">221 </span>    68/push  _test-buffered-file/imm32
<span id="L222" class="LineNr">222 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L223" class="LineNr">223 </span>    e8/call  read-byte/disp32
<span id="L224" class="LineNr">224 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L225" class="LineNr">225 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              4/imm32           <span class="subxComment"># add to ESP</span>
<span id="L226" class="LineNr">226 </span>    <span class="subxComment"># check-ints-equal(EAX, -1)</span>
<span id="L227" class="LineNr">227 </span>    <span class="subxS2Comment"># . . push args</span>
<span id="L228" class="LineNr">228 </span>    68/push  <span class="Constant">&quot;F - test-read-byte-end-of-file&quot;</span>/imm32
<span id="L229" class="LineNr">229 </span>    68/push  -1/imm32
<span id="L230" class="LineNr">230 </span>    50/push-EAX
<span id="L231" class="LineNr">231 </span>    <span class="subxS2Comment"># . . call</span>
<span id="L232" class="LineNr">232 </span>    e8/call  check-ints-equal/disp32
<span id="L233" class="LineNr">233 </span>    <span class="subxS2Comment"># . . discard args</span>
<span id="L234" class="LineNr">234 </span>    81          0/subop/add         3/mod/direct    4/rm32/ESP   <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>           <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>         <span class="CommentedCode"> . </span>              0xc/imm32         <span class="subxComment"># add to ESP</span>
<span id="L235" class="LineNr">235 </span>    <span class="subxS1Comment"># . end</span>
<span id="L236" class="LineNr">236 </span>    c3/return
<span id="L237" class="LineNr">237 </span>
<span id="L238" class="LineNr">238 </span>== data
<span id="L239" class="LineNr">239 </span>
<span id="L240" class="LineNr">240 </span>_test-buffered-file:
<span id="L241" class="LineNr">241 </span>    <span class="subxComment"># file descriptor or (address stream)</span>
<span id="L242" class="LineNr">242 </span>    _test-stream/imm32
<span id="L243" class="LineNr">243 </span>    <span class="subxComment"># current write index</span>
<span id="L244" class="LineNr">244 </span>    00 00 00 00
<span id="L245" class="LineNr">245 </span>    <span class="subxComment"># current read index</span>
<span id="L246" class="LineNr">246 </span>    00 00 00 00
<span id="L247" class="LineNr">247 </span>    <span class="subxComment"># length (8)</span>
<span id="L248" class="LineNr">248 </span>    08 00 00 00
<span id="L249" class="LineNr">249 </span>    <span class="subxComment"># data</span>
<span id="L250" class="LineNr">250 </span>    00 00 00 00 00 00 00 00  <span class="subxComment"># 8 bytes</span>
<span id="L251" class="LineNr">251 </span>
<span id="L252" class="LineNr">252 </span><span class="subxS2Comment"># . . vim&#0058;nowrap:textwidth=0</span>
</pre>
</body>
</html>
<!-- vim: set foldmethod=manual : -->
result) proc lenField(p: BProc): Rope = result = rope(if p.module.compileToCpp: "len" else: "Sup.len") include ccgcalls, "ccgstmts.nim" proc initFrame(p: BProc, procname, filename: Rope): Rope = discard cgsym(p.module, "nimFrame") if p.maxFrameLen > 0: discard cgsym(p.module, "VarSlot") result = ropecg(p.module, "\tnimfrs_($1, $2, $3, $4);$n", procname, filename, p.maxFrameLen.rope, p.blocks[0].frameLen.rope) else: result = ropecg(p.module, "\tnimfr_($1, $2);$n", procname, filename) proc initFrameNoDebug(p: BProc; frame, procname, filename: Rope; line: int): Rope = discard cgsym(p.module, "nimFrame") addf(p.blocks[0].sections[cpsLocals], "TFrame $1;$n", [frame]) result = ropecg(p.module, "\t$1.procname = $2; $1.filename = $3; " & " $1.line = $4; $1.len = -1; nimFrame(&$1);$n", frame, procname, filename, rope(line)) proc deinitFrameNoDebug(p: BProc; frame: Rope): Rope = result = ropecg(p.module, "\t#popFrameOfAddr(&$1);$n", frame) proc deinitFrame(p: BProc): Rope = result = ropecg(p.module, "\t#popFrame();$n") include ccgexprs # ----------------------------- dynamic library handling ----------------- # We don't finalize dynamic libs as the OS does this for us. proc isGetProcAddr(lib: PLib): bool = let n = lib.path result = n.kind in nkCallKinds and n.typ != nil and n.typ.kind in {tyPointer, tyProc} proc loadDynamicLib(m: BModule, lib: PLib) = assert(lib != nil) if not lib.generated: lib.generated = true var tmp = getTempName(m) assert(lib.name == nil) lib.name = tmp # BUGFIX: cgsym has awful side-effects addf(m.s[cfsVars], "static void* $1;$n", [tmp]) if lib.path.kind in {nkStrLit..nkTripleStrLit}: var s: TStringSeq = @[] libCandidates(lib.path.strVal, s) rawMessage(m.config, hintDependency, lib.path.strVal) var loadlib: Rope = nil for i in countup(0, high(s)): inc(m.labels) if i > 0: add(loadlib, "||") let n = newStrNode(nkStrLit, s[i]) n.info = lib.path.info appcg(m, loadlib, "($1 = #nimLoadLibrary($2))$n", [tmp, genStringLiteral(m, n)]) appcg(m, m.s[cfsDynLibInit], "if (!($1)) #nimLoadLibraryError($2);$n", [loadlib, genStringLiteral(m, lib.path)]) else: var p = newProc(nil, m) p.options = p.options - {optStackTrace, optEndb} var dest: TLoc initLocExpr(p, lib.path, dest) add(m.s[cfsVars], p.s(cpsLocals)) add(m.s[cfsDynLibInit], p.s(cpsInit)) add(m.s[cfsDynLibInit], p.s(cpsStmts)) appcg(m, m.s[cfsDynLibInit], "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n", [tmp, rdLoc(dest)]) if lib.name == nil: internalError(m.config, "loadDynamicLib") proc mangleDynLibProc(sym: PSym): Rope = if sfCompilerProc in sym.flags: # NOTE: sym.loc.r is the external name! result = rope(sym.name.s) else: result = "Dl_$1_" % [rope(sym.id)] proc symInDynamicLib(m: BModule, sym: PSym) = var lib = sym.annex let isCall = isGetProcAddr(lib) var extname = sym.loc.r if not isCall: loadDynamicLib(m, lib) var tmp = mangleDynLibProc(sym) sym.loc.r = tmp # from now on we only need the internal name sym.typ.sym = nil # generate a new name inc(m.labels, 2) if isCall: let n = lib.path var a: TLoc initLocExpr(m.initProc, n[0], a) var params = rdLoc(a) & "(" for i in 1 .. n.len-2: initLocExpr(m.initProc, n[i], a) params.add(rdLoc(a)) params.add(", ") let load = "\t$1 = ($2) ($3$4));$n" % [tmp, getTypeDesc(m, sym.typ), params, makeCString($extname)] var last = lastSon(n) if last.kind == nkHiddenStdConv: last = last.sons[1] internalAssert(m.config, last.kind == nkStrLit) let idx = last.strVal if idx.len == 0: add(m.initProc.s(cpsStmts), load) elif idx.len == 1 and idx[0] in {'0'..'9'}: add(m.extensionLoaders[idx[0]], load) else: internalError(m.config, sym.info, "wrong index: " & idx) else: appcg(m, m.s[cfsDynLibInit], "\t$1 = ($2) #nimGetProcAddr($3, $4);$n", [tmp, getTypeDesc(m, sym.typ), lib.name, makeCString($extname)]) addf(m.s[cfsVars], "$2 $1;$n", [sym.loc.r, getTypeDesc(m, sym.loc.t)]) proc varInDynamicLib(m: BModule, sym: PSym) = var lib = sym.annex var extname = sym.loc.r loadDynamicLib(m, lib) incl(sym.loc.flags, lfIndirect) var tmp = mangleDynLibProc(sym) sym.loc.r = tmp # from now on we only need the internal name inc(m.labels, 2) appcg(m, m.s[cfsDynLibInit], "$1 = ($2*) #nimGetProcAddr($3, $4);$n", [tmp, getTypeDesc(m, sym.typ), lib.name, makeCString($extname)]) addf(m.s[cfsVars], "$2* $1;$n", [sym.loc.r, getTypeDesc(m, sym.loc.t)]) proc symInDynamicLibPartial(m: BModule, sym: PSym) = sym.loc.r = mangleDynLibProc(sym) sym.typ.sym = nil # generate a new name proc cgsym(m: BModule, name: string): Rope = let sym = magicsys.getCompilerProc(m.g.graph, name) if sym != nil: case sym.kind of skProc, skFunc, skMethod, skConverter, skIterator: genProc(m, sym) of skVar, skResult, skLet: genVarPrototype(m, newSymNode sym) of skType: discard getTypeDesc(m, sym.typ) else: internalError(m.config, "cgsym: " & name & ": " & $sym.kind) else: # we used to exclude the system module from this check, but for DLL # generation support this sloppyness leads to hard to detect bugs, so # we're picky here for the system module too: rawMessage(m.config, errGenerated, "system module needs: " & name) result = sym.loc.r proc generateHeaders(m: BModule) = add(m.s[cfsHeaders], "\L#include \"nimbase.h\"\L") for it in m.headerFiles: if it[0] == '#': add(m.s[cfsHeaders], rope(it.replace('`', '"') & "\L")) elif it[0] notin {'\"', '<'}: addf(m.s[cfsHeaders], "#include \"$1\"$N", [rope(it)]) else: addf(m.s[cfsHeaders], "#include $1$N", [rope(it)]) add(m.s[cfsHeaders], "#undef LANGUAGE_C\L") add(m.s[cfsHeaders], "#undef MIPSEB\L") add(m.s[cfsHeaders], "#undef MIPSEL\L") add(m.s[cfsHeaders], "#undef PPC\L") add(m.s[cfsHeaders], "#undef R3000\L") add(m.s[cfsHeaders], "#undef R4000\L") add(m.s[cfsHeaders], "#undef i386\L") add(m.s[cfsHeaders], "#undef linux\L") add(m.s[cfsHeaders], "#undef mips\L") add(m.s[cfsHeaders], "#undef near\L") add(m.s[cfsHeaders], "#undef powerpc\L") add(m.s[cfsHeaders], "#undef unix\L") proc openNamespaceNim(): Rope = result.add("namespace Nim {\L") proc closeNamespaceNim(): Rope = result.add("}\L") proc closureSetup(p: BProc, prc: PSym) = if tfCapturesEnv notin prc.typ.flags: return # prc.ast[paramsPos].last contains the type we're after: var ls = lastSon(prc.ast[paramsPos]) if ls.kind != nkSym: internalError(p.config, prc.info, "closure generation failed") var env = ls.sym #echo "created environment: ", env.id, " for ", prc.name.s assignLocalVar(p, ls) # generate cast assignment: linefmt(p, cpsStmts, "$1 = ($2) ClE_0;$n", rdLoc(env.loc), getTypeDesc(p.module, env.typ)) proc containsResult(n: PNode): bool = if n.kind == nkSym and n.sym.kind == skResult: result = true else: for i in 0..<n.safeLen: if containsResult(n[i]): return true proc easyResultAsgn(n: PNode): PNode = const harmless = {nkConstSection, nkTypeSection, nkEmpty, nkCommentStmt} + declarativeDefs case n.kind of nkStmtList, nkStmtListExpr: var i = 0 while i < n.len and n[i].kind in harmless: inc i if i < n.len: result = easyResultAsgn(n[i]) of nkAsgn, nkFastAsgn: if n[0].kind == nkSym and n[0].sym.kind == skResult and not containsResult(n[1]): incl n.flags, nfPreventCg return n[1] of nkReturnStmt: if n.len > 0: result = easyResultAsgn(n[0]) if result != nil: incl n.flags, nfPreventCg else: discard proc genProcAux(m: BModule, prc: PSym) = var p = newProc(prc, m) var header = genProcHeader(m, prc) var returnStmt: Rope = nil assert(prc.ast != nil) if sfPure notin prc.flags and prc.typ.sons[0] != nil: if resultPos >= prc.ast.len: internalError(m.config, prc.info, "proc has no result symbol") let resNode = prc.ast.sons[resultPos] let res = resNode.sym # get result symbol if not isInvalidReturnType(m.config, prc.typ.sons[0]): if sfNoInit in prc.flags: incl(res.flags, sfNoInit) if sfNoInit in prc.flags and p.module.compileToCpp and (let val = easyResultAsgn(prc.getBody); val != nil): var decl = localVarDecl(p, resNode) var a: TLoc initLocExprSingleUse(p, val, a) linefmt(p, cpsStmts, "$1 = $2;$n", decl, rdLoc(a)) else: # declare the result symbol: assignLocalVar(p, resNode) assert(res.loc.r != nil) initLocalVar(p, res, immediateAsgn=false) returnStmt = ropecg(p.module, "\treturn $1;$n", rdLoc(res.loc)) else: fillResult(p.config, resNode) assignParam(p, res) if sfNoInit notin prc.flags: resetLoc(p, res.loc) if skipTypes(res.typ, abstractInst).kind == tyArray: #incl(res.loc.flags, lfIndirect) res.loc.storage = OnUnknown for i in countup(1, sonsLen(prc.typ.n) - 1): let param = prc.typ.n.sons[i].sym if param.typ.isCompileTimeOnly: continue assignParam(p, param) closureSetup(p, prc) genStmts(p, prc.getBody) # modifies p.locals, p.init, etc. var generatedProc: Rope if sfNoReturn in prc.flags: if hasDeclspec in extccomp.CC[p.config.cCompiler].props: header = "__declspec(noreturn) " & header if sfPure in prc.flags: if hasDeclspec in extccomp.CC[p.config.cCompiler].props: header = "__declspec(naked) " & header generatedProc = ropecg(p.module, "$N$1 {$n$2$3$4}$N$N", header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)) else: generatedProc = ropecg(p.module, "$N$1 {$N", header) add(generatedProc, initGCFrame(p)) if optStackTrace in prc.options: add(generatedProc, p.s(cpsLocals)) var procname = makeCString(prc.name.s) add(generatedProc, initFrame(p, procname, quotedFilename(p.config, prc.info))) else: add(generatedProc, p.s(cpsLocals)) if optProfiler in prc.options: # invoke at proc entry for recursion: appcg(p, cpsInit, "\t#nimProfile();$n", []) if p.beforeRetNeeded: add(generatedProc, "{") add(generatedProc, p.s(cpsInit)) add(generatedProc, p.s(cpsStmts)) if p.beforeRetNeeded: add(generatedProc, ~"\t}BeforeRet_: ;$n") add(generatedProc, deinitGCFrame(p)) if optStackTrace in prc.options: add(generatedProc, deinitFrame(p)) add(generatedProc, returnStmt) add(generatedProc, ~"}$N") add(m.s[cfsProcs], generatedProc) proc requiresExternC(m: BModule; sym: PSym): bool {.inline.} = result = (sfCompileToCpp in m.module.flags and sfCompileToCpp notin sym.getModule().flags and m.config.cmd != cmdCompileToCpp) or ( sym.flags * {sfImportc, sfInfixCall, sfCompilerProc} == {sfImportc} and sym.magic == mNone and m.config.cmd == cmdCompileToCpp) proc genProcPrototype(m: BModule, sym: PSym) = useHeader(m, sym) if lfNoDecl in sym.loc.flags: return if lfDynamicLib in sym.loc.flags: if getModule(sym).id != m.module.id and not containsOrIncl(m.declaredThings, sym.id): add(m.s[cfsVars], ropecg(m, "extern $1 $2;$n", getTypeDesc(m, sym.loc.t), mangleDynLibProc(sym))) elif not containsOrIncl(m.declaredProtos, sym.id): var header = genProcHeader(m, sym) if sfNoReturn in sym.flags and hasDeclspec in extccomp.CC[m.config.cCompiler].props: header = "__declspec(noreturn) " & header if sym.typ.callConv != ccInline and requiresExternC(m, sym): header = "extern \"C\" " & header if sfPure in sym.flags and hasAttribute in CC[m.config.cCompiler].props: header.add(" __attribute__((naked))") if sfNoReturn in sym.flags and hasAttribute in CC[m.config.cCompiler].props: header.add(" __attribute__((noreturn))") add(m.s[cfsProcHeaders], ropecg(m, "$1;$n", header)) proc genProcNoForward(m: BModule, prc: PSym) = if lfImportCompilerProc in prc.loc.flags: fillProcLoc(m, prc.ast[namePos]) useHeader(m, prc) # dependency to a compilerproc: discard cgsym(m, prc.name.s) return if lfNoDecl in prc.loc.flags: fillProcLoc(m, prc.ast[namePos]) useHeader(m, prc) genProcPrototype(m, prc) elif prc.typ.callConv == ccInline: # We add inline procs to the calling module to enable C based inlining. # This also means that a check with ``q.declaredThings`` is wrong, we need # a check for ``m.declaredThings``. if not containsOrIncl(m.declaredThings, prc.id): #if prc.loc.k == locNone: fillProcLoc(m, prc.ast[namePos]) #elif {sfExportc, sfImportc} * prc.flags == {}: # # reset name to restore consistency in case of hashing collisions: # echo "resetting ", prc.id, " by ", m.module.name.s # prc.loc.r = nil # prc.loc.r = mangleName(m, prc) useHeader(m, prc) genProcPrototype(m, prc) genProcAux(m, prc) elif lfDynamicLib in prc.loc.flags: var q = findPendingModule(m, prc) fillProcLoc(q, prc.ast[namePos]) useHeader(m, prc) genProcPrototype(m, prc) if q != nil and not containsOrIncl(q.declaredThings, prc.id): symInDynamicLib(q, prc) else: symInDynamicLibPartial(m, prc) elif sfImportc notin prc.flags: var q = findPendingModule(m, prc) fillProcLoc(q, prc.ast[namePos]) useHeader(m, prc) genProcPrototype(m, prc) if q != nil and not containsOrIncl(q.declaredThings, prc.id): genProcAux(q, prc) else: fillProcLoc(m, prc.ast[namePos]) useHeader(m, prc) if sfInfixCall notin prc.flags: genProcPrototype(m, prc) proc requestConstImpl(p: BProc, sym: PSym) = var m = p.module useHeader(m, sym) if sym.loc.k == locNone: fillLoc(sym.loc, locData, sym.ast, mangleName(p.module, sym), OnStatic) if lfNoDecl in sym.loc.flags: return # declare implementation: var q = findPendingModule(m, sym) if q != nil and not containsOrIncl(q.declaredThings, sym.id): assert q.initProc.module == q addf(q.s[cfsData], "NIM_CONST $1 $2 = $3;$n", [getTypeDesc(q, sym.typ), sym.loc.r, genConstExpr(q.initProc, sym.ast)]) # declare header: if q != m and not containsOrIncl(m.declaredThings, sym.id): assert(sym.loc.r != nil) let headerDecl = "extern NIM_CONST $1 $2;$n" % [getTypeDesc(m, sym.loc.t), sym.loc.r] add(m.s[cfsData], headerDecl) if sfExportc in sym.flags and p.module.g.generatedHeader != nil: add(p.module.g.generatedHeader.s[cfsData], headerDecl) proc isActivated(prc: PSym): bool = prc.typ != nil proc genProc(m: BModule, prc: PSym) = if sfBorrow in prc.flags or not isActivated(prc): return if sfForward in prc.flags: addForwardedProc(m, prc) fillProcLoc(m, prc.ast[namePos]) else: genProcNoForward(m, prc) if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and m.g.generatedHeader != nil and lfNoDecl notin prc.loc.flags: genProcPrototype(m.g.generatedHeader, prc) if prc.typ.callConv == ccInline: if not containsOrIncl(m.g.generatedHeader.declaredThings, prc.id): genProcAux(m.g.generatedHeader, prc) proc genVarPrototype(m: BModule, n: PNode) = #assert(sfGlobal in sym.flags) let sym = n.sym useHeader(m, sym) fillLoc(sym.loc, locGlobalVar, n, mangleName(m, sym), OnHeap) if (lfNoDecl in sym.loc.flags) or containsOrIncl(m.declaredThings, sym.id): return if sym.owner.id != m.module.id: # else we already have the symbol generated! assert(sym.loc.r != nil) if sfThread in sym.flags: declareThreadVar(m, sym, true) else: add(m.s[cfsVars], "extern ") add(m.s[cfsVars], getTypeDesc(m, sym.loc.t)) if lfDynamicLib in sym.loc.flags: add(m.s[cfsVars], "*") if sfRegister in sym.flags: add(m.s[cfsVars], " register") if sfVolatile in sym.flags: add(m.s[cfsVars], " volatile") addf(m.s[cfsVars], " $1;$n", [sym.loc.r]) proc addIntTypes(result: var Rope; conf: ConfigRef) {.inline.} = addf(result, "#define NIM_NEW_MANGLING_RULES\L" & "#define NIM_INTBITS $1\L", [ platform.CPU[conf.target.targetCPU].intSize.rope]) if optUseNimNamespace in conf.globalOptions: result.add("#define USE_NIM_NAMESPACE\L") proc getCopyright(conf: ConfigRef; cfile: Cfile): Rope = if optCompileOnly in conf.globalOptions: result = ("/* Generated by Nim Compiler v$1 */$N" & "/* (c) " & copyrightYear & " Andreas Rumpf */$N" & "/* The generated code is subject to the original license. */$N") % [rope(VersionAsString)] else: result = ("/* Generated by Nim Compiler v$1 */$N" & "/* (c) " & copyrightYear & " Andreas Rumpf */$N" & "/* The generated code is subject to the original license. */$N" & "/* Compiled for: $2, $3, $4 */$N" & "/* Command for C compiler:$n $5 */$N") % [rope(VersionAsString), rope(platform.OS[conf.target.targetOS].name), rope(platform.CPU[conf.target.targetCPU].name), rope(extccomp.CC[conf.cCompiler].name), rope(getCompileCFileCmd(conf, cfile))] proc getFileHeader(conf: ConfigRef; cfile: Cfile): Rope = result = getCopyright(conf, cfile) addIntTypes(result, conf) proc genFilenames(m: BModule): Rope = discard cgsym(m, "dbgRegisterFilename") result = nil for i in 0..<m.config.m.fileInfos.len: result.addf("dbgRegisterFilename($1);$N", [m.config.m.fileInfos[i].projPath.makeCString]) proc genMainProc(m: BModule) = const # The use of a volatile function pointer to call Pre/NimMainInner # prevents inlining of the NimMainInner function and dependent # functions, which might otherwise merge their stack frames. PreMainBody = "void PreMainInner(void) {$N" & "\tsystemInit000();$N" & "$1" & "$2" & "$3" & "}$N$N" & "void PreMain(void) {$N" & "\tvoid (*volatile inner)(void);$N" & "\tsystemDatInit000();$N" & "\tinner = PreMainInner;$N" & "$4$5" & "\t(*inner)();$N" & "}$N$N" MainProcs = "\tNimMain();$N" MainProcsWithResult = MainProcs & "\treturn nim_program_result;$N" NimMainInner = "N_CDECL(void, NimMainInner)(void) {$N" & "$1" & "}$N$N" NimMainProc = "N_CDECL(void, NimMain)(void) {$N" & "\tvoid (*volatile inner)(void);$N" & "\tPreMain();$N" & "\tinner = NimMainInner;$N" & "$2" & "\t(*inner)();$N" & "}$N$N" NimMainBody = NimMainInner & NimMainProc PosixNimMain = "int cmdCount;$N" & "char** cmdLine;$N" & "char** gEnv;$N" & NimMainBody PosixCMain = "int main(int argc, char** args, char** env) {$N" & "\tcmdLine = args;$N" & "\tcmdCount = argc;$N" & "\tgEnv = env;$N" & MainProcsWithResult & "}$N$N" StandaloneCMain = "int main(void) {$N" & MainProcs & "\treturn 0;$N" & "}$N$N" WinNimMain = NimMainBody WinCMain = "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N" & " HINSTANCE hPrevInstance, $N" & " LPSTR lpCmdLine, int nCmdShow) {$N" & MainProcsWithResult & "}$N$N" WinNimDllMain = NimMainInner & "N_LIB_EXPORT " & NimMainProc WinCDllMain = "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N" & " LPVOID lpvReserved) {$N" & "\tif(fwdreason == DLL_PROCESS_ATTACH) {$N" & MainProcs & "}$N" & "\treturn 1;$N}$N$N" PosixNimDllMain = WinNimDllMain PosixCDllMain = "void NIM_POSIX_INIT NimMainInit(void) {$N" & MainProcs & "}$N$N" GenodeNimMain = "Libc::Env *genodeEnv;$N" & NimMainBody ComponentConstruct = "void Libc::Component::construct(Libc::Env &env) {$N" & "\tgenodeEnv = &env;$N" & "\tLibc::with_libc([&] () {$N\t" & MainProcs & "\t});$N" & "}$N$N" var nimMain, otherMain: FormatStr if m.config.target.targetOS == osWindows and m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}: if optGenGuiApp in m.config.globalOptions: nimMain = WinNimMain otherMain = WinCMain else: nimMain = WinNimDllMain otherMain = WinCDllMain m.includeHeader("<windows.h>") elif m.config.target.targetOS == osGenode: nimMain = GenodeNimMain otherMain = ComponentConstruct elif optGenDynLib in m.config.globalOptions: nimMain = PosixNimDllMain otherMain = PosixCDllMain elif m.config.target.targetOS == osStandalone: nimMain = PosixNimMain otherMain = StandaloneCMain else: nimMain = PosixNimMain otherMain = PosixCMain if m.g.breakpoints != nil: discard cgsym(m, "dbgRegisterBreakpoint") if optEndb in m.config.options: m.g.breakpoints.add(m.genFilenames) let initStackBottomCall = if m.config.target.targetOS == osStandalone or m.config.selectedGC == gcNone: "".rope else: ropecg(m, "\t#initStackBottomWith((void *)&inner);$N") inc(m.labels) appcg(m, m.s[cfsProcs], PreMainBody, [ m.g.mainDatInit, m.g.breakpoints, m.g.otherModsInit, if emulatedThreadVars(m.config) and m.config.target.targetOS != osStandalone: ropecg(m, "\t#initThreadVarsEmulation();$N") else: "".rope, initStackBottomCall]) appcg(m, m.s[cfsProcs], nimMain, [m.g.mainModInit, initStackBottomCall, rope(m.labels)]) if optNoMain notin m.config.globalOptions: if optUseNimNamespace in m.config.globalOptions: m.s[cfsProcs].add closeNamespaceNim() & "using namespace Nim;\L" appcg(m, m.s[cfsProcs], otherMain, []) if optUseNimNamespace in m.config.globalOptions: m.s[cfsProcs].add openNamespaceNim() proc getSomeInitName(m: PSym, suffix: string): Rope = assert m.kind == skModule assert m.owner.kind == skPackage if {sfSystemModule, sfMainModule} * m.flags == {}: result = m.owner.name.s.mangle.rope result.add "_" result.add m.name.s result.add suffix proc getInitName(m: PSym): Rope = if sfMainModule in m.flags: # generate constant name for main module, for "easy" debugging. result = rope"NimMainModule" else: result = getSomeInitName(m, "Init000") proc getDatInitName(m: PSym): Rope = getSomeInitName(m, "DatInit000") proc registerModuleToMain(g: BModuleList; m: PSym) = var init = m.getInitName datInit = m.getDatInitName addf(g.mainModProcs, "N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [init]) addf(g.mainModProcs, "N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [datInit]) if sfSystemModule notin m.flags: addf(g.mainDatInit, "\t$1();$N", [datInit]) let initCall = "\t$1();$N" % [init] if sfMainModule in m.flags: add(g.mainModInit, initCall) else: add(g.otherModsInit, initCall) proc genInitCode(m: BModule) = var initname = getInitName(m.module) var prc = "N_LIB_PRIVATE N_NIMCALL(void, $1)(void) {$N" % [initname] if m.typeNodes > 0: appcg(m, m.s[cfsTypeInit1], "static #TNimNode $1[$2];$n", [m.typeNodesName, rope(m.typeNodes)]) if m.nimTypes > 0: appcg(m, m.s[cfsTypeInit1], "static #TNimType $1[$2];$n", [m.nimTypesName, rope(m.nimTypes)]) add(prc, initGCFrame(m.initProc)) add(prc, genSectionStart(cpsLocals, m.config)) add(prc, m.preInitProc.s(cpsLocals)) add(prc, m.initProc.s(cpsLocals)) add(prc, m.postInitProc.s(cpsLocals)) add(prc, genSectionEnd(cpsLocals, m.config)) if optStackTrace in m.initProc.options and frameDeclared notin m.flags: # BUT: the generated init code might depend on a current frame, so # declare it nevertheless: incl m.flags, frameDeclared if preventStackTrace notin m.flags: var procname = makeCString(m.module.name.s) add(prc, initFrame(m.initProc, procname, quotedFilename(m.config, m.module.info))) else: add(prc, ~"\tTFrame FR_; FR_.len = 0;$N") add(prc, genSectionStart(cpsInit, m.config)) add(prc, m.preInitProc.s(cpsInit)) add(prc, m.initProc.s(cpsInit)) add(prc, m.postInitProc.s(cpsInit)) add(prc, genSectionEnd(cpsInit, m.config)) add(prc, genSectionStart(cpsStmts, m.config)) add(prc, m.preInitProc.s(cpsStmts)) add(prc, m.initProc.s(cpsStmts)) add(prc, m.postInitProc.s(cpsStmts)) add(prc, genSectionEnd(cpsStmts, m.config)) if optStackTrace in m.initProc.options and preventStackTrace notin m.flags: add(prc, deinitFrame(m.initProc)) add(prc, deinitGCFrame(m.initProc)) addf(prc, "}$N$N", []) prc.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void) {$N", [getDatInitName(m.module)]) for i in cfsTypeInit1..cfsDynLibInit: add(prc, genSectionStart(i, m.config)) add(prc, m.s[i]) add(prc, genSectionEnd(i, m.config)) addf(prc, "}$N$N", []) # we cannot simply add the init proc to ``m.s[cfsProcs]`` anymore because # that would lead to a *nesting* of merge sections which the merger does # not support. So we add it to another special section: ``cfsInitProc`` add(m.s[cfsInitProc], prc) for i, el in pairs(m.extensionLoaders): if el != nil: let ex = "NIM_EXTERNC N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N" % [(i.ord - '0'.ord).rope, el] add(m.s[cfsInitProc], ex) proc genModule(m: BModule, cfile: Cfile): Rope = result = getFileHeader(m.config, cfile) result.add(genMergeInfo(m)) generateThreadLocalStorage(m) generateHeaders(m) for i in countup(cfsHeaders, cfsProcs): add(result, genSectionStart(i, m.config)) add(result, m.s[i]) add(result, genSectionEnd(i, m.config)) if optUseNimNamespace in m.config.globalOptions and i == cfsHeaders: result.add openNamespaceNim() add(result, m.s[cfsInitProc]) if optUseNimNamespace in m.config.globalOptions: result.add closeNamespaceNim() proc newPreInitProc(m: BModule): BProc = result = newProc(nil, m) # little hack so that unique temporaries are generated: result.labels = 100_000 proc newPostInitProc(m: BModule): BProc = result = newProc(nil, m) # little hack so that unique temporaries are generated: result.labels = 200_000 proc initProcOptions(m: BModule): TOptions = let opts = m.config.options if sfSystemModule in m.module.flags: opts-{optStackTrace} else: opts proc rawNewModule(g: BModuleList; module: PSym, filename: string): BModule = new(result) result.g = g result.tmpBase = rope("TM" & $hashOwner(module) & "_") result.headerFiles = @[] result.declaredThings = initIntSet() result.declaredProtos = initIntSet() result.cfilename = filename result.filename = filename result.typeCache = initTable[SigHash, Rope]() result.forwTypeCache = initTable[SigHash, Rope]() result.module = module result.typeInfoMarker = initTable[SigHash, Rope]() result.sigConflicts = initCountTable[SigHash]() result.initProc = newProc(nil, result) result.initProc.options = initProcOptions(result) result.preInitProc = newPreInitProc(result) result.postInitProc = newPostInitProc(result) initNodeTable(result.dataCache) result.typeStack = @[] result.forwardedProcs = @[] result.typeNodesName = getTempName(result) result.nimTypesName = getTempName(result) # no line tracing for the init sections of the system module so that we # don't generate a TFrame which can confuse the stack botton initialization: if sfSystemModule in module.flags: incl result.flags, preventStackTrace excl(result.preInitProc.options, optStackTrace) excl(result.postInitProc.options, optStackTrace) let ndiName = if optCDebug in g.config.globalOptions: changeFileExt(completeCFilePath(g.config, filename), "ndi") else: "" open(result.ndi, ndiName, g.config) proc nullify[T](arr: var T) = for i in low(arr)..high(arr): arr[i] = Rope(nil) proc resetModule*(m: BModule) = # between two compilations in CAAS mode, we can throw # away all the data that was written to disk m.headerFiles = @[] m.declaredProtos = initIntSet() m.forwTypeCache = initTable[SigHash, Rope]() m.initProc = newProc(nil, m) m.initProc.options = initProcOptions(m) m.preInitProc = newPreInitProc(m) m.postInitProc = newPostInitProc(m) initNodeTable(m.dataCache) m.typeStack = @[] m.forwardedProcs = @[] m.typeNodesName = getTempName(m) m.nimTypesName = getTempName(m) if sfSystemModule in m.module.flags: incl m.flags, preventStackTrace else: excl m.flags, preventStackTrace nullify m.s m.typeNodes = 0 m.nimTypes = 0 nullify m.extensionLoaders # indicate that this is now cached module # the cache will be invalidated by nullifying gModules #m.fromCache = true m.g = nil # we keep only the "merge info" information for the module # and the properties that can't change: # m.filename # m.cfilename # m.isHeaderFile # m.module ? # m.typeCache # m.declaredThings # m.typeInfoMarker # m.labels # m.FrameDeclared proc resetCgenModules*(g: BModuleList) = for m in cgenModules(g): resetModule(m) proc rawNewModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule = result = rawNewModule(g, module, toFullPath(conf, module.position.FileIndex)) proc newModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule = # we should create only one cgen module for each module sym result = rawNewModule(g, module, conf) if module.position >= g.modules.len: setLen(g.modules, module.position + 1) #growCache g.modules, module.position g.modules[module.position] = result template injectG() {.dirty.} = if graph.backend == nil: graph.backend = newModuleList(graph) let g = BModuleList(graph.backend) proc myOpen(graph: ModuleGraph; module: PSym; cache: IdentCache): PPassContext = injectG() result = newModule(g, module, graph.config) if optGenIndex in graph.config.globalOptions and g.generatedHeader == nil: let f = if graph.config.headerFile.len > 0: graph.config.headerFile else: graph.config.projectFull g.generatedHeader = rawNewModule(g, module, changeFileExt(completeCFilePath(graph.config, f), hExt)) incl g.generatedHeader.flags, isHeaderFile proc writeHeader(m: BModule) = var result = ("/* Generated by Nim Compiler v$1 */$N" & "/* (c) 2017 Andreas Rumpf */$N" & "/* The generated code is subject to the original license. */$N") % [rope(VersionAsString)] var guard = "__$1__" % [m.filename.splitFile.name.rope] result.addf("#ifndef $1$n#define $1$n", [guard]) addIntTypes(result, m.config) generateHeaders(m) generateThreadLocalStorage(m) for i in countup(cfsHeaders, cfsProcs): add(result, genSectionStart(i, m.config)) add(result, m.s[i]) add(result, genSectionEnd(i, m.config)) if optUseNimNamespace in m.config.globalOptions and i == cfsHeaders: result.add openNamespaceNim() add(result, m.s[cfsInitProc]) if optGenDynLib in m.config.globalOptions: result.add("N_LIB_IMPORT ") result.addf("N_CDECL(void, NimMain)(void);$n", []) if optUseNimNamespace in m.config.globalOptions: result.add closeNamespaceNim() result.addf("#endif /* $1 */$n", [guard]) if not writeRope(result, m.filename): rawMessage(m.config, errCannotOpenFile, m.filename) proc getCFile(m: BModule): string = let ext = if m.compileToCpp: ".cpp" elif m.config.cmd == cmdCompileToOC or sfCompileToObjC in m.module.flags: ".m" else: ".c" result = changeFileExt(completeCFilePath(m.config, withPackageName(m.config, m.cfilename)), ext) proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext = injectG() var m = newModule(g, module, graph.config) readMergeInfo(getCFile(m), m) result = m proc myProcess(b: PPassContext, n: PNode): PNode = result = n if b == nil: return var m = BModule(b) if passes.skipCodegen(m.config, n): return m.initProc.options = initProcOptions(m) #softRnl = if optLineDir in m.config.options: noRnl else: rnl # XXX replicate this logic! genStmts(m.initProc, n) proc finishModule(m: BModule) = var i = 0 while i <= high(m.forwardedProcs): # Note: ``genProc`` may add to ``m.forwardedProcs``, so we cannot use # a ``for`` loop here var prc = m.forwardedProcs[i] if sfForward in prc.flags: internalError(m.config, prc.info, "still forwarded: " & prc.name.s) genProcNoForward(m, prc) inc(i) assert(m.g.forwardedProcsCounter >= i) dec(m.g.forwardedProcsCounter, i) setLen(m.forwardedProcs, 0) proc shouldRecompile(m: BModule; code: Rope, cfile: Cfile): bool = result = true if optForceFullMake notin m.config.globalOptions: if not equalsFile(code, cfile.cname): if isDefined(m.config, "nimdiff"): if fileExists(cfile.cname): copyFile(cfile.cname, cfile.cname & ".backup") echo "diff ", cfile.cname, ".backup ", cfile.cname else: echo "new file ", cfile.cname if not writeRope(code, cfile.cname): rawMessage(m.config, errCannotOpenFile, cfile.cname) return if existsFile(cfile.obj) and os.fileNewer(cfile.obj, cfile.cname): result = false else: if not writeRope(code, cfile.cname): rawMessage(m.config, errCannotOpenFile, cfile.cname) # We need 2 different logics here: pending modules (including # 'nim__dat') may require file merging for the combination of dead code # elimination and incremental compilation! Non pending modules need no # such logic and in fact the logic hurts for the main module at least; # it would generate multiple 'main' procs, for instance. proc writeModule(m: BModule, pending: bool) = # generate code for the init statements of the module: let cfile = getCFile(m) if true or optForceFullMake in m.config.globalOptions: genInitCode(m) finishTypeDescriptions(m) if sfMainModule in m.module.flags: # generate main file: add(m.s[cfsProcHeaders], m.g.mainModProcs) generateThreadVarsSize(m) var cf = Cfile(cname: cfile, obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {}) var code = genModule(m, cf) when hasTinyCBackend: if conf.cmd == cmdRun: tccgen.compileCCode($code) return if not shouldRecompile(m, code, cf): cf.flags = {CfileFlag.Cached} addFileToCompile(m.config, cf) elif pending and mergeRequired(m) and sfMainModule notin m.module.flags: let cf = Cfile(cname: cfile, obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {}) mergeFiles(cfile, m) genInitCode(m) finishTypeDescriptions(m) var code = genModule(m, cf) if not writeRope(code, cfile): rawMessage(m.config, errCannotOpenFile, cfile) addFileToCompile(m.config, cf) else: # Consider: first compilation compiles ``system.nim`` and produces # ``system.c`` but then compilation fails due to an error. This means # that ``system.o`` is missing, so we need to call the C compiler for it: var cf = Cfile(cname: cfile, obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {}) if not existsFile(cf.obj): cf.flags = {CfileFlag.Cached} addFileToCompile(m.config, cf) close(m.ndi) proc updateCachedModule(m: BModule) = let cfile = getCFile(m) var cf = Cfile(cname: cfile, obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {}) if mergeRequired(m) and sfMainModule notin m.module.flags: mergeFiles(cfile, m) genInitCode(m) finishTypeDescriptions(m) var code = genModule(m, cf) if not writeRope(code, cfile): rawMessage(m.config, errCannotOpenFile, cfile) else: cf.flags = {CfileFlag.Cached} addFileToCompile(m.config, cf) proc myClose(graph: ModuleGraph; b: PPassContext, n: PNode): PNode = result = n if b == nil: return var m = BModule(b) if passes.skipCodegen(m.config, n): return # if the module is cached, we don't regenerate the main proc # nor the dispatchers? But if the dispatchers changed? # XXX emit the dispatchers into its own .c file? if n != nil: m.initProc.options = initProcOptions(m) genStmts(m.initProc, n) # cached modules need to registered too: registerModuleToMain(m.g, m.module) if sfMainModule in m.module.flags: if m.g.forwardedProcsCounter == 0: incl m.flags, objHasKidsValid let disp = generateMethodDispatchers(graph) for x in disp: genProcAux(m, x.sym) genMainProc(m) proc cgenWriteModules*(backend: RootRef, config: ConfigRef) = let g = BModuleList(backend) # we need to process the transitive closure because recursive module # deps are allowed (and the system module is processed in the wrong # order anyway) g.config = config if g.generatedHeader != nil: finishModule(g.generatedHeader) while g.forwardedProcsCounter > 0: for m in cgenModules(g): finishModule(m) for m in cgenModules(g): m.writeModule(pending=true) writeMapping(config, g.mapping) if g.generatedHeader != nil: writeHeader(g.generatedHeader) const cgenPass* = makePass(myOpen, myOpenCached, myProcess, myClose)