Skip to content

Instantly share code, notes, and snippets.

@spaceface777
Last active June 22, 2021 16:14
Show Gist options
  • Save spaceface777/34d25420f2dc4953fb7864f44a211105 to your computer and use it in GitHub Desktop.
Save spaceface777/34d25420f2dc4953fb7864f44a211105 to your computer and use it in GitHub Desktop.
C amalgamator for the Boehm garbage collector
const ENTRYPOINTS = ['extra/gc.c', 'include/gc.h']
const fs = require('fs')
const path = require('path')
const search_dirs = ['.', 'extra', 'include', 'include/private', 'include/extra']
function find(file) {
file = file.substring(file.lastIndexOf('/') + 1)
for (const dir of search_dirs) {
if (fs.readdirSync(dir).includes(file)) return path.join(dir, file)
}
return file
}
const included_files = []
function amalgamate(line) {
const m = line.match(/#\s*include "(.+?)"/)
if (!m) return line
const p = find(m[1])
if (included_files.includes(p)) return ''
included_files.push(p)
try {
return fs.readFileSync(p, 'utf-8')
.split('\n')
.map(amalgamate)
.join('\n')
} catch {
return line
}
}
for (const entrypoint of ENTRYPOINTS) {
const gc_source = fs.readFileSync(entrypoint, 'utf-8')
const copyright_header = gc_source.match(/\/\*[\s\S]+?\*\//)[0]
let amalgamated_source = gc_source.split('\n').map(amalgamate).join('\n')
if (process.argv.find(it => it === '-m' || it === '--minify')) {
amalgamated_source = amalgamated_source
// remove comments
.replace(/\/\*[\s\S]+?\*\//g, '')
.replace(/\/\/.+/g, '')
.replace(/\\\n\s+/g, '') // escaped newlines
.replace(/^# +/gm, '#') // `# define` -> `#define`
.replace(/ *(\+|\*|\/|\+\+|\-\-|\+=|\-=|\*=|\/=|%=|=|==|!=|&&|\|\||\?|\:|!|&|\||\^|<<|>>|;|<=|>=|<<=|>>=|&=|\|=|\^=|,|->|\)) */g, '$1') // remove spaces around infix ops
.replace(/"\n"/g, '') // remove concatenated string literals spanning multiple lines
.replace(/ +/g, ' ') // replace multiple spaces with just one
.split('\n')
.map(it => it.trim()) // trim whitespace around each line
.filter(it => it !== '') // remove empty lines
.join('\n');
}
fs.mkdirSync('dist', { recursive: true })
fs.writeFileSync(`dist/${path.basename(entrypoint)}`, `${copyright_header}\n\n${amalgamated_source}\n`)
}
@spytheman
Copy link

.filter(Boolean) ?

@spaceface777
Copy link
Author

spaceface777 commented Jun 22, 2021

it's the same as .filter(it => !!it) / .filter(it => it !== '') :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment