diff --git a/self_hosted/main.jou b/self_hosted/main.jou index e2b43ab3..e2618f59 100644 --- a/self_hosted/main.jou +++ b/self_hosted/main.jou @@ -235,6 +235,9 @@ class Compiler: if strcmp(self->files[isrc].ast.path, imp->resolved_path) == 0: src = &self->files[isrc] break + if src == dest: + fail(imp->location, "the file itself cannot be imported") + assert src != NULL for exp = src->pending_exports; exp->name[0] != '\0'; exp++: diff --git a/src/main.c b/src/main.c index 190b6899..6540083b 100644 --- a/src/main.c +++ b/src/main.c @@ -365,12 +365,13 @@ static void add_imported_symbol(struct FileState *fs, const ExportSymbol *es, As static void add_imported_symbols(struct CompileState *compst) { - // TODO: should it be possible for a file to import from itself? - // Should fail with error? for (struct FileState *to = compst->files.ptr; to < End(compst->files); to++) { for (AstImport *imp = to->ast.imports.ptr; imp < End(to->ast.imports); imp++) { struct FileState *from = find_file(compst, imp->resolved_path); assert(from); + if (from == to) { + fail_with_error(imp->location, "the file itself cannot be imported"); + } for (struct ExportSymbol *es = from->pending_exports; es->name[0]; es++) { if (command_line_args.verbosity >= 2) { diff --git a/tests/other_errors/import_it_self.jou b/tests/other_errors/import_it_self.jou new file mode 100644 index 00000000..231161c4 --- /dev/null +++ b/tests/other_errors/import_it_self.jou @@ -0,0 +1,4 @@ +import "./import_it_self.jou" # Error: the file itself cannot be imported + +def main() -> int: + return 0