Skip to main content

ktrs_parser/
lib.rs

1//! Port of the Kotlin compiler's PSI parser (`KotlinParsing`, `KotlinExpressionParsing`,
2//! `KDocParser`) on top of a re-implementation of IntelliJ's `PsiBuilder` semantics.
3//! See `builder` for the builder contract and `parsing` for the porting conventions.
4
5pub mod builder;
6mod kdoc;
7pub mod kt_tokens;
8pub mod parsing;
9pub mod token_set;
10
11use ktrs_syntax::Parse;
12
13pub use builder::ChameleonCache;
14
15pub use parsing::kotlin_parser::{
16    parse_block_code_fragment, parse_block_expression, parse_expression_code_fragment, parse_lambda_expression,
17    parse_type_code_fragment,
18};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum FileKind {
22    Source,
23    Script,
24}
25
26impl FileKind {
27    /// Like `KotlinParser.parse`: no extension or `.kt` is a source file, anything else a script.
28    pub fn from_file_name(name: &str) -> FileKind {
29        let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
30        match base.rsplit_once('.') {
31            None => FileKind::Source,
32            Some((_, "kt")) | Some((_, "")) => FileKind::Source,
33            Some(_) => FileKind::Script,
34        }
35    }
36}
37
38/// Parses a whole file. `text` must already have CRLF normalized to LF.
39pub fn parse_file(text: &str, kind: FileKind) -> Parse {
40    parsing::kotlin_parser::parse(text, kind)
41}
42
43/// [`parse_file`] for callers re-parsing similar text: the result is identical, but lazy blocks,
44/// lambdas and KDoc whose text was already seen with `cache` are reused instead of re-parsed.
45pub fn parse_file_cached(text: &str, kind: FileKind, cache: &mut ChameleonCache) -> Parse {
46    parsing::kotlin_parser::parse_cached(text, kind, cache)
47}