Error on imports with keyword names

This commit is contained in:
Noam Zaks 2025-06-14 23:35:59 +03:00
parent 64d0a564bf
commit 39b3d94bee
6 changed files with 26 additions and 4 deletions

View File

@ -85,6 +85,10 @@ impl Eval for ast::ModuleImport<'_> {
source_span, "module name would not be a valid identifier";
hint: "you can rename the import with `as`",
),
Err(BareImportError::Keyword(name)) => bail!(
source_span, "module `{name}` would be overridden as a keyword";
hint: "you can rename the import with `as`",
),
// Bad package spec would have failed the import already.
Err(BareImportError::PackageInvalid) => unreachable!(),
}

View File

@ -86,7 +86,7 @@ use ecow::EcoString;
use unscanny::Scanner;
use crate::package::PackageSpec;
use crate::{is_ident, is_newline, Span, SyntaxKind, SyntaxNode};
use crate::{is_ident, is_keyword, is_newline, Span, SyntaxKind, SyntaxNode};
/// A typed AST node.
pub trait AstNode<'a>: Sized {
@ -2223,6 +2223,10 @@ impl<'a> ModuleImport<'a> {
return Err(BareImportError::PathInvalid);
}
if is_keyword(&name) {
return Err(BareImportError::Keyword(name));
}
Ok(name)
}
_ => Err(BareImportError::Dynamic),
@ -2240,13 +2244,15 @@ impl<'a> ModuleImport<'a> {
}
/// Reasons why a bare name cannot be determined for an import source.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum BareImportError {
/// There is no statically resolvable binding name.
Dynamic,
/// The import source is not a valid path or the path stem not a valid
/// identifier.
PathInvalid,
/// The import source is a valid path but the path stem is a keyword.
Keyword(EcoString),
/// The import source is not a valid package spec.
PackageInvalid,
}

View File

@ -1063,6 +1063,12 @@ pub fn is_ident(string: &str) -> bool {
.is_some_and(|c| is_id_start(c) && chars.all(is_id_continue))
}
/// Whether a string is a Typst keyword.
#[inline]
pub fn is_keyword(string: &str) -> bool {
keyword(string).is_some()
}
/// Whether a character can start an identifier.
#[inline]
pub fn is_id_start(c: char) -> bool {

View File

@ -20,8 +20,8 @@ pub use self::file::FileId;
pub use self::highlight::{highlight, highlight_html, Tag};
pub use self::kind::SyntaxKind;
pub use self::lexer::{
is_id_continue, is_id_start, is_ident, is_newline, is_valid_label_literal_id,
link_prefix, split_newlines,
is_id_continue, is_id_start, is_ident, is_keyword, is_newline,
is_valid_label_literal_id, link_prefix, split_newlines,
};
pub use self::lines::Lines;
pub use self::node::{LinkedChildren, LinkedNode, Side, SyntaxError, SyntaxNode};

View File

@ -483,3 +483,8 @@ This is never reached.
--- import-from-file-package-lookalike ---
// Error: 9-28 file not found (searched at tests/suite/scripting/#test/mypkg:1.0.0)
#import "#test/mypkg:1.0.0": *
--- import-keyword ---
// Error: 9-26 module `set` would be overridden as a keyword
// Hint: 9-26 you can rename the import with `as`
#import "modules/set.typ"

View File

@ -0,0 +1 @@
// SKIP