Skip to content

Commit

Permalink
Improve detecting modules names
Browse files Browse the repository at this point in the history
When building or checking a source file, the compiler derives its name
based on the file path. If the file is located outside of the project's
root, the name defaults to "main".

This commit improves this logic by adding an extra fallback _before_
falling back to "main". This extra fallback scans the file path for a
"src" directory and uses everything _after_ that to derive a module name
from. This makes it possible to type-check files from projects in sub
directories.

For example, with this change you can run
`inko check ./libstd/src/std/string.inko` from the `.` directory,
instead of having to `cd` into `libstd` first. Prior to this commit this
could lead to errors, as the compiler wouldn't correctly detect standard
library files as being part of the standard library, thus disallowing
the use of `_INKO.x` expressions.

Changelog: changed
  • Loading branch information
yorickpeterse committed Sep 12, 2022
1 parent 6bac7cc commit 5c57ddc
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
21 changes: 18 additions & 3 deletions compiler/src/compiler.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::codegen;
use crate::config::{Config, IMAGE_EXT, SOURCE_EXT};
use crate::config::{Config, IMAGE_EXT, SOURCE, SOURCE_EXT};
use crate::hir;
use crate::mir::{passes as mir, Mir};
use crate::modules_parser::{ModulesParser, ParsedModule};
Expand Down Expand Up @@ -236,9 +236,24 @@ impl Compiler {

fn module_name_from_path(&self, file: &Path) -> ModuleName {
file.strip_prefix(&self.state.config.source)
.or_else(|_| file.strip_prefix(&self.state.config.tests))
.ok()
.or_else(|| file.strip_prefix(&self.state.config.tests).ok())
.or_else(|| {
// This allows us to check e.g. `./libstd/src/std/string.inko`
// while the current working directory is `.`. This is useful
// when e.g. checking files using a text editor, as they would
// likely have the working directory set to `.` and not
// `./libstd`.
let mut components = file.components();

if components.any(|c| c.as_os_str() == SOURCE) {
Some(components.as_path())
} else {
None
}
})
.map(ModuleName::from_relative_path)
.unwrap_or_else(|_| ModuleName::main())
.unwrap_or_else(|| ModuleName::main())
}

fn all_source_modules(
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub const IMAGE_EXT: &str = "ibi";
pub(crate) const MAIN_MODULE: &str = "main";

/// The name of the directory containing a project's source code.
const SOURCE: &str = "src";
pub(crate) const SOURCE: &str = "src";

/// The name of the directory containing a project's unit tests.
const TESTS: &str = "test";
Expand Down

0 comments on commit 5c57ddc

Please sign in to comment.