1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! Token scanning: the big punctuation/keyword `match` and the small
//! sub-scanners it dispatches to (identifiers, env paths, dot-tokens).
use super::Lexer;
use crate::ast::Token;
impl Lexer {
/// Parse next token (without trivia handling)
/// Trivia should ONLY be managed by `lexeme()`, not by this function.
/// This matches Haskell nixfmt's `rawSymbol` which parses tokens without trivia.
pub(super) fn next_token(&mut self) -> crate::error::Result<Token> {
let _ = self.skip_hspace();
let Some(b) = self.peek_byte() else {
return Ok(Token::Sof); // Use SOF as EOF token
};
// All token-start characters are ASCII; non-ASCII falls through to the
// error arm which decodes the full codepoint for the message.
let ch = b as char;
// Nix identifiers are ASCII-only: [a-zA-Z_][a-zA-Z0-9_'-]*. Must be
// checked before the punctuation match below.
if ch.is_ascii_alphabetic() || ch == '_' {
return Ok(self.parse_ident_or_keyword());
}
match ch {
'{' => Ok(self.single(Token::BraceOpen)),
'}' => Ok(self.single(Token::BraceClose)),
'[' => Ok(self.single(Token::BrackOpen)),
']' => Ok(self.single(Token::BrackClose)),
'(' => Ok(self.single(Token::ParenOpen)),
')' => Ok(self.single(Token::ParenClose)),
'=' => Ok(self.try_two_char('=', Token::Equal, Token::Assign)),
'@' => Ok(self.single(Token::At)),
':' => Ok(self.single(Token::Colon)),
',' => Ok(self.single(Token::Comma)),
';' => Ok(self.single(Token::Semicolon)),
'?' => Ok(self.single(Token::Question)),
'.' => Ok(self.parse_dot_token()),
'+' => Ok(self.try_two_char('+', Token::Concat, Token::Plus)),
'-' => Ok(self.try_two_char('>', Token::Implies, Token::Minus)),
'*' => Ok(self.single(Token::Mul)),
'/' => Ok(self.try_two_char('/', Token::Update, Token::Div)),
'!' => Ok(self.try_two_char('=', Token::Unequal, Token::Not)),
'<' => {
if let Some(tok) = self.try_env_path() {
return Ok(tok);
}
self.advance();
Ok(match self.peek() {
Some('=') => self.single(Token::LessEqual),
Some('|') => self.single(Token::PipeBackward),
_ => Token::Less,
})
}
'>' => Ok(self.try_two_char('=', Token::GreaterEqual, Token::Greater)),
'&' => {
if self.at("&&") {
self.advance_by(2);
Ok(Token::And)
} else {
// Don't advance: keep the error span on the '&' itself.
self.err_unexpected(&["'&&'"], "'&'")
}
}
'|' => {
if self.at("||") {
self.advance_by(2);
Ok(Token::Or)
} else if self.at("|>") {
self.advance_by(2);
Ok(Token::PipeForward)
} else {
self.err_unexpected(&["'||'", "'|>'"], "'|'")
}
}
'"' => Ok(self.single(Token::DoubleQuote)),
'\'' => {
if self.at("''") {
self.advance_by(2);
Ok(Token::DoubleSingleQuote)
} else {
self.err_unexpected(&["''"], "'")
}
}
'$' => {
if self.at("${") {
self.advance_by(2);
Ok(Token::InterOpen)
} else {
self.err_unexpected(&["'${'"], "'$'")
}
}
'0'..='9' => self.parse_number(),
'~' => Ok(self.single(Token::Tilde)),
_ => {
// `ch` was derived from a single byte; for the error message
// decode the actual codepoint so multi-byte input is reported
// correctly.
let ch = self.peek().unwrap();
self.err_unexpected(&[], &format!("'{ch}'"))
}
}
}
/// Parse identifier or keyword
fn parse_ident_or_keyword(&mut self) -> Token {
// Nix identifiers are ASCII-only: [a-zA-Z_][a-zA-Z0-9_'-]*.
let len = self
.take_ascii_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'\''))
.len();
let start_byte = self.byte_pos - len;
let bytes = self.source.as_bytes();
let text = &self.source[start_byte..self.byte_pos];
// First-byte + length dispatch keeps the common "not a keyword" path
// to a single comparison instead of up to nine `memcmp`s.
match (len, bytes[start_byte]) {
(6, b'a') if text == "assert" => Token::Assert,
(4, b'e') if text == "else" => Token::Else,
(2, b'i') if text == "if" => Token::If,
(2, b'i') if text == "in" => Token::In,
(7, b'i') if text == "inherit" => Token::Inherit,
(3, b'l') if text == "let" => Token::Let,
(3, b'r') if text == "rec" => Token::Rec,
(4, b't') if text == "then" => Token::Then,
(4, b'w') if text == "with" => Token::With,
_ => Token::Identifier(text.into()),
}
}
/// `.` may start `...`, a leading-dot float, or be `Dot`.
fn parse_dot_token(&mut self) -> Token {
if self.at("...") {
self.advance_by(3);
Token::Ellipsis
} else if self.peek_ahead(1).is_some_and(|c| c.is_ascii_digit()) {
self.advance();
let mut num = String::from(".");
num.push_str(&self.consume_digits());
if let Some(exp) = self.parse_exponent() {
num.push_str(&exp);
}
Token::Float(num.into())
} else {
self.advance();
Token::Dot
}
}
/// Lex a search path (`<nixpkgs/lib>`) only if the full Nix SPATH pattern
/// `<{PATH_CHAR}+(/{PATH_CHAR}+)*>` matches at the cursor; otherwise
/// consume nothing so `<` lexes as `Less`, matching the Nix lexer's
/// maximal-munch behaviour (`a<b` is a comparison).
fn try_env_path(&mut self) -> Option<Token> {
let is_path_char =
|b: u8| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-' | b'+');
let bytes = &self.source.as_bytes()[self.byte_pos + 1..];
let mut i = 0;
loop {
let seg_start = i;
while i < bytes.len() && is_path_char(bytes[i]) {
i += 1;
}
if i == seg_start {
return None; // empty segment, e.g. `<>` or `<a//b>`
}
match bytes.get(i) {
Some(b'>') => break,
Some(b'/') => i += 1,
_ => return None,
}
}
let path = &self.source[self.byte_pos + 1..self.byte_pos + 1 + i];
let tok = Token::EnvPath(path.into());
// `<` + path + `>` is all ASCII with no newlines.
self.advance_bytes_no_newline(i + 2);
Some(tok)
}
/// Build an `UnexpectedToken` error at the current cursor.
#[cold]
fn err_unexpected<T>(&self, expected: &[&str], found: &str) -> crate::error::Result<T> {
Err(crate::error::ParseError {
span: self.current_pos(),
kind: crate::error::ErrorKind::UnexpectedToken {
expected: expected
.iter()
.map(std::string::ToString::to_string)
.collect(),
found: found.to_string(),
},
})
}
/// Helper for two-character tokens: advance and check if next char matches
/// Returns `if_match` if second char matches, otherwise `if_single`
fn try_two_char(&mut self, second: char, if_match: Token, if_single: Token) -> Token {
self.advance();
if self.peek() == Some(second) {
self.advance();
if_match
} else {
if_single
}
}
/// Advance one char and return `tok`; for trivial single-char arms in
/// `next_token`.
#[inline]
fn single(&mut self, tok: Token) -> Token {
self.advance();
tok
}
}