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
|
#
#
# The Nim Compiler
# (c) Copyright 2015 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
# This module handles the parsing of command line arguments.
# We do this here before the 'import' statement so 'defined' does not get
# confused with 'TGCMode.gcGenerational' etc.
template bootSwitch(name, expr, userString: expr): expr =
# Helper to build boot constants, for debugging you can 'echo' the else part.
const name = if expr: " " & userString else: ""
bootSwitch(usedRelease, defined(release), "-d:release")
bootSwitch(usedGnuReadline, defined(useGnuReadline), "-d:useGnuReadline")
bootSwitch(usedNoCaas, defined(noCaas), "-d:noCaas")
bootSwitch(usedBoehm, defined(boehmgc), "--gc:boehm")
bootSwitch(usedMarkAndSweep, defined(gcmarkandsweep), "--gc:markAndSweep")
bootSwitch(usedGenerational, defined(gcgenerational), "--gc:generational")
bootSwitch(usedNoGC, defined(nogc), "--gc:none")
import
os, msgs, options, nversion, condsyms, strutils, extccomp, platform, lists,
wordrecg, parseutils, nimblecmd, idents, parseopt
# but some have deps to imported modules. Yay.
bootSwitch(usedTinyC, hasTinyCBackend, "-d:tinyc")
bootSwitch(usedAvoidTimeMachine, noTimeMachine, "-d:avoidTimeMachine")
bootSwitch(usedNativeStacktrace,
defined(nativeStackTrace) and nativeStackTraceSupported,
"-d:nativeStackTrace")
bootSwitch(usedFFI, hasFFI, "-d:useFFI")
proc writeCommandLineUsage*()
type
TCmdLinePass* = enum
passCmd1, # first pass over the command line
passCmd2, # second pass over the command line
passPP # preprocessor called processCommand()
proc processCommand*(switch: string, pass: TCmdLinePass)
proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo)
# implementation
const
HelpMessage = "Nim Compiler Version $1 (" & CompileDate & ") [$2: $3]\n" &
"Copyright (c) 2006-2015 by Andreas Rumpf\n"
const
Usage = slurp"doc/basicopt.txt".replace("//", "")
AdvancedUsage = slurp"doc/advopt.txt".replace("//", "")
proc getCommandLineDesc(): string =
result = (HelpMessage % [VersionAsString, platform.OS[platform.hostOS].name,
CPU[platform.hostCPU].name]) & Usage
proc helpOnError(pass: TCmdLinePass) =
if pass == passCmd1:
msgWriteln(getCommandLineDesc())
msgQuit(0)
proc writeAdvancedUsage(pass: TCmdLinePass) =
if pass == passCmd1:
msgWriteln(`%`(HelpMessage, [VersionAsString,
platform.OS[platform.hostOS].name,
CPU[platform.hostCPU].name]) & AdvancedUsage)
msgQuit(0)
proc writeVersionInfo(pass: TCmdLinePass) =
if pass == passCmd1:
msgWriteln(`%`(HelpMessage, [VersionAsString,
platform.OS[platform.hostOS].name,
CPU[platform.hostCPU].name]))
discard """const gitHash = gorge("git log -n 1 --format=%H")
if gitHash.strip.len == 40:
msgWriteln("git hash: " & gitHash)"""
msgWriteln("active boot switches:" & usedRelease & usedAvoidTimeMachine &
usedTinyC & usedGnuReadline & usedNativeStacktrace & usedNoCaas &
usedFFI & usedBoehm & usedMarkAndSweep & usedGenerational & usedNoGC)
msgQuit(0)
var
helpWritten: bool
proc writeCommandLineUsage() =
if not helpWritten:
msgWriteln(getCommandLineDesc())
helpWritten = true
proc addPrefix(switch: string): string =
if len(switch) == 1: result = "-" & switch
else: result = "--" & switch
proc invalidCmdLineOption(pass: TCmdLinePass, switch: string, info: TLineInfo) =
if switch == " ": localError(info, errInvalidCmdLineOption, "-")
else: localError(info, errInvalidCmdLineOption, addPrefix(switch))
proc splitSwitch(switch: string, cmd, arg: var string, pass: TCmdLinePass,
info: TLineInfo) =
cmd = ""
var i = 0
if i < len(switch) and switch[i] == '-': inc(i)
if i < len(switch) and switch[i] == '-': inc(i)
while i < len(switch):
case switch[i]
of 'a'..'z', 'A'..'Z', '0'..'9', '_', '.': add(cmd, switch[i])
else: break
inc(i)
if i >= len(switch): arg = ""
elif switch[i] in {':', '=', '['}: arg = substr(switch, i + 1)
else: invalidCmdLineOption(pass, switch, info)
proc processOnOffSwitch(op: TOptions, arg: string, pass: TCmdLinePass,
info: TLineInfo) =
case whichKeyword(arg)
of wOn: gOptions = gOptions + op
of wOff: gOptions = gOptions - op
else: localError(info, errOnOrOffExpectedButXFound, arg)
proc processOnOffSwitchG(op: TGlobalOptions, arg: string, pass: TCmdLinePass,
info: TLineInfo) =
case whichKeyword(arg)
of wOn: gGlobalOptions = gGlobalOptions + op
of wOff: gGlobalOptions = gGlobalOptions - op
else: localError(info, errOnOrOffExpectedButXFound, arg)
proc expectArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
if arg == "": localError(info, errCmdLineArgExpected, addPrefix(switch))
proc expectNoArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
if arg != "": localError(info, errCmdLineNoArgExpected, addPrefix(switch))
proc processSpecificNote(arg: string, state: TSpecialWord, pass: TCmdLinePass,
info: TLineInfo; orig: string) =
var id = "" # arg = "X]:on|off"
var i = 0
var n = hintMin
while i < len(arg) and (arg[i] != ']'):
add(id, arg[i])
inc(i)
if i < len(arg) and (arg[i] == ']'): inc(i)
else: invalidCmdLineOption(pass, orig, info)
if i < len(arg) and (arg[i] in {':', '='}): inc(i)
else: invalidCmdLineOption(pass, orig, info)
if state == wHint:
var x = findStr(msgs.HintsToStr, id)
if x >= 0: n = TNoteKind(x + ord(hintMin))
else: localError(info, "unknown hint: " & id)
else:
var x = findStr(msgs.WarningsToStr, id)
if x >= 0: n = TNoteKind(x + ord(warnMin))
else: localError(info, "unknown warning: " & id)
case whichKeyword(substr(arg, i))
of wOn: incl(gNotes, n)
of wOff: excl(gNotes, n)
else: localError(info, errOnOrOffExpectedButXFound, arg)
proc processCompile(filename: string) =
var found = findFile(filename)
if found == "": found = filename
var trunc = changeFileExt(found, "")
extccomp.addExternalFileToCompile(found)
extccomp.addFileToLink(completeCFilePath(trunc, false))
proc testCompileOptionArg*(switch, arg: string, info: TLineInfo): bool =
case switch.normalize
of "gc":
case arg.normalize
of "boehm": result = gSelectedGC == gcBoehm
of "refc": result = gSelectedGC == gcRefc
of "v2": result = gSelectedGC == gcV2
of "markandsweep": result = gSelectedGC == gcMarkAndSweep
of "generational": result = gSelectedGC == gcGenerational
of "none": result = gSelectedGC == gcNone
else: localError(info, errNoneBoehmRefcExpectedButXFound, arg)
of "opt":
case arg.normalize
of "speed": result = contains(gOptions, optOptimizeSpeed)
of "size": result = contains(gOptions, optOptimizeSize)
of "none": result = gOptions * {optOptimizeSpeed, optOptimizeSize} == {}
else: localError(info, errNoneSpeedOrSizeExpectedButXFound, arg)
else: invalidCmdLineOption(passCmd1, switch, info)
proc testCompileOption*(switch: string, info: TLineInfo): bool =
case switch.normalize
of "debuginfo": result = contains(gGlobalOptions, optCDebug)
of "compileonly", "c": result = contains(gGlobalOptions, optCompileOnly)
of "nolinking": result = contains(gGlobalOptions, optNoLinking)
of "nomain": result = contains(gGlobalOptions, optNoMain)
of "forcebuild", "f": result = contains(gGlobalOptions, optForceFullMake)
of "warnings", "w": result = contains(gOptions, optWarns)
of "hints": result = contains(gOptions, optHints)
of "threadanalysis": result = contains(gGlobalOptions, optThreadAnalysis)
of "stacktrace": result = contains(gOptions, optStackTrace)
of "linetrace": result = contains(gOptions, optLineTrace)
of "debugger": result = contains(gOptions, optEndb)
of "profiler": result = contains(gOptions, optProfiler)
of "checks", "x": result = gOptions * ChecksOptions == ChecksOptions
of "floatchecks":
result = gOptions * {optNaNCheck, optInfCheck} == {optNaNCheck, optInfCheck}
of "infchecks": result = contains(gOptions, optInfCheck)
of "nanchecks": result = contains(gOptions, optNaNCheck)
of "objchecks": result = contains(gOptions, optObjCheck)
of "fieldchecks": result = contains(gOptions, optFieldCheck)
of "rangechecks": result = contains(gOptions, optRangeCheck)
of "boundchecks": result = contains(gOptions, optBoundsCheck)
of "overflowchecks": result = contains(gOptions, optOverflowCheck)
of "linedir": result = contains(gOptions, optLineDir)
of "assertions", "a": result = contains(gOptions, optAssert)
of "deadcodeelim": result = contains(gGlobalOptions, optDeadCodeElim)
of "run", "r": result = contains(gGlobalOptions, optRun)
of "symbolfiles": result = contains(gGlobalOptions, optSymbolFiles)
of "genscript": result = contains(gGlobalOptions, optGenScript)
of "threads": result = contains(gGlobalOptions, optThreads)
of "taintmode": result = contains(gGlobalOptions, optTaintMode)
of "tlsemulation": result = contains(gGlobalOptions, optTlsEmulation)
of "implicitstatic": result = contains(gOptions, optImplicitStatic)
of "patterns": result = contains(gOptions, optPatterns)
of "experimental": result = gExperimentalMode
else: invalidCmdLineOption(passCmd1, switch, info)
proc processPath(path: string, notRelativeToProj = false): string =
let p = if notRelativeToProj or os.isAbsolute(path) or
'$' in path or path[0] == '.':
path
else:
options.gProjectPath / path
result = unixToNativePath(p % ["nimrod", getPrefixDir(),
"nim", getPrefixDir(),
"lib", libpath,
"home", removeTrailingDirSep(os.getHomeDir()),
"projectname", options.gProjectName,
"projectpath", options.gProjectPath])
proc trackDirty(arg: string, info: TLineInfo) =
var a = arg.split(',')
if a.len != 4: localError(info, errTokenExpected,
"DIRTY_BUFFER,ORIGINAL_FILE,LINE,COLUMN")
var line, column: int
if parseUtils.parseInt(a[2], line) <= 0:
localError(info, errInvalidNumber, a[1])
if parseUtils.parseInt(a[3], column) <= 0:
localError(info, errInvalidNumber, a[2])
let dirtyOriginalIdx = a[1].fileInfoIdx
if dirtyOriginalIdx >= 0:
msgs.setDirtyFile(dirtyOriginalIdx, a[0])
gTrackPos = newLineInfo(dirtyOriginalIdx, line, column)
proc track(arg: string, info: TLineInfo) =
var a = arg.split(',')
if a.len != 3: localError(info, errTokenExpected, "FILE,LINE,COLUMN")
var line, column: int
if parseUtils.parseInt(a[1], line) <= 0:
localError(info, errInvalidNumber, a[1])
if parseUtils.parseInt(a[2], column) <= 0:
localError(info, errInvalidNumber, a[2])
gTrackPos = newLineInfo(a[0], line, column)
proc dynlibOverride(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
if pass in {passCmd2, passPP}:
expectArg(switch, arg, pass, info)
options.inclDynlibOverride(arg)
proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
var
theOS: TSystemOS
cpu: TSystemCPU
key, val: string
case switch.normalize
of "path", "p":
expectArg(switch, arg, pass, info)
addPath(processPath(arg), info)
of "nimblepath", "babelpath":
# keep the old name for compat
if pass in {passCmd2, passPP} and not options.gNoNimblePath:
expectArg(switch, arg, pass, info)
let path = processPath(arg, notRelativeToProj=true)
nimblePath(path, info)
of "nonimblepath", "nobabelpath":
expectNoArg(switch, arg, pass, info)
options.gNoNimblePath = true
of "excludepath":
expectArg(switch, arg, pass, info)
let path = processPath(arg)
lists.excludePath(options.searchPaths, path)
lists.excludePath(options.lazyPaths, path)
if (len(path) > 0) and (path[len(path) - 1] == DirSep):
let strippedPath = path[0 .. (len(path) - 2)]
lists.excludePath(options.searchPaths, strippedPath)
lists.excludePath(options.lazyPaths, strippedPath)
of "nimcache":
expectArg(switch, arg, pass, info)
options.nimcacheDir = processPath(arg)
of "out", "o":
expectArg(switch, arg, pass, info)
options.outFile = arg
of "docseesrcurl":
expectArg(switch, arg, pass, info)
options.docSeeSrcUrl = arg
of "mainmodule", "m":
discard "allow for backwards compatibility, but don't do anything"
of "define", "d":
expectArg(switch, arg, pass, info)
defineSymbol(arg)
of "undef", "u":
expectArg(switch, arg, pass, info)
undefSymbol(arg)
of "symbol":
expectArg(switch, arg, pass, info)
declareSymbol(arg)
of "compile":
expectArg(switch, arg, pass, info)
if pass in {passCmd2, passPP}: processCompile(arg)
of "link":
expectArg(switch, arg, pass, info)
if pass in {passCmd2, passPP}: addFileToLink(arg)
of "debuginfo":
expectNoArg(switch, arg, pass, info)
incl(gGlobalOptions, optCDebug)
of "embedsrc":
expectNoArg(switch, arg, pass, info)
incl(gGlobalOptions,pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long *///: A big convenience high-level languages provide is the ability to name memory
//: locations. In mu, a transform called 'transform_names' provides this
//: convenience.
:(scenario transform_names)
def main [
x:number <- copy 0
]
+name: assign x 1
+mem: storing 0 in location 1
:(scenarios transform)
:(scenario transform_names_fails_on_use_before_define)
% Hide_errors = true;
def main [
x:number <- copy y:number
]
+error: main: use before set: y
# todo: detect conditional defines
:(after "Transform.push_back(compute_container_metadata)") // we need sizes for all types
Transform.push_back(transform_names); // idempotent
:(before "End Globals")
map<recipe_ordinal, map<string, int> > Name;
//: the Name map is a global, so save it before tests and reset it for every
//: test, just to be safe.
:(before "End Globals")
map<recipe_ordinal, map<string, int> > Name_snapshot;
:(before "End save_snapshots")
Name_snapshot = Name;
:(before "End restore_snapshots")
Name = Name_snapshot;
:(code)
void transform_names(const recipe_ordinal r) {
recipe& caller = get(Recipe, r);
trace(9991, "transform") << "--- transform names for recipe " << caller.name << end();
//? cerr << "--- transform names for recipe " << caller.name << '\n';
bool names_used = false;
bool numeric_locations_used = false;
map<string, int>& names = Name[r];
// store the indices 'used' so far in the map
int& curr_idx = names[""];
++curr_idx; // avoid using index 0, benign skip in some other cases
for (int i = 0; i < SIZE(caller.steps); ++i) {
instruction& inst = caller.steps.at(i);
// End transform_names(inst) Special-cases
// map names to addresses
for (int in = 0; in < SIZE(inst.ingredients); ++in) {
if (is_disqualified(inst.ingredients.at(in), inst, caller.name)) continue;
if (is_numeric_location(inst.ingredients.at(in))) numeric_locations_used = true;
if (is_named_location(inst.ingredients.at(in))) names_used = true;
if (is_integer(inst.ingredients.at(in).name)) continue;
if (!already_transformed(inst.ingredients.at(in), names)) {
raise << maybe(caller.name) << "use before set: " << inst.ingredients.at(in).name << '\n' << end();
}
int v = lookup_name(inst.ingredients.at(in), r);
if (v >= 0) {
inst.ingredients.at(in).set_value(v);
}
else {
raise << maybe(caller.name) << "can't find a place to store " << inst.ingredients.at(in).name << '\n' << end();
return;
}
}
for (int out = 0; out < SIZE(inst.products); ++out) {
if (is_disqualified(inst.products.at(out), inst, caller.name)) continue;
if (is_numeric_location(inst.products.at(out))) numeric_locations_used = true;
if (is_named_location(inst.products.at(out))) names_used = true;
if (is_integer(inst.products.at(out).name)) continue;
if (names.find(inst.products.at(out).name) == names.end()) {
trace(9993, "name") << "assign " << inst.products.at(out).name << " " << curr_idx << end();
names[inst.products.at(out).name] = curr_idx;
curr_idx += size_of(inst.products.at(out));
}
int v = lookup_name(inst.products.at(out), r);
if (v >= 0) {
inst.products.at(out).set_value(v);
}
else {
raise << maybe(caller.name) << "can't find a place to store " << inst.products.at(out).name << '\n' << end();
return;
}
}
}
if (names_used && numeric_locations_used)
raise << maybe(caller.name) << "mixing variable names and numeric addresses\n" << end();
}
bool is_disqualified(/*mutable*/ reagent& x, const instruction& inst, const string& recipe_name) {
if (!x.type) {
// End Null-type is_disqualified Exceptions
raise << maybe(recipe_name) << "missing type for " << x.original_string << " in '" << to_original_string(inst) << "'\n" << end();
return true;
}
if (is_raw(x)) return true;
if (is_literal(x)) return true;
// End is_disqualified Cases
if (x.initialized) return true;
return false;
}
bool already_transformed(const reagent& r, const map<string, int>& names) {
return contains_key(names, r.name);
}
int lookup_name(const reagent& r, const recipe_ordinal default_recipe) {
return Name[default_recipe][r.name];
}
type_ordinal skip_addresses(type_tree* type) {
type_ordinal address = get(Type_ordinal, "address");
for (; type; type = type->right) {
if (type->value != address)
return type->value;
}
return -1;
}
int find_element_name(const type_ordinal t, const string& name, const string& recipe_name) {
const type_info& container = get(Type, t);
for (int i = 0; i < SIZE(container.elements); ++i)
if (container.elements.at(i).name == name) return i;
raise << maybe(recipe_name) << "unknown element " << name << " in container " << get(Type, t).name << '\n' << end();
return -1;
}
bool is_numeric_location(const reagent& x) {
if (is_literal(x)) return false;
if (is_raw(x)) return false;
if (x.name == "0") return false; // used for chaining lexical scopes
return is_integer(x.name);
}
bool is_named_location(const reagent& x) {
if (is_literal(x)) return false;
if (is_raw(x)) return false;
if (is_special_name(x.name)) return false;
return !is_integer(x.name);
}
bool is_special_name(const string& s) {
if (s == "_") return true;
if (s == "0") return true;
// End is_special_name Cases
return false;
}
:(scenario transform_names_supports_containers)
def main [
x:point <- merge 34, 35
y:number <- copy 3
]
+name: assign x 1
# skip location 2 because x occupies two locations
+name: assign y 3
:(scenario transform_names_supports_static_arrays)
def main [
x:array:number:3 <- create-array
y:number <- copy 3
]
+name: assign x 1
# skip locations 2, 3, 4 because x occupies four locations
+name: assign y 5
:(scenario transform_names_passes_dummy)
# _ is just a dummy result that never gets consumed
def main [
_, x:number <- copy 0, 1
]
+name: assign x 1
-name: assign _ 1
//: an escape hatch to suppress name conversion that we'll use later
:(scenarios run)
:(scenario transform_names_passes_raw)
% Hide_errors = true;
def main [
x:number/raw <- copy 0
]
-name: assign x 1
+error: can't write to location 0 in 'x:number/raw <- copy 0'
:(scenarios transform)
:(scenario transform_names_fails_when_mixing_names_and_numeric_locations)
% Hide_errors = true;
def main [
x:number <- copy 1:number
]
+error: main: mixing variable names and numeric addresses
:(scenario transform_names_fails_when_mixing_names_and_numeric_locations_2)
% Hide_errors = true;
def main [
x:number <- copy 1
1:number <- copy x:number
]
+error: main: mixing variable names and numeric addresses
:(scenario transform_names_does_not_fail_when_mixing_names_and_raw_locations)
def main [
x:number <- copy 1:number/raw
]
-error: main: mixing variable names and numeric addresses
$error: 0
:(scenario transform_names_does_not_fail_when_mixing_names_and_literals)
def main [
x:number <- copy 1
]
-error: main: mixing variable names and numeric addresses
$error: 0
//:: Support element names for containers in 'get' and 'get-location' and 'put'.
//: (get-location is implemented later)
:(scenario transform_names_transforms_container_elements)
def main [
p:address:point <- copy 0
a:number <- get *p:address:point, y:offset
b:number <- get *p:address:point, x:offset
]
+name: element y of type point is at offset 1
+name: element x of type point is at offset 0
:(before "End transform_names(inst) Special-cases")
// replace element names of containers with offsets
if (inst.name == "get" || inst.name == "get-location" || inst.name == "put") {
//: avoid raising any errors here; later layers will support overloading new
//: instructions with the same names (static dispatch), which could lead to
//: spurious errors
if (SIZE(inst.ingredients) < 2)
break; // error raised elsewhere
if (!is_literal(inst.ingredients.at(1)))
break; // error raised elsewhere
if (inst.ingredients.at(1).name.find_first_not_of("0123456789") != string::npos) {
// since first non-address in base type must be a container, we don't have to canonize
type_ordinal base_type = skip_addresses(inst.ingredients.at(0).type);
if (base_type == -1)
break; // error raised elsewhere
if (contains_key(Type, base_type)) { // otherwise we'll raise an error elsewhere
inst.ingredients.at(1).set_value(find_element_name(base_type, inst.ingredients.at(1).name, get(Recipe, r).name));
trace(9993, "name") << "element " << inst.ingredients.at(1).name << " of type " << get(Type, base_type).name << " is at offset " << no_scientific(inst.ingredients.at(1).value) << end();
}
}
}
//: this test is actually illegal so can't call run
:(scenarios transform)
:(scenario transform_names_handles_containers)
def main [
a:point <- copy 0/unsafe
b:number <- copy 0/unsafe
]
+name: assign a 1
+name: assign b 3
//:: Support variant names for exclusive containers in 'maybe-convert'.
:(scenarios run)
:(scenario transform_names_handles_exclusive_containers)
def main [
12:number <- copy 1
13:number <- copy 35
14:number <- copy 36
20:point, 22:boolean <- maybe-convert 12:number-or-point/unsafe, p:variant
]
+name: variant p of type number-or-point has tag 1
+mem: storing 35 in location 20
+mem: storing 36 in location 21
+mem: storing 1 in location 22
:(before "End transform_names(inst) Special-cases")
// convert variant names of exclusive containers
if (inst.name == "maybe-convert") {
if (SIZE(inst.ingredients) != 2) {
raise << maybe(get(Recipe, r).name) << "exactly 2 ingredients expected in '" << to_original_string(inst) << "'\n" << end();
break;
}
assert(is_literal(inst.ingredients.at(1)));
if (inst.ingredients.at(1).name.find_first_not_of("0123456789") != string::npos) {
// since first non-address in base type must be an exclusive container, we don't have to canonize
type_ordinal base_type = skip_addresses(inst.ingredients.at(0).type);
if (base_type == -1)
raise << maybe(get(Recipe, r).name) << "expected an exclusive-container in '" << to_original_string(inst) << "'\n" << end();
if (contains_key(Type, base_type)) { // otherwise we'll raise an error elsewhere
inst.ingredients.at(1).set_value(find_element_name(base_type, inst.ingredients.at(1).name, get(Recipe, r).name));
trace(9993, "name") << "variant " << inst.ingredients.at(1).name << " of type " << get(Type, base_type).name << " has tag " << no_scientific(inst.ingredients.at(1).value) << end();
}
}
}
|