1use crate::emit;
4use crate::image;
5use crate::link::{self, Linked, Module};
6use crate::parse::{Exports, Global, Parser, Program, merge_exports};
7use crate::pp::{Diagnostic, LinkMacro, Preprocessor, Severity, SourceFiles};
8
9#[derive(Debug, Clone)]
11pub struct CompileOptions {
12 pub include_paths: Vec<String>,
14 pub defines: Vec<(String, String)>,
16 pub undefines: Vec<String>,
18 pub default_charset: Option<String>,
21 pub timestamp: [u8; 24],
25 pub source_text_group: bool,
28 pub module_names: Vec<(String, usize)>,
33 pub from_library: Vec<bool>,
38 pub imports: Vec<(String, Option<String>)>,
41 pub text_tags: Vec<String>,
45 pub object_tags: Vec<String>,
49 pub object_keys: Vec<String>,
52 pub ifid: Option<String>,
56 pub debug: bool,
60 pub line_records: bool,
66}
67
68impl Default for CompileOptions {
69 fn default() -> Self {
70 Self {
71 include_paths: Vec::new(),
72 defines: Vec::new(),
73 undefines: Vec::new(),
74 default_charset: None,
75 timestamp: *b"Thu Jan 1 00:00:00 1970",
76 source_text_group: false,
77 module_names: Vec::new(),
78 from_library: Vec::new(),
79 imports: Vec::new(),
80 text_tags: Vec::new(),
81 object_tags: Vec::new(),
82 object_keys: Vec::new(),
83 ifid: None,
84 debug: false,
85 line_records: true,
86 }
87 }
88}
89
90#[derive(Debug, Clone, Default)]
92pub struct Compiled {
93 pub image: Option<Vec<u8>>,
95 pub unspecified: Vec<(usize, usize)>,
100 pub diagnostics: Vec<Diagnostic>,
102 pub symbols: Vec<RuntimeSymbol>,
107 pub macros: Vec<LinkMacro>,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct RuntimeSymbol {
115 pub name: Vec<u8>,
117 pub value: RuntimeValue,
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum RuntimeValue {
124 Function(u32),
126 Object(u32),
128 Property(u16),
130 Enum(u32),
132 BuiltIn {
134 set: u16,
136 index: u16,
138 },
139 Class(u32),
141}
142
143fn predefined_macros(options: &CompileOptions) -> Vec<(String, String)> {
148 let stamp = String::from_utf8_lossy(&options.timestamp);
149 let part = |range: std::ops::Range<usize>| stamp.get(range).unwrap_or("").to_owned();
150 let mut macros = vec![
151 (
152 "__DATE__".to_owned(),
153 format!("'{} {} {}'", part(4..7), part(8..10), part(20..24)),
154 ),
155 ("__TIME__".to_owned(), format!("'{}'", part(11..19))),
156 ];
157 if options.debug {
158 macros.push(("__DEBUG".to_owned(), "1".to_owned()));
159 }
160 macros.extend([
161 ("__HEXICON".to_owned(), "1".to_owned()),
162 (
163 "__HEXICON_VERSION_MAJOR".to_owned(),
164 env!("CARGO_PKG_VERSION_MAJOR").to_owned(),
165 ),
166 (
167 "__HEXICON_VERSION_MINOR".to_owned(),
168 env!("CARGO_PKG_VERSION_MINOR").to_owned(),
169 ),
170 ]);
171 macros.extend(options.defines.iter().cloned());
172 macros
173}
174
175struct MacroTable {
178 macros: Vec<(LinkMacro, bool)>,
181 undefined: std::collections::HashSet<Vec<u8>>,
182}
183
184fn debug_macros(table: &MacroTable) -> (Vec<u8>, Vec<(usize, usize)>) {
190 let mut count = 0u32;
191 let mut out = Vec::new();
192 let mut clock = Vec::new();
193 for (mac, pseudo) in &table.macros {
194 if *pseudo || table.undefined.contains(&mac.name) {
195 continue;
196 }
197 count += 1;
198 out.extend_from_slice(&(mac.name.len() as u16).to_le_bytes());
199 out.extend_from_slice(&mac.name);
200 let flags = u16::from(mac.has_args) | u16::from(mac.has_varargs) << 1;
201 out.extend_from_slice(&flags.to_le_bytes());
202 out.extend_from_slice(&(mac.params.len() as u16).to_le_bytes());
203 for param in &mac.params {
204 out.extend_from_slice(&(param.len() as u16).to_le_bytes());
205 out.extend_from_slice(param);
206 }
207 out.extend_from_slice(&(mac.expansion.len() as u32).to_le_bytes());
208 if matches!(mac.name.as_slice(), b"__DATE__" | b"__TIME__") {
209 clock.push((4 + out.len(), mac.expansion.len()));
210 }
211 out.extend_from_slice(&mac.expansion);
212 }
213 let mut block = count.to_le_bytes().to_vec();
214 block.extend_from_slice(&out);
215 (block, clock)
216}
217
218fn link_macro_table(options: &CompileOptions, modules: Vec<Vec<LinkMacro>>) -> MacroTable {
224 struct Entry {
225 mac: LinkMacro,
226 pseudo: bool,
227 seq: usize,
228 }
229 let mut table: Vec<Entry> = Vec::new();
230 let mut seq = 0;
231 let mut add = |table: &mut Vec<Entry>, mac: LinkMacro, pseudo: bool| {
232 table.push(Entry { mac, pseudo, seq });
233 seq += 1;
234 };
235 let plain = |name: &str, expansion: &str| LinkMacro {
236 name: name.as_bytes().to_vec(),
237 has_args: false,
238 has_varargs: false,
239 params: Vec::new(),
240 expansion: expansion.as_bytes().to_vec(),
241 };
242 add(&mut table, plain("__LINE__", "0"), true);
243 add(&mut table, plain("__FILE__", ""), true);
244 for (name, expansion) in predefined_macros(options) {
245 add(&mut table, plain(&name, &expansion), false);
246 }
247 let mut undefined = std::collections::HashSet::new();
248 for name in &options.undefines {
249 table.retain(|entry| entry.pseudo || entry.mac.name != name.as_bytes());
250 undefined.insert(name.as_bytes().to_vec());
251 }
252 for module in modules {
253 for mac in module {
254 match table.iter().position(|entry| entry.mac.name == mac.name) {
255 Some(at) => {
256 let entry = &table[at];
257 if !entry.pseudo && entry.mac != mac {
258 undefined.insert(mac.name.clone());
259 table.remove(at);
260 }
261 }
262 None => add(&mut table, mac, false),
263 }
264 }
265 }
266 table.sort_by_key(|entry| {
267 (
268 crate::pp::macro_chain(&entry.mac.name),
269 std::cmp::Reverse(entry.seq),
270 )
271 });
272 MacroTable {
273 macros: table
274 .into_iter()
275 .map(|entry| (entry.mac, entry.pseudo))
276 .collect(),
277 undefined,
278 }
279}
280
281const TOOL_DATA: [u8; 4] = *b"hxcn";
283
284#[derive(Debug, Default)]
287pub struct Shown<'a> {
288 pub problems: Vec<&'a Diagnostic>,
290 pub unshown: Vec<(String, usize)>,
293}
294
295pub fn shown(diagnostics: &[Diagnostic]) -> Shown<'_> {
300 let mut shown = Shown::default();
301 let mut seen: Vec<(&str, u32, &str)> = Vec::new();
302 for problem in diagnostics {
303 if problem.hexicon {
304 if let Some((_, count)) = shown
305 .unshown
306 .iter_mut()
307 .find(|(file, _)| *file == problem.file)
308 {
309 *count += 1;
310 continue;
311 }
312 let key = (
313 problem.file.as_str(),
314 problem.line,
315 problem.message.as_str(),
316 );
317 if seen.contains(&key) {
318 continue;
319 }
320 seen.push(key);
321 if problem.message.starts_with("this string has no end") {
322 shown.unshown.push((problem.file.clone(), 0));
323 }
324 }
325 shown.problems.push(problem);
326 }
327 shown
328}
329
330fn has_errors(diagnostics: &[Diagnostic]) -> bool {
331 diagnostics.iter().any(|diagnostic| {
332 matches!(
333 diagnostic.severity,
334 Severity::Error | Severity::Fatal | Severity::Internal
335 )
336 })
337}
338
339pub(crate) fn start<'a>(
340 files: &'a mut dyn SourceFiles,
341 source: &str,
342 options: &CompileOptions,
343) -> Result<Preprocessor<'a>, Diagnostic> {
344 let mut pp = set_up(files, source, options)?;
345 pp.set_compile_mode();
346 Ok(pp)
347}
348
349pub fn with_preprocessor<R>(
355 files: &mut dyn SourceFiles,
356 sources: &[&str],
357 source: &str,
358 options: &CompileOptions,
359 then: impl FnOnce(&mut Preprocessor<'_>) -> R,
360) -> Result<R, Diagnostic> {
361 let mut with_sources: Vec<&str> = sources.to_vec();
362 if !with_sources.contains(&source) {
363 with_sources.push(source);
364 }
365 let mut files = crate::builtin::WithBuiltIns::for_sources(files, &with_sources);
366 let mut pp = set_up(&mut files, source, options)?;
367 Ok(then(&mut pp))
368}
369
370fn set_up<'a>(
372 files: &'a mut dyn SourceFiles,
373 source: &str,
374 options: &CompileOptions,
375) -> Result<Preprocessor<'a>, Diagnostic> {
376 let mut pp = Preprocessor::new(files);
377 if let Some(charset) = &options.default_charset {
378 pp.set_default_charset(charset);
379 }
380
381 for (name, expansion) in predefined_macros(options) {
382 pp.define(&name, &expansion);
383 }
384 for path in &options.include_paths {
385 pp.add_include_path(path);
386 }
387 for name in &options.undefines {
388 pp.undefine(name);
389 }
390 if !pp.set_source(source) {
391 return Err(Diagnostic {
392 file: String::new(),
394 line: 0,
395 severity: Severity::Error,
396 message: format!("unable to open source file \"{source}\""),
397 ..Default::default()
398 });
399 }
400 pp.set_imports(options.imports.clone());
401 Ok(pp)
402}
403
404pub fn compile(files: &mut dyn SourceFiles, source: &str, options: &CompileOptions) -> Compiled {
406 compile_program(files, &[source], options)
407}
408
409pub fn compile_program(
417 files: &mut dyn SourceFiles,
418 sources: &[&str],
419 options: &CompileOptions,
420) -> Compiled {
421 compile_reading(files, sources, options, None)
422}
423
424pub fn compile_and_document(
431 files: &mut dyn SourceFiles,
432 sources: &[&str],
433 options: &CompileOptions,
434) -> (Compiled, crate::Documented) {
435 let mut reading = Some(crate::docs::Reading::default());
436 let mut documented = None;
437 let compiled = compile_reading(
438 files,
439 sources,
440 options,
441 Some((&mut reading, &mut documented)),
442 );
443 let documented = documented.unwrap_or_else(|| {
444 let mut problems: Vec<Diagnostic> = compiled
445 .diagnostics
446 .iter()
447 .filter(|d| d.severity != Severity::Warning)
448 .cloned()
449 .collect();
450 if problems.is_empty() {
451 problems.push(Diagnostic {
452 severity: Severity::Error,
453 message: "the sources were not all read".to_owned(),
454 ..Diagnostic::default()
455 });
456 }
457 reading.take().unwrap_or_default().stopped(problems)
458 });
459 (compiled, documented)
460}
461
462type Documenting<'r> = (
465 &'r mut Option<crate::docs::Reading>,
466 &'r mut Option<crate::Documented>,
467);
468
469fn compile_reading(
470 files: &mut dyn SourceFiles,
471 sources: &[&str],
472 options: &CompileOptions,
473 mut documenting: Option<Documenting<'_>>,
474) -> Compiled {
475 let mut files = crate::builtin::WithBuiltIns::for_sources(files, sources);
477 let files: &mut dyn SourceFiles = &mut files;
478 let mut compiled = Compiled::default();
479
480 let mut exports = Vec::new();
481 let mut first_warnings: Vec<Vec<Diagnostic>> = Vec::new();
484 for source in sources {
485 let mut pp = match start(files, source, options) {
486 Ok(pp) => pp,
487 Err(diagnostic) => {
488 compiled.diagnostics.push(diagnostic);
489 return compiled;
490 }
491 };
492 let prog = Parser::new(&mut pp, true, Exports::default()).parse_top();
493 let mut found = pp.take_diagnostics();
494 found.iter_mut().for_each(crate::wording::for_hexicon);
495 let (warnings, mut found): (Vec<_>, Vec<_>) = found
498 .into_iter()
499 .partition(|d| d.severity == Severity::Warning);
500 first_warnings.push(warnings);
501 compiled.diagnostics.append(&mut found);
502 if has_errors(&compiled.diagnostics) {
503 return compiled;
504 }
505 exports.push(prog.exports());
506 }
507 let defined: Vec<Vec<Vec<u8>>> = exports
511 .iter()
512 .map(|exported| {
513 exported
514 .objs
515 .iter()
516 .map(|obj| obj.name.clone())
517 .chain(exported.funcs.iter().map(|func| func.name.clone()))
518 .collect()
519 })
520 .collect();
521 let known = Program::knowing(merge_exports(exports));
523
524 let mut modules = Vec::new();
525 let mut module_macros = Vec::new();
526 let mut source_files: Vec<String> = Vec::new();
530 let from_library = |index: usize| options.from_library.get(index) == Some(&true);
532 let checks_names = (0..sources.len()).any(|index| !from_library(index));
533 let mut names = crate::names::Checker::default();
534 for (index, source) in sources.iter().enumerate() {
535 let module = options
536 .module_names
537 .get(index)
538 .cloned()
539 .unwrap_or_else(|| ((*source).to_owned(), index + 1));
540 let mut pp = match start(files, source, options) {
541 Ok(pp) => pp,
542 Err(diagnostic) => {
543 compiled.diagnostics.push(diagnostic);
544 return compiled;
545 }
546 };
547 let mut parser = Parser::with_program(&mut pp, false, known.clone());
548 parser.set_module(module, options.source_text_group);
549 parser.set_record_uses(documenting.is_some() && !from_library(index));
551 if !from_library(index) {
552 let mut before = std::collections::HashMap::new();
553 for (earlier, names) in defined.iter().enumerate().take(index) {
554 let by = (!from_library(earlier)).then(|| sources[earlier].to_owned());
555 for name in names {
556 before.entry(name.clone()).or_insert_with(|| by.clone());
557 }
558 }
559 parser.set_defined_before(before);
560 }
561 let mut prog = parser.parse_top();
562 let mut found = pp.take_diagnostics();
563 for diagnostic in &mut found {
564 crate::wording::for_hexicon(diagnostic);
565 crate::wording::suggest_name(diagnostic, &prog.globals);
566 }
567 for warning in std::mem::take(&mut first_warnings[index]) {
569 if !found.contains(&warning) {
570 compiled.diagnostics.push(warning);
571 }
572 }
573 compiled.diagnostics.extend(found);
574 module_macros.push(pp.link_macros());
575 if has_errors(&compiled.diagnostics) {
576 return compiled;
577 }
578 if let Some((Some(reading), _)) = documenting.as_mut().map(|(r, d)| (&mut **r, d)) {
581 let names = pp.file_names();
582 reading.add(&prog, &names, from_library(index), pp.files());
583 }
584
585 if checks_names {
586 names.add(
587 crate::names::collect(&prog),
588 !from_library(index),
589 from_library(index),
590 &|file| pp.file_name(file).to_owned(),
591 );
592 }
593 prog.from_library = from_library(index);
594 let mut generated = emit::generate(
595 &mut prog,
596 options.debug,
597 options.line_records || options.debug,
598 source_files.len(),
599 );
600 source_files.extend(pp.file_names());
601 for diagnostic in std::mem::take(&mut generated.diagnostics) {
602 let meant = diagnostic.meant.clone();
603 let file = if diagnostic.file == usize::MAX || diagnostic.line == 0 {
606 String::new()
607 } else {
608 pp.file_name(diagnostic.file).to_owned()
609 };
610 let mut diagnostic = Diagnostic {
611 file,
612 line: diagnostic.line,
613 severity: diagnostic.severity,
614 message: diagnostic.message,
615 ..Default::default()
616 };
617 crate::wording::for_hexicon(&mut diagnostic);
618 crate::wording::suggest_name(&mut diagnostic, &prog.globals);
619 if let Some(meant) = &meant {
620 diagnostic.note = Some(format!(
621 "did you mean \"{}\"?",
622 String::from_utf8_lossy(meant)
623 ));
624 }
625 compiled.diagnostics.push(diagnostic);
626 }
627 if has_errors(&compiled.diagnostics) {
628 return compiled;
629 }
630 let object_file = source
633 .rsplit(['/', '\\'])
634 .next()
635 .unwrap_or(source)
636 .to_owned();
637 modules.push(Module {
638 prog,
639 out: generated,
640 object_file,
641 });
642 }
643
644 if let Some((reading, documented)) = documenting.take()
646 && let Some(reading) = reading.take()
647 {
648 *documented = Some(reading.finish(files));
649 }
650 compiled.diagnostics.extend(names.warnings());
651 let texts: Vec<String> = if options.text_tags.is_empty()
654 && options.object_tags.is_empty()
655 && options.object_keys.is_empty()
656 && options.ifid.is_none()
657 {
658 Vec::new()
659 } else {
660 sources
661 .iter()
662 .map(|source| {
663 files
664 .read(source)
665 .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
666 .unwrap_or_default()
667 })
668 .collect()
669 };
670 if !options.text_tags.is_empty() {
671 let mut known: std::collections::HashSet<String> =
672 options.text_tags.iter().cloned().collect();
673 for text in &texts {
674 known.extend(crate::tags::tags_defined(text));
675 }
676 for (index, source) in sources.iter().enumerate() {
677 if !from_library(index) {
678 compiled
679 .diagnostics
680 .extend(crate::tags::check(source, &texts[index], &known));
681 }
682 }
683 }
684 if let Some(property) = &options.ifid {
686 let own: Vec<(&str, &str)> = sources
687 .iter()
688 .enumerate()
689 .filter(|(index, _)| !from_library(*index))
690 .map(|(index, source)| (*source, texts[index].as_str()))
691 .collect();
692 compiled
693 .diagnostics
694 .extend(crate::ifid::check(&own, property));
695 }
696 let note = |compiled: &mut Compiled, severity: Severity, message: String| {
699 compiled.diagnostics.push(Diagnostic {
700 file: String::new(),
701 line: 0,
702 severity,
703 message,
704 ..Default::default()
705 });
706 };
707 let Linked {
708 mut prog,
709 out,
710 enum_ids,
711 errors,
712 } = link::link(modules);
713 if !errors.is_empty() {
716 for message in errors {
717 note(&mut compiled, Severity::Error, message);
718 }
719 return compiled;
720 }
721 if !options.object_tags.is_empty() || !options.object_keys.is_empty() {
724 let objects: std::collections::HashSet<&[u8]> = prog
725 .globals
726 .names()
727 .filter(|name| matches!(prog.globals.peek(name), Some(Global::Obj(_))))
728 .collect();
729 let tag_names: std::collections::HashSet<String> =
730 options.object_tags.iter().cloned().collect();
731 for (index, source) in sources.iter().enumerate() {
732 if !from_library(index) {
733 compiled.diagnostics.extend(crate::tags::check_objects(
734 source,
735 &texts[index],
736 &tag_names,
737 &options.object_keys,
738 &objects,
739 ));
740 }
741 }
742 if has_errors(&compiled.diagnostics) {
743 return compiled;
744 }
745 }
746 let mut generated = emit::link_generate(&mut prog, out, enum_ids.clone());
747 for name in emit::unresolved_externs(&prog, &generated) {
748 let message = if name.as_slice() == b"main" {
750 "the program has no main(args) function, which the system library calls \
751 when it starts"
752 .to_owned()
753 } else {
754 format!(
755 "unresolved external reference \"{}\"",
756 crate::pp::show_name(&name)
757 )
758 };
759 note(&mut compiled, Severity::Error, message);
760 }
761 let has_main = matches!(
763 prog.globals.peek(b"_main".as_slice()),
764 Some(Global::Func(func)) if generated.func_anchor.contains_key(func)
765 );
766 if !has_main && prog.globals.peek(b"_main".as_slice()).is_none() {
767 note(
768 &mut compiled,
769 Severity::Error,
770 "function _main() is not defined: a program built without the system \
771 library (--no-system) has to define its own"
772 .to_owned(),
773 );
774 return compiled;
775 }
776 let exports = emit::resolve_exports(&prog, &mut generated);
777 for (severity, message) in exports.problems {
778 note(&mut compiled, severity, message);
779 }
780 for (name, id) in exports.assumed_props {
781 prog.add_assumed_prop(name, id);
782 }
783 if has_errors(&compiled.diagnostics) {
784 return compiled;
785 }
786 for message in std::mem::take(&mut generated.link_errors) {
789 note(&mut compiled, Severity::Error, message);
790 }
791 if has_errors(&compiled.diagnostics) {
792 return compiled;
793 }
794
795 let table = link_macro_table(options, module_macros);
796 let debug = options.debug.then(|| {
797 let (macros, macros_unspecified) = debug_macros(&table);
798 image::DebugRecords {
799 enum_ids: enum_ids.clone(),
800 macros,
801 macros_unspecified,
802 }
803 });
804 match image::write_image(
805 &prog,
806 generated,
807 &options.timestamp,
808 &TOOL_DATA,
809 if options.line_records || options.debug {
810 &source_files
811 } else {
812 &[]
813 },
814 debug.as_ref(),
815 ) {
816 Ok(image) => {
817 compiled.symbols = runtime_symbols(&prog, &enum_ids, &image.func_addrs);
818 compiled.macros = table.macros.into_iter().map(|(mac, _)| mac).collect();
819 compiled.image = Some(image.bytes);
820 compiled.unspecified = image.unspecified;
821 }
822 Err(message) => note(&mut compiled, Severity::Error, message),
823 }
824 compiled
825}
826
827fn runtime_symbols(
831 prog: &crate::parse::Program,
832 enum_ids: &[u32],
833 func_addrs: &std::collections::HashMap<usize, u32>,
834) -> Vec<RuntimeSymbol> {
835 prog.globals
836 .in_table_order()
837 .into_iter()
838 .filter_map(|(name, global)| {
839 let value = match global {
840 Global::Func(func) => RuntimeValue::Function(*func_addrs.get(&func)?),
841 Global::Obj(obj) => RuntimeValue::Object(prog.objs[obj].id),
842 Global::Prop(prop) => RuntimeValue::Property(prog.props[prop].id),
843 Global::Enum(sym) => RuntimeValue::Enum(*enum_ids.get(sym)?),
844 Global::Bif(bif) => RuntimeValue::BuiltIn {
845 set: prog.bifs[bif].set as u16,
846 index: prog.bifs[bif].index as u16,
847 },
848 Global::Meta(meta) => RuntimeValue::Class(prog.metas[meta].obj_id),
849 Global::DynLocal(_) => return None,
851 };
852 Some(RuntimeSymbol {
853 name: name.to_vec(),
854 value,
855 })
856 })
857 .collect()
858}