1
0
mirror of https://github.com/sehugg/8bitworkshop.git synced 2024-11-12 10:07:00 +00:00
8bitworkshop/src/project.ts

334 lines
11 KiB
TypeScript
Raw Normal View History

"use strict";
2019-02-21 21:47:25 +00:00
import { FileData, Dependency, SourceLine, SourceFile, CodeListing, CodeListingMap, WorkerError, Segment, WorkerResult } from "./workertypes";
import { getFilenamePrefix, getFolderForPath, isProbablyBinary, getBasePlatform } from "./util";
import { Platform } from "./baseplatform";
2018-07-26 13:43:49 +00:00
type BuildResultCallback = (result:WorkerResult) => void;
type BuildStatusCallback = (busy:boolean) => void;
type IterateFilesCallback = (path:string, data:FileData) => void;
type GetRemoteCallback = (path:string, callback:(data:FileData) => void, datatype:'text'|'arraybuffer') => any;
export class CodeProject {
filedata : {[path:string]:FileData} = {};
listings : CodeListingMap;
2019-02-21 21:47:25 +00:00
segments : Segment[];
mainpath : string;
pendingWorkerMessages = 0;
tools_preloaded = {};
callbackBuildResult : BuildResultCallback;
callbackBuildStatus : BuildStatusCallback;
2018-07-08 04:58:11 +00:00
worker : Worker;
platform_id : string;
platform : Platform;
store : any;
callbackGetRemote : GetRemoteCallback;
2018-09-11 00:44:53 +00:00
mainPath : string;
isCompiling : boolean = false;
constructor(worker, platform_id:string, platform, store) {
this.worker = worker;
this.platform_id = platform_id;
this.platform = platform;
this.store = store;
worker.onmessage = (e) => {
2018-12-01 11:48:33 +00:00
this.receiveWorkerMessage(e.data);
};
}
2018-12-01 11:48:33 +00:00
receiveWorkerMessage(data : WorkerResult) {
var notfinal = this.pendingWorkerMessages > 1;
if (notfinal) {
this.sendBuild();
this.pendingWorkerMessages = 1;
} else {
if (this.callbackBuildStatus) this.callbackBuildStatus(false);
if (!this.isCompiling) { console.log(this.pendingWorkerMessages); console.trace(); } // debug compile problems
this.isCompiling = false;
this.pendingWorkerMessages = 0;
}
if (data && !data.unchanged) {
this.processBuildResult(data);
if (this.callbackBuildResult) this.callbackBuildResult(data); // call with data when changed
}
}
preloadWorker(path:string) {
var tool = this.platform.getToolForFilename(path);
if (tool && !this.tools_preloaded[tool]) {
this.worker.postMessage({preload:tool, platform:this.platform_id});
this.tools_preloaded[tool] = true;
}
}
pushAllFiles(files:string[], fn:string) {
// look for local and preset files
files.push(fn);
// look for files in current (main file) folder
var dir = getFolderForPath(this.mainpath);
2018-11-27 20:14:22 +00:00
if (dir.length > 0 && dir != 'local') // TODO
files.push(dir + '/' + fn);
}
parseIncludeDependencies(text:string):string[] {
2019-04-24 17:46:19 +00:00
let files = [];
let m;
2018-11-18 17:30:41 +00:00
if (this.platform_id.startsWith('verilog')) {
2018-12-03 15:51:47 +00:00
// include verilog includes
2019-04-24 17:46:19 +00:00
let re1 = /^\s*(`include|[.]include)\s+"(.+?)"/gmi;
while (m = re1.exec(text)) {
this.pushAllFiles(files, m[2]);
}
// include .arch (json) statements
2019-04-24 17:46:19 +00:00
let re2 = /^\s*([.]arch)\s+(\w+)/gmi;
while (m = re2.exec(text)) {
this.pushAllFiles(files, m[2]+".json");
}
2018-12-03 15:51:47 +00:00
// include $readmem[bh] (TODO)
let re3 = /\$readmem[bh]\("(.+?)"/gmi;
2018-12-03 15:51:47 +00:00
while (m = re3.exec(text)) {
this.pushAllFiles(files, m[1]);
2018-12-03 15:51:47 +00:00
}
} else {
// for .asm -- [.]include "file"
// for .c -- #include "file"
2019-04-24 17:46:19 +00:00
let re2 = /^\s*[.#]?(include|incbin)\s+"(.+?)"/gmi;
while (m = re2.exec(text)) {
this.pushAllFiles(files, m[2]);
}
// for .c -- //#resource "file" (or ;resource or #resource)
let re3 = /^\s*([;]|[/][/])#resource\s+"(.+?)"/gm;
2019-04-24 17:46:19 +00:00
while (m = re3.exec(text)) {
this.pushAllFiles(files, m[2]);
}
}
return files;
}
parseLinkDependencies(text:string):string[] {
2019-04-24 17:46:19 +00:00
let files = [];
let m;
2018-11-18 17:30:41 +00:00
if (this.platform_id.startsWith('verilog')) {
//
} else {
// for .c -- //#link "file" (or ;link or #link)
let re = /^\s*([;]|[/][/])#link\s+"(.+?)"/gm;
while (m = re.exec(text)) {
this.pushAllFiles(files, m[2]);
}
}
return files;
}
2019-05-23 12:32:53 +00:00
loadFileDependencies(text:string) : Promise<Dependency[]> {
2019-04-24 17:46:19 +00:00
let includes = this.parseIncludeDependencies(text);
let linkfiles = this.parseLinkDependencies(text);
let allfiles = includes.concat(linkfiles);
2019-05-23 12:32:53 +00:00
return this.loadFiles(allfiles).then((result) => {
// set 'link' property on files that are link dependencies (must match filename)
2019-04-24 17:46:19 +00:00
if (result) {
for (let dep of result) {
dep.link = linkfiles.indexOf(dep.path) >= 0;
2019-04-24 17:46:19 +00:00
}
}
2019-05-23 12:32:53 +00:00
return result;
});
}
okToSend():boolean {
return this.pendingWorkerMessages++ == 0;
}
updateFileInStore(path:string, text:FileData) {
// protect against accidential whole-file deletion
if ((<string>text).trim && (<string>text).trim().length) {
this.store.setItem(path, text);
}
}
// TODO: test duplicate files, local paths mixed with presets
buildWorkerMessage(depends:Dependency[]) {
this.preloadWorker(this.mainpath);
var msg = {updates:[], buildsteps:[]};
// TODO: add preproc directive for __MAINFILE__
var mainfilename = this.stripLocalPath(this.mainpath);
var maintext = this.getFile(this.mainpath);
var depfiles = [];
msg.updates.push({path:mainfilename, data:maintext});
for (var dep of depends) {
if (!dep.link) {
msg.updates.push({path:dep.filename, data:dep.data});
depfiles.push(dep.filename);
}
}
msg.buildsteps.push({path:mainfilename, files:[mainfilename].concat(depfiles), platform:this.platform_id, tool:this.platform.getToolForFilename(this.mainpath), mainfile:true});
for (var dep of depends) {
if (dep.data && dep.link) {
this.preloadWorker(dep.filename);
msg.updates.push({path:dep.filename, data:dep.data});
msg.buildsteps.push({path:dep.filename, files:[dep.filename].concat(depfiles), platform:this.platform_id, tool:this.platform.getToolForFilename(dep.path)});
}
}
return msg;
}
// TODO: get local file as well as presets?
2019-05-23 12:32:53 +00:00
loadFiles(paths:string[]) : Promise<Dependency[]> {
return new Promise( (yes,no) => {
var result : Dependency[] = [];
var addResult = (path, data) => {
result.push({
path:path,
filename:this.stripLocalPath(path),
link:true,
data:data
});
}
var loadNext = () => {
var path = paths.shift();
if (!path) {
// finished loading all files; return result
2019-05-23 12:32:53 +00:00
yes(result);
} else {
// look in cache
if (path in this.filedata) { // found in cache?
var data = this.filedata[path];
if (data)
addResult(path, data);
loadNext();
} else {
// look in store
this.store.getItem(path, (err, value) => {
if (err) { // err fetching from store
2019-05-23 12:32:53 +00:00
no(err);
} else if (value) { // found in store?
2018-08-21 14:16:47 +00:00
this.filedata[path] = value; // do not update store, just cache
addResult(path, value);
loadNext();
} else {
// found on remote fetch?
var preset_id = this.platform_id;
preset_id = getBasePlatform(preset_id); // remove .suffix from preset name
var webpath = "presets/" + preset_id + "/" + path;
// try to GET file, use file ext to determine text/binary
this.callbackGetRemote( webpath, (data:FileData) => {
if (data == null) {
console.log("Could not load preset file", path);
2018-08-21 14:16:47 +00:00
this.filedata[path] = null; // mark cache entry as invalid
} else {
if (data instanceof ArrayBuffer)
data = new Uint8Array(data); // convert to typed array
console.log("GET",webpath,data.length,'bytes');
this.filedata[path] = data; // do not update store, just cache
addResult(path, data);
}
loadNext();
}, isProbablyBinary(path) ? 'arraybuffer' : 'text');
}
});
}
}
}
loadNext(); // load first file
2019-05-23 12:32:53 +00:00
});
}
getFile(path:string):FileData {
return this.filedata[path];
}
// TODO: purge files not included in latest build?
iterateFiles(callback:IterateFilesCallback) {
for (var path in this.filedata) {
callback(path, this.getFile(path));
}
}
sendBuild() {
if (!this.mainpath) throw "need to call setMainFile first";
var maindata = this.getFile(this.mainpath);
2018-12-01 11:48:33 +00:00
// if binary blob, just return it as ROM
if (maindata instanceof Uint8Array) {
this.isCompiling = true;
this.receiveWorkerMessage({
output:maindata,
errors:[],
listings:null,
symbolmap:null,
params:{}
});
return;
}
// otherwise, make it a string
var text = typeof maindata === "string" ? maindata : '';
// TODO: load dependencies of non-main files
2019-05-23 12:32:53 +00:00
return this.loadFileDependencies(text).then( (depends) => {
2018-07-06 06:42:01 +00:00
if (!depends) depends = [];
var workermsg = this.buildWorkerMessage(depends);
this.worker.postMessage(workermsg);
2018-09-11 00:44:53 +00:00
this.isCompiling = true;
});
}
updateFile(path:string, text:FileData) {
this.updateFileInStore(path, text); // TODO: isBinary
this.filedata[path] = text;
if (this.okToSend() && this.mainpath) {
if (this.callbackBuildStatus) this.callbackBuildStatus(true);
this.sendBuild();
}
};
setMainFile(path:string) {
this.mainpath = path;
if (this.callbackBuildStatus) this.callbackBuildStatus(true);
this.sendBuild();
}
processBuildResult(data:WorkerResult) {
// TODO: link listings with source files
if (data.listings) {
this.listings = data.listings;
for (var lstname in this.listings) {
var lst = this.listings[lstname];
2019-02-22 16:43:07 +00:00
if (lst.lines)
lst.sourcefile = new SourceFile(lst.lines, lst.text);
2019-02-22 16:43:07 +00:00
if (lst.asmlines)
lst.assemblyfile = new SourceFile(lst.asmlines, lst.text);
}
}
2019-02-21 21:47:25 +00:00
// save and sort segment list
this.segments = data.segments;
if (this.segments) {
this.segments.sort((a,b) => {return a.start-b.start});
}
}
getListings() : CodeListingMap {
return this.listings;
}
// returns first listing in format [prefix].lst (TODO: could be better)
getListingForFile(path) : CodeListing {
var fnprefix = getFilenamePrefix(this.stripLocalPath(path));
var listings = this.getListings();
for (var lstfn in listings) {
if (getFilenamePrefix(lstfn) == fnprefix) {
return listings[lstfn];
}
}
}
stripLocalPath(path : string) : string {
2019-05-07 19:37:37 +00:00
if (this.mainPath) {
var folder = getFolderForPath(this.mainPath);
if (folder != '' && path.startsWith(folder)) {
path = path.substring(folder.length+1);
}
}
return path;
}
}