forked from Crimso777/Factorio-Access
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathsyntrax-cli.lua
More file actions
500 lines (442 loc) · 14.8 KB
/
syntrax-cli.lua
File metadata and controls
500 lines (442 loc) · 14.8 KB
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
#!/usr/bin/env lua
---@diagnostic disable
--[[
Syntrax CLI - Development and debugging tool for the Syntrax language
This is NOT part of the public API. It's a development utility that provides
access to internal modules for debugging and testing purposes.
Usage:
syntrax [options] [file]
syntrax [options] -c <code>
Options:
-h, --help Show this help message
-c <code> Compile and run code from command line
-o, --output <fmt> Output format: rails (default), bytecode, ast, all
-q, --quiet Quiet mode (only show output, no headers)
--version Show version information
--demo Run VM demo (shows direct bytecode creation)
--test Run the test suite
Examples:
syntrax program.syn # Run a file
syntrax -c "[l r] x 4" # Run code directly
syntrax -o bytecode file.syn # Show only bytecode
syntrax -o all -c "l r s" # Show all stages
syntrax --demo # Run VM demo
syntrax --test # Run test suite
]]
-- For the public API (not used directly in CLI)
-- For debugging features, we need internal modules
local Parser = require("syntrax.parser")
local Compiler = require("syntrax.compiler")
local Vm = require("syntrax.vm")
local Ast = require("syntrax.ast")
-- CLI argument parsing
local function parse_args(args)
local options = {
output = "rails",
quiet = false,
help = false,
version = false,
demo = false,
test = false,
code = nil,
file = nil,
}
local i = 1
while i <= #args do
local arg = args[i]
if arg == "-h" or arg == "--help" then
options.help = true
return options
elseif arg == "--version" then
options.version = true
return options
elseif arg == "--demo" then
options.demo = true
return options
elseif arg == "--test" then
options.test = true
return options
elseif arg == "-q" or arg == "--quiet" then
options.quiet = true
elseif arg == "-o" or arg == "--output" then
i = i + 1
if i > #args then return nil, "Option " .. arg .. " requires an argument" end
local fmt = args[i]
if fmt ~= "rails" and fmt ~= "bytecode" and fmt ~= "ast" and fmt ~= "all" then
return nil, "Invalid output format: " .. fmt
end
options.output = fmt
elseif arg == "-c" then
i = i + 1
if i > #args then return nil, "Option -c requires an argument" end
options.code = args[i]
elseif arg:sub(1, 1) == "-" then
return nil, "Unknown option: " .. arg
else
if options.file then return nil, "Multiple input files specified" end
options.file = arg
end
i = i + 1
end
-- Validate options
if options.code and options.file then return nil, "Cannot specify both -c and input file" end
if
not options.code
and not options.file
and not options.help
and not options.version
and not options.demo
and not options.test
then
return nil, "No input specified (use -c for code or provide a file)"
end
return options
end
local function show_help()
print([[
Syntrax CLI - Command line interface for the Syntrax language
Usage:
syntrax [options] [file]
syntrax [options] -c <code>
Options:
-h, --help Show this help message
-c <code> Compile and run code from command line
-o, --output <fmt> Output format: rails (default), bytecode, ast, all
-q, --quiet Quiet mode (only show output, no headers)
--version Show version information
--demo Run VM demo (shows direct bytecode creation)
--test Run the test suite
Examples:
syntrax program.syn # Run a file
syntrax -c "[l r] x 4" # Run code directly
syntrax -o bytecode file.syn # Show only bytecode
syntrax -o all -c "l r s" # Show all stages
syntrax --demo # Run VM demo
syntrax --test # Run test suite
]])
end
local function show_version()
print("Syntrax version 0.1.0")
print("A domain-specific language for Factorio train layouts")
end
-- Pretty print AST
local function print_ast(node, indent)
indent = indent or 0
local prefix = string.rep(" ", indent)
if node.type == Ast.NODE_TYPE.SEQUENCE then
print(prefix .. "sequence:")
if #node.statements == 0 then
print(prefix .. " (empty)")
else
for _, stmt in ipairs(node.statements) do
print_ast(stmt, indent + 1)
end
end
elseif node.type == Ast.NODE_TYPE.IMPLICIT_SEQUENCE then
print(prefix .. "implicit_sequence:")
if #node.statements == 0 then
print(prefix .. " (empty)")
else
for _, stmt in ipairs(node.statements) do
print_ast(stmt, indent + 1)
end
end
elseif node.type == Ast.NODE_TYPE.LEFT then
print(prefix .. "left")
elseif node.type == Ast.NODE_TYPE.RIGHT then
print(prefix .. "right")
elseif node.type == Ast.NODE_TYPE.STRAIGHT then
print(prefix .. "straight")
elseif node.type == Ast.NODE_TYPE.L45 then
print(prefix .. "l45")
elseif node.type == Ast.NODE_TYPE.R45 then
print(prefix .. "r45")
elseif node.type == Ast.NODE_TYPE.L90 then
print(prefix .. "l90")
elseif node.type == Ast.NODE_TYPE.R90 then
print(prefix .. "r90")
elseif node.type == Ast.NODE_TYPE.FLIP then
print(prefix .. "flip")
elseif node.type == Ast.NODE_TYPE.RPUSH then
print(prefix .. "rpush")
elseif node.type == Ast.NODE_TYPE.RPOP then
print(prefix .. "rpop")
elseif node.type == Ast.NODE_TYPE.RESET then
print(prefix .. "reset")
elseif node.type == Ast.NODE_TYPE.MARK then
print(prefix .. "mark")
elseif node.type == Ast.NODE_TYPE.SIGLEFT then
print(prefix .. "sigleft")
elseif node.type == Ast.NODE_TYPE.SIGRIGHT then
print(prefix .. "sigright")
elseif node.type == Ast.NODE_TYPE.CHAINLEFT then
print(prefix .. "chainleft")
elseif node.type == Ast.NODE_TYPE.CHAINRIGHT then
print(prefix .. "chainright")
elseif node.type == Ast.NODE_TYPE.SIG then
print(prefix .. "sig")
elseif node.type == Ast.NODE_TYPE.CHAIN then
print(prefix .. "chain")
elseif node.type == Ast.NODE_TYPE.SIGCHAIN then
print(prefix .. "sigchain")
elseif node.type == Ast.NODE_TYPE.CHAINSIG then
print(prefix .. "chainsig")
elseif node.type == Ast.NODE_TYPE.REPETITION then
print(prefix .. "repetition:")
print(prefix .. " count: " .. node.count)
print(prefix .. " body:")
print_ast(node.body, indent + 2)
else
print(prefix .. "unknown: " .. tostring(node.type))
end
end
-- Run VM demo
local function run_demo()
print("=== VM Demo: Creating a square using direct bytecode ===\n")
local vm = Vm.new()
-- Helper functions
local function bc(...)
return Vm.bytecode(...)
end
local function val(n)
return Vm.value(Vm.VALUE_TYPE.NUMBER, n)
end
local function reg(n)
return Vm.register(n)
end
-- Create bytecode for a square
vm.bytecode = {
-- r1 = 4 (number of sides)
bc(Vm.BYTECODE_KIND.MOV, reg(1), val(4)),
-- loop: draw one side
bc(Vm.BYTECODE_KIND.STRAIGHT),
bc(Vm.BYTECODE_KIND.STRAIGHT),
bc(Vm.BYTECODE_KIND.STRAIGHT),
bc(Vm.BYTECODE_KIND.STRAIGHT),
-- Turn right (90 degrees = 4 units)
bc(Vm.BYTECODE_KIND.RIGHT),
bc(Vm.BYTECODE_KIND.RIGHT),
bc(Vm.BYTECODE_KIND.RIGHT),
bc(Vm.BYTECODE_KIND.RIGHT),
-- r1 = r1 - 1
bc(Vm.BYTECODE_KIND.MATH, reg(1), reg(1), val(1), Vm.math_op(Vm.MATH_OP.SUB)),
-- If r1 != 0, jump back to start of loop (offset -9)
bc(Vm.BYTECODE_KIND.JNZ, reg(1), val(-9)),
}
-- Print the bytecode
print("Bytecode listing:")
local labels = {
[2] = "loop",
[11] = "end",
}
for i, instr in ipairs(vm.bytecode) do
print(string.format("%2d: %s", i, Vm.format_bytecode(instr, i, labels)))
end
-- Execute
print("\nExecuting...")
local rails, err = vm:run()
if err then
print("\nRuntime error: " .. err.message)
return
end
assert(rails)
-- Print results with new format
print(string.format("\nGenerated %d placement groups:", #rails))
local placement_num = 0
for _, group in ipairs(rails) do
local first_alt = group[1]
for _, placement in ipairs(first_alt) do
placement_num = placement_num + 1
if placement.type == "rail" then
print(
string.format(
" Rail %d: %s at (%d, %d) dir=%d",
placement_num,
placement.rail_type,
placement.position.x,
placement.position.y,
placement.placement_direction
)
)
end
end
end
-- Summary by type
local type_counts = {}
for _, group in ipairs(rails) do
local first_alt = group[1]
for _, placement in ipairs(first_alt) do
if placement.type == "rail" then
type_counts[placement.rail_type] = (type_counts[placement.rail_type] or 0) + 1
end
end
end
print("\nSummary by rail type:")
for rail_type, count in pairs(type_counts) do
print(string.format(" %s: %d", rail_type, count))
end
end
-- Run test suite
local function run_tests()
print("=== Running Syntrax Test Suite ===\n")
-- Load test runner
local lu = require("luaunit")
-- Load all test modules
local tests = {
{ "span", require("syntrax.tests.span") },
{ "lexer", require("syntrax.tests.lexer") },
{ "ast", require("syntrax.tests.ast") },
{ "parser", require("syntrax.tests.parser") },
{ "directions", require("syntrax.tests.directions") },
{ "vm", require("syntrax.tests.vm") },
{ "compiler", require("syntrax.tests.compiler") },
{ "syntrax", require("syntrax.tests.syntrax") },
{ "syntax", require("syntrax.tests.syntax") },
{ "rail-stack", require("syntrax.tests.rail-stack") },
}
-- Run tests
local runner = lu.LuaUnit.new()
runner:setOutputType("text")
return runner:runSuiteByInstances(tests)
end
-- Main execution
local function main(args)
-- Parse arguments
local options, err = parse_args(args)
if not options then
io.stderr:write("Error: " .. err .. "\n")
io.stderr:write("Use -h for help\n")
os.exit(1)
end
-- Handle help and version
if options.help then
show_help()
os.exit(0)
end
if options.version then
show_version()
os.exit(0)
end
-- Handle demo mode
if options.demo then
run_demo()
os.exit(0)
end
-- Handle test mode
if options.test then
local exit_code = run_tests()
os.exit(exit_code)
end
-- Get input
local input
if options.code then
input = options.code
else
local file = io.open(options.file, "r")
if not file then
io.stderr:write("Error: Could not open file '" .. options.file .. "'\n")
os.exit(1)
end
input = file:read("*a")
file:close()
end
-- Parse
local ast, parse_err = Parser.parse(input)
if parse_err then
io.stderr:write("Parse error: " .. parse_err.message .. "\n")
if parse_err.span then
local l1, c1 = parse_err.span:get_printable_range()
io.stderr:write(string.format(" at line %d, column %d\n", l1, c1))
end
os.exit(1)
end
assert(ast, "Parser returned nil AST without error")
-- Show AST if requested
if options.output == "ast" or options.output == "all" then
if not options.quiet then print("=== Abstract Syntax Tree ===") end
print_ast(ast)
if options.output == "ast" then os.exit(0) end
if not options.quiet and options.output == "all" then print() end
end
-- Compile
local bytecode = Compiler.compile(ast)
-- Show bytecode if requested
if options.output == "bytecode" or options.output == "all" then
if not options.quiet then print("=== Bytecode ===") end
print(Compiler.format_bytecode_listing(bytecode))
if options.output == "bytecode" then os.exit(0) end
if not options.quiet and options.output == "all" then print() end
end
-- Execute
local vm = Vm.new()
vm.bytecode = bytecode
local rails, runtime_err = vm:run()
if runtime_err then
io.stderr:write("Runtime error: " .. runtime_err.message .. "\n")
if runtime_err.span then
local l1, c1 = runtime_err.span:get_printable_range()
io.stderr:write(string.format(" at line %d, column %d\n", l1, c1))
end
os.exit(1)
end
assert(rails)
-- Show rails output
-- rails is now PlacementGroup[] where each group is alternatives (Placement[][])
if options.output == "rails" or options.output == "all" then
if not options.quiet then
print("=== Placements Output ===")
print(string.format("Generated %d placement groups:", #rails))
end
local placement_num = 0
for _, group in ipairs(rails) do
-- Each group contains alternatives; show first alternative
local first_alt = group[1]
for _, placement in ipairs(first_alt) do
placement_num = placement_num + 1
if placement.type == "rail" then
print(
string.format(
"Rail %d: %s at (%d, %d) dir=%d",
placement_num,
placement.rail_type,
placement.position.x,
placement.position.y,
placement.placement_direction
)
)
elseif placement.type == "signal" then
local alt_count = #group
local alt_info = alt_count > 1 and string.format(" (%d alternatives)", alt_count) or ""
print(
string.format(
"Signal %d: %s at (%d, %d) dir=%d%s",
placement_num,
placement.signal_type,
placement.position.x,
placement.position.y,
placement.direction,
alt_info
)
)
end
end
end
if not options.quiet then
-- Summary by type
local type_counts = {}
for _, group in ipairs(rails) do
local first_alt = group[1]
for _, placement in ipairs(first_alt) do
local key = placement.type == "rail" and placement.rail_type or placement.signal_type
type_counts[key] = (type_counts[key] or 0) + 1
end
end
print("\nSummary by type:")
for item_type, count in pairs(type_counts) do
print(string.format(" %s: %d", item_type, count))
end
end
end
end
-- Run main with command line arguments
main(arg or {})