use crate::emit;
use crate::image;
use crate::link::{self, Linked, Module};
use crate::parse::{Exports, Global, Parser, Program, merge_exports};
use crate::pp::{Diagnostic, LinkMacro, Preprocessor, Severity, SourceFiles};
#[derive(Debug, Clone)]
pub struct CompileOptions {
pub include_paths: Vec<String>,
pub defines: Vec<(String, String)>,
pub undefines: Vec<String>,
pub default_charset: Option<String>,
pub timestamp: [u8; 24],
pub source_text_group: bool,
pub module_names: Vec<(String, usize)>,
pub from_library: Vec<bool>,
pub imports: Vec<(String, Option<String>)>,
pub text_tags: Vec<String>,
pub object_tags: Vec<String>,
pub object_keys: Vec<String>,
pub debug: bool,
pub line_records: bool,
}
impl Default for CompileOptions {
fn default() -> Self {
Self {
include_paths: Vec::new(),
defines: Vec::new(),
undefines: Vec::new(),
default_charset: None,
timestamp: *b"Thu Jan 1 00:00:00 1970",
source_text_group: false,
module_names: Vec::new(),
from_library: Vec::new(),
imports: Vec::new(),
text_tags: Vec::new(),
object_tags: Vec::new(),
object_keys: Vec::new(),
debug: false,
line_records: true,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Compiled {
pub image: Option<Vec<u8>>,
pub unspecified: Vec<(usize, usize)>,
pub diagnostics: Vec<Diagnostic>,
pub symbols: Vec<RuntimeSymbol>,
pub macros: Vec<LinkMacro>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeSymbol {
pub name: Vec<u8>,
pub value: RuntimeValue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeValue {
Function(u32),
Object(u32),
Property(u16),
Enum(u32),
BuiltIn {
set: u16,
index: u16,
},
Class(u32),
}
fn predefined_macros(options: &CompileOptions) -> Vec<(String, String)> {
let stamp = String::from_utf8_lossy(&options.timestamp);
let part = |range: std::ops::Range<usize>| stamp.get(range).unwrap_or("").to_owned();
let mut macros = vec![
(
"__DATE__".to_owned(),
format!("'{} {} {}'", part(4..7), part(8..10), part(20..24)),
),
("__TIME__".to_owned(), format!("'{}'", part(11..19))),
];
if options.debug {
macros.push(("__DEBUG".to_owned(), "1".to_owned()));
}
macros.extend([
("__HEXICON".to_owned(), "1".to_owned()),
(
"__HEXICON_VERSION_MAJOR".to_owned(),
env!("CARGO_PKG_VERSION_MAJOR").to_owned(),
),
(
"__HEXICON_VERSION_MINOR".to_owned(),
env!("CARGO_PKG_VERSION_MINOR").to_owned(),
),
]);
macros.extend(options.defines.iter().cloned());
macros
}
struct MacroTable {
macros: Vec<(LinkMacro, bool)>,
undefined: std::collections::HashSet<Vec<u8>>,
}
fn debug_macros(table: &MacroTable) -> (Vec<u8>, Vec<(usize, usize)>) {
let mut count = 0u32;
let mut out = Vec::new();
let mut clock = Vec::new();
for (mac, pseudo) in &table.macros {
if *pseudo || table.undefined.contains(&mac.name) {
continue;
}
count += 1;
out.extend_from_slice(&(mac.name.len() as u16).to_le_bytes());
out.extend_from_slice(&mac.name);
let flags = u16::from(mac.has_args) | u16::from(mac.has_varargs) << 1;
out.extend_from_slice(&flags.to_le_bytes());
out.extend_from_slice(&(mac.params.len() as u16).to_le_bytes());
for param in &mac.params {
out.extend_from_slice(&(param.len() as u16).to_le_bytes());
out.extend_from_slice(param);
}
out.extend_from_slice(&(mac.expansion.len() as u32).to_le_bytes());
if matches!(mac.name.as_slice(), b"__DATE__" | b"__TIME__") {
clock.push((4 + out.len(), mac.expansion.len()));
}
out.extend_from_slice(&mac.expansion);
}
let mut block = count.to_le_bytes().to_vec();
block.extend_from_slice(&out);
(block, clock)
}
fn link_macro_table(options: &CompileOptions, modules: Vec<Vec<LinkMacro>>) -> MacroTable {
struct Entry {
mac: LinkMacro,
pseudo: bool,
seq: usize,
}
let mut table: Vec<Entry> = Vec::new();
let mut seq = 0;
let mut add = |table: &mut Vec<Entry>, mac: LinkMacro, pseudo: bool| {
table.push(Entry { mac, pseudo, seq });
seq += 1;
};
let plain = |name: &str, expansion: &str| LinkMacro {
name: name.as_bytes().to_vec(),
has_args: false,
has_varargs: false,
params: Vec::new(),
expansion: expansion.as_bytes().to_vec(),
};
add(&mut table, plain("__LINE__", "0"), true);
add(&mut table, plain("__FILE__", ""), true);
for (name, expansion) in predefined_macros(options) {
add(&mut table, plain(&name, &expansion), false);
}
let mut undefined = std::collections::HashSet::new();
for name in &options.undefines {
table.retain(|entry| entry.pseudo || entry.mac.name != name.as_bytes());
undefined.insert(name.as_bytes().to_vec());
}
for module in modules {
for mac in module {
match table.iter().position(|entry| entry.mac.name == mac.name) {
Some(at) => {
let entry = &table[at];
if !entry.pseudo && entry.mac != mac {
undefined.insert(mac.name.clone());
table.remove(at);
}
}
None => add(&mut table, mac, false),
}
}
}
table.sort_by_key(|entry| {
(
crate::pp::macro_chain(&entry.mac.name),
std::cmp::Reverse(entry.seq),
)
});
MacroTable {
macros: table
.into_iter()
.map(|entry| (entry.mac, entry.pseudo))
.collect(),
undefined,
}
}
const TOOL_DATA: [u8; 4] = *b"hxcn";
#[derive(Debug, Default)]
pub struct Shown<'a> {
pub problems: Vec<&'a Diagnostic>,
pub unshown: Vec<(String, usize)>,
}
pub fn shown(diagnostics: &[Diagnostic]) -> Shown<'_> {
let mut shown = Shown::default();
let mut seen: Vec<(&str, u32, &str)> = Vec::new();
for problem in diagnostics {
if problem.hexicon {
if let Some((_, count)) = shown
.unshown
.iter_mut()
.find(|(file, _)| *file == problem.file)
{
*count += 1;
continue;
}
let key = (
problem.file.as_str(),
problem.line,
problem.message.as_str(),
);
if seen.contains(&key) {
continue;
}
seen.push(key);
if problem.message.starts_with("this string has no end") {
shown.unshown.push((problem.file.clone(), 0));
}
}
shown.problems.push(problem);
}
shown
}
fn has_errors(diagnostics: &[Diagnostic]) -> bool {
diagnostics.iter().any(|diagnostic| {
matches!(
diagnostic.severity,
Severity::Error | Severity::Fatal | Severity::Internal
)
})
}
pub(crate) fn start<'a>(
files: &'a mut dyn SourceFiles,
source: &str,
options: &CompileOptions,
) -> Result<Preprocessor<'a>, Diagnostic> {
let mut pp = set_up(files, source, options)?;
pp.set_compile_mode();
Ok(pp)
}
pub fn with_preprocessor<R>(
files: &mut dyn SourceFiles,
sources: &[&str],
source: &str,
options: &CompileOptions,
then: impl FnOnce(&mut Preprocessor<'_>) -> R,
) -> Result<R, Diagnostic> {
let mut with_sources: Vec<&str> = sources.to_vec();
if !with_sources.contains(&source) {
with_sources.push(source);
}
let mut files = crate::builtin::WithBuiltIns::for_sources(files, &with_sources);
let mut pp = set_up(&mut files, source, options)?;
Ok(then(&mut pp))
}
fn set_up<'a>(
files: &'a mut dyn SourceFiles,
source: &str,
options: &CompileOptions,
) -> Result<Preprocessor<'a>, Diagnostic> {
let mut pp = Preprocessor::new(files);
if let Some(charset) = &options.default_charset {
pp.set_default_charset(charset);
}
for (name, expansion) in predefined_macros(options) {
pp.define(&name, &expansion);
}
for path in &options.include_paths {
pp.add_include_path(path);
}
for name in &options.undefines {
pp.undefine(name);
}
if !pp.set_source(source) {
return Err(Diagnostic {
file: String::new(),
line: 0,
severity: Severity::Error,
message: format!("unable to open source file \"{source}\""),
..Default::default()
});
}
pp.set_imports(options.imports.clone());
Ok(pp)
}
pub fn compile(files: &mut dyn SourceFiles, source: &str, options: &CompileOptions) -> Compiled {
compile_program(files, &[source], options)
}
pub fn compile_program(
files: &mut dyn SourceFiles,
sources: &[&str],
options: &CompileOptions,
) -> Compiled {
compile_reading(files, sources, options, None)
}
pub fn compile_and_document(
files: &mut dyn SourceFiles,
sources: &[&str],
options: &CompileOptions,
) -> (Compiled, crate::Documented) {
let mut reading = Some(crate::docs::Reading::default());
let mut documented = None;
let compiled = compile_reading(
files,
sources,
options,
Some((&mut reading, &mut documented)),
);
let documented = documented.unwrap_or_else(|| {
let mut problems: Vec<Diagnostic> = compiled
.diagnostics
.iter()
.filter(|d| d.severity != Severity::Warning)
.cloned()
.collect();
if problems.is_empty() {
problems.push(Diagnostic {
severity: Severity::Error,
message: "the sources were not all read".to_owned(),
..Diagnostic::default()
});
}
reading.take().unwrap_or_default().stopped(problems)
});
(compiled, documented)
}
type Documenting<'r> = (
&'r mut Option<crate::docs::Reading>,
&'r mut Option<crate::Documented>,
);
fn compile_reading(
files: &mut dyn SourceFiles,
sources: &[&str],
options: &CompileOptions,
mut documenting: Option<Documenting<'_>>,
) -> Compiled {
let mut files = crate::builtin::WithBuiltIns::for_sources(files, sources);
let files: &mut dyn SourceFiles = &mut files;
let mut compiled = Compiled::default();
let mut exports = Vec::new();
let mut first_warnings: Vec<Vec<Diagnostic>> = Vec::new();
for source in sources {
let mut pp = match start(files, source, options) {
Ok(pp) => pp,
Err(diagnostic) => {
compiled.diagnostics.push(diagnostic);
return compiled;
}
};
let prog = Parser::new(&mut pp, true, Exports::default()).parse_top();
let mut found = pp.take_diagnostics();
found.iter_mut().for_each(crate::wording::for_hexicon);
let (warnings, mut found): (Vec<_>, Vec<_>) = found
.into_iter()
.partition(|d| d.severity == Severity::Warning);
first_warnings.push(warnings);
compiled.diagnostics.append(&mut found);
if has_errors(&compiled.diagnostics) {
return compiled;
}
exports.push(prog.exports());
}
let defined: Vec<Vec<Vec<u8>>> = exports
.iter()
.map(|exported| {
exported
.objs
.iter()
.map(|obj| obj.name.clone())
.chain(exported.funcs.iter().map(|func| func.name.clone()))
.collect()
})
.collect();
let known = Program::knowing(merge_exports(exports));
let mut modules = Vec::new();
let mut module_macros = Vec::new();
let mut source_files: Vec<String> = Vec::new();
let from_library = |index: usize| options.from_library.get(index) == Some(&true);
let checks_names = (0..sources.len()).any(|index| !from_library(index));
let mut names = crate::names::Checker::default();
for (index, source) in sources.iter().enumerate() {
let module = options
.module_names
.get(index)
.cloned()
.unwrap_or_else(|| ((*source).to_owned(), index + 1));
let mut pp = match start(files, source, options) {
Ok(pp) => pp,
Err(diagnostic) => {
compiled.diagnostics.push(diagnostic);
return compiled;
}
};
let mut parser = Parser::with_program(&mut pp, false, known.clone());
parser.set_module(module, options.source_text_group);
parser.set_record_uses(documenting.is_some() && !from_library(index));
if !from_library(index) {
let mut before = std::collections::HashMap::new();
for (earlier, names) in defined.iter().enumerate().take(index) {
let by = (!from_library(earlier)).then(|| sources[earlier].to_owned());
for name in names {
before.entry(name.clone()).or_insert_with(|| by.clone());
}
}
parser.set_defined_before(before);
}
let mut prog = parser.parse_top();
let mut found = pp.take_diagnostics();
for diagnostic in &mut found {
crate::wording::for_hexicon(diagnostic);
crate::wording::suggest_name(diagnostic, &prog.globals);
}
for warning in std::mem::take(&mut first_warnings[index]) {
if !found.contains(&warning) {
compiled.diagnostics.push(warning);
}
}
compiled.diagnostics.extend(found);
module_macros.push(pp.link_macros());
if has_errors(&compiled.diagnostics) {
return compiled;
}
if let Some((Some(reading), _)) = documenting.as_mut().map(|(r, d)| (&mut **r, d)) {
let names = pp.file_names();
reading.add(&prog, &names, from_library(index), pp.files());
}
if checks_names {
names.add(
crate::names::collect(&prog),
!from_library(index),
from_library(index),
&|file| pp.file_name(file).to_owned(),
);
}
prog.from_library = from_library(index);
let mut generated = emit::generate(
&mut prog,
options.debug,
options.line_records || options.debug,
source_files.len(),
);
source_files.extend(pp.file_names());
for diagnostic in std::mem::take(&mut generated.diagnostics) {
let meant = diagnostic.meant.clone();
let file = if diagnostic.file == usize::MAX || diagnostic.line == 0 {
String::new()
} else {
pp.file_name(diagnostic.file).to_owned()
};
let mut diagnostic = Diagnostic {
file,
line: diagnostic.line,
severity: diagnostic.severity,
message: diagnostic.message,
..Default::default()
};
crate::wording::for_hexicon(&mut diagnostic);
crate::wording::suggest_name(&mut diagnostic, &prog.globals);
if let Some(meant) = &meant {
diagnostic.note = Some(format!(
"did you mean \"{}\"?",
String::from_utf8_lossy(meant)
));
}
compiled.diagnostics.push(diagnostic);
}
if has_errors(&compiled.diagnostics) {
return compiled;
}
let object_file = source
.rsplit(['/', '\\'])
.next()
.unwrap_or(source)
.to_owned();
modules.push(Module {
prog,
out: generated,
object_file,
});
}
if let Some((reading, documented)) = documenting.take()
&& let Some(reading) = reading.take()
{
*documented = Some(reading.finish(files));
}
compiled.diagnostics.extend(names.warnings());
let texts: Vec<String> = if options.text_tags.is_empty()
&& options.object_tags.is_empty()
&& options.object_keys.is_empty()
{
Vec::new()
} else {
sources
.iter()
.map(|source| {
files
.read(source)
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
.unwrap_or_default()
})
.collect()
};
if !options.text_tags.is_empty() {
let mut known: std::collections::HashSet<String> =
options.text_tags.iter().cloned().collect();
for text in &texts {
known.extend(crate::tags::tags_defined(text));
}
for (index, source) in sources.iter().enumerate() {
if !from_library(index) {
compiled
.diagnostics
.extend(crate::tags::check(source, &texts[index], &known));
}
}
}
let note = |compiled: &mut Compiled, severity: Severity, message: String| {
compiled.diagnostics.push(Diagnostic {
file: String::new(),
line: 0,
severity,
message,
..Default::default()
});
};
let Linked {
mut prog,
out,
enum_ids,
errors,
} = link::link(modules);
if !errors.is_empty() {
for message in errors {
note(&mut compiled, Severity::Error, message);
}
return compiled;
}
if !options.object_tags.is_empty() || !options.object_keys.is_empty() {
let objects: std::collections::HashSet<&[u8]> = prog
.globals
.names()
.filter(|name| matches!(prog.globals.peek(name), Some(Global::Obj(_))))
.collect();
let tag_names: std::collections::HashSet<String> =
options.object_tags.iter().cloned().collect();
for (index, source) in sources.iter().enumerate() {
if !from_library(index) {
compiled.diagnostics.extend(crate::tags::check_objects(
source,
&texts[index],
&tag_names,
&options.object_keys,
&objects,
));
}
}
if has_errors(&compiled.diagnostics) {
return compiled;
}
}
let mut generated = emit::link_generate(&mut prog, out, enum_ids.clone());
for name in emit::unresolved_externs(&prog, &generated) {
let message = if name.as_slice() == b"main" {
"the program has no main(args) function, which the system library calls \
when it starts"
.to_owned()
} else {
format!(
"unresolved external reference \"{}\"",
crate::pp::show_name(&name)
)
};
note(&mut compiled, Severity::Error, message);
}
let has_main = matches!(
prog.globals.peek(b"_main".as_slice()),
Some(Global::Func(func)) if generated.func_anchor.contains_key(func)
);
if !has_main && prog.globals.peek(b"_main".as_slice()).is_none() {
note(
&mut compiled,
Severity::Error,
"function _main() is not defined: a program built without the system \
library (--no-system) has to define its own"
.to_owned(),
);
return compiled;
}
let exports = emit::resolve_exports(&prog, &mut generated);
for (severity, message) in exports.problems {
note(&mut compiled, severity, message);
}
for (name, id) in exports.assumed_props {
prog.add_assumed_prop(name, id);
}
if has_errors(&compiled.diagnostics) {
return compiled;
}
for message in std::mem::take(&mut generated.link_errors) {
note(&mut compiled, Severity::Error, message);
}
if has_errors(&compiled.diagnostics) {
return compiled;
}
let table = link_macro_table(options, module_macros);
let debug = options.debug.then(|| {
let (macros, macros_unspecified) = debug_macros(&table);
image::DebugRecords {
enum_ids: enum_ids.clone(),
macros,
macros_unspecified,
}
});
match image::write_image(
&prog,
generated,
&options.timestamp,
&TOOL_DATA,
if options.line_records || options.debug {
&source_files
} else {
&[]
},
debug.as_ref(),
) {
Ok(image) => {
compiled.symbols = runtime_symbols(&prog, &enum_ids, &image.func_addrs);
compiled.macros = table.macros.into_iter().map(|(mac, _)| mac).collect();
compiled.image = Some(image.bytes);
compiled.unspecified = image.unspecified;
}
Err(message) => note(&mut compiled, Severity::Error, message),
}
compiled
}
fn runtime_symbols(
prog: &crate::parse::Program,
enum_ids: &[u32],
func_addrs: &std::collections::HashMap<usize, u32>,
) -> Vec<RuntimeSymbol> {
prog.globals
.in_table_order()
.into_iter()
.filter_map(|(name, global)| {
let value = match global {
Global::Func(func) => RuntimeValue::Function(*func_addrs.get(&func)?),
Global::Obj(obj) => RuntimeValue::Object(prog.objs[obj].id),
Global::Prop(prop) => RuntimeValue::Property(prog.props[prop].id),
Global::Enum(sym) => RuntimeValue::Enum(*enum_ids.get(sym)?),
Global::Bif(bif) => RuntimeValue::BuiltIn {
set: prog.bifs[bif].set as u16,
index: prog.bifs[bif].index as u16,
},
Global::Meta(meta) => RuntimeValue::Class(prog.metas[meta].obj_id),
Global::DynLocal(_) => return None,
};
Some(RuntimeSymbol {
name: name.to_vec(),
value,
})
})
.collect()
}