CLIte/clite/build.js
2025-09-02 19:38:13 +10:00

142 lines
2.9 KiB
JavaScript

clite.commands.data = function() {
// insert commands below this line
clite.commands.load('cc',function(args,env,io) {
var stdlib = io.include('stdlib');
var stdio = io.include('stdio');
var time = io.include('time');
var clite = io.include('clite');
var ifiles = [];
var ofile = null;
var link = true;
var includes = [];
var code = [];
function help() {
stdio.printf(`
cc - code compiler
Usage: ls [OPTIONS] <FILE>
Options:
-? Print this help information
-o <FILE> Output to <FILE>
-c Compile but do not link
`);
}
function compile(file) {
var fd = stdio.open(file,stdio.flags.O_RDONLY);
if (!fd) {
stdio.fprintf(io.stderr,'Error: Cannot open file: %s\n',file);
return false;
}
var c = stdio.readAll(fd);
stdio.close(fd);
if (!c) {
stdio.fprintf(io.stderr,'Error: Cannot read file: %s\n',file);
return false;
}
try{
var f = new Function('args','env','io',c+';return main(args.length,args);');
} catch(e) {
var l = '';
if (typeof e.lineNumber !== 'undefined')
l = (e.lineNumber-2)+':';
stdio.fprintf(io.stderr,'Error: %s:%s %s\n',file,l,e.message);
return false;
}
code.push(c);
return true;
}
function output() {
if (!link) {
stdio.fprintf(io.stderr,'Error: Compile-only is not currently supported\n',ofile);
return false;
}
var c = code.join('\n')+';return main(args.length,args);';
var f;
try{
f = new Function('args','env','io',c);
} catch(e) {
stdio.fprintf(io.stderr,'Error: Could not create executable file: %s\n',e.message);
return false;
}
var fd = stdio.open(ofile,stdio.flags.O_WRONLY|stdio.flags.O_CREAT|stdio.flags.O_TRUNC);
if (!fd) {
stdio.fprintf(io.stderr,'Error: Cannot open output file: %s\n',ofile);
return false;
}
if (!stdio.write(fd,f)) {
stdio.close(fd);
stdio.fprintf(io.stderr,'Error: Cannot write output file: %s\n',ofile);
return false;
}
stdio.fchmod(fd,clite.modestr('-rwxr-xr-x'));
stdio.close(fd);
return true;
}
function main(argc,argv) {
for (var i=1; i<argc; i++) {
if (argv[i][0] == '-') {
for (var j=1; j<argv[i].length; j++) {
switch (argv[i][j]) {
case '?':
help();
return 0;
break;
case 'o':
ofile = true;
break;
case 'c':
link = false;
break;
default:
stdio.fprintf(io.stderr,'Error: Unknown argument: -%c\n',argv[i][j]);
}
}
}else if (ofile === true) {
ofile = clite.resolvePath(argv[i],false);
}else{
ifiles.push(clite.resolvePath(argv[i],false));
}
}
if (ofile == true)
return 1;
if (ifiles.length < 1) {
stdio.fprintf(io.stderr,'Error: No files specified\n');
return 1;
}
if (ofile == null)
ofile = clite.resolvePath('out.bin',false);
for (var i=0; i<ifiles.length; i++) {
if (!compile(ifiles[i]))
break;
}
if (!output())
return 1;
return 0;
}
return main(args.length,args);
});
// insert commands above this line
}