Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,283 @@
|
||||
//! 在原文给定范围内扫描词法项并保留字节位置。
|
||||
//! 数值保留原始拼写,具体类型和表示范围留给语义检查。
|
||||
|
||||
pub mod token;
|
||||
|
||||
use crate::syntax::diagnostic::Diagnostic;
|
||||
use crate::syntax::source::{Source, Span};
|
||||
use std::ops::Range;
|
||||
use token::{Kind, Token};
|
||||
|
||||
/// 错误词法项保留为 Invalid,解析器必须拒绝所属定义,不能删掉坏字符后接受程序。
|
||||
pub fn scan_with_diagnostics(
|
||||
source: &Source,
|
||||
range: Range<usize>,
|
||||
) -> (Vec<Token>, Vec<Diagnostic>, Vec<Span>) {
|
||||
let mut scanner = Scanner {
|
||||
source,
|
||||
offset: range.start,
|
||||
end: range.end,
|
||||
comments: Vec::new(),
|
||||
};
|
||||
let mut tokens = Vec::new();
|
||||
let mut diagnostics = Vec::new();
|
||||
while scanner.offset < scanner.end {
|
||||
let start = scanner.offset;
|
||||
match scanner.next() {
|
||||
Ok(Some(token)) => tokens.push(token),
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
if matches!(error.code, "L005" | "L006") {
|
||||
// 词法合同不允许跨行字符串;坏转义的剩余内容不能被当作源码。
|
||||
if matches!(source.text.as_bytes()[scanner.offset - 1], b'\n' | b'\r') {
|
||||
scanner.offset -= 1;
|
||||
}
|
||||
while scanner.peek().is_some_and(|c| c != '\n' && c != '\r') {
|
||||
scanner.advance();
|
||||
}
|
||||
}
|
||||
tokens.push(Token {
|
||||
kind: Kind::Invalid,
|
||||
span: source.span(start, scanner.offset),
|
||||
});
|
||||
diagnostics.push(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
tokens.push(Token {
|
||||
kind: Kind::End,
|
||||
span: source.span(range.end, range.end),
|
||||
});
|
||||
(tokens, diagnostics, scanner.comments)
|
||||
}
|
||||
|
||||
struct Scanner<'source> {
|
||||
source: &'source Source,
|
||||
offset: usize,
|
||||
end: usize,
|
||||
comments: Vec<Span>,
|
||||
}
|
||||
|
||||
impl Scanner<'_> {
|
||||
fn next(&mut self) -> Result<Option<Token>, Diagnostic> {
|
||||
while let Some(character) = self.peek() {
|
||||
let start = self.offset;
|
||||
let kind = match character {
|
||||
' ' | '\t' => {
|
||||
self.advance();
|
||||
continue;
|
||||
}
|
||||
'#' => {
|
||||
let remaining = &self.source.text[start..self.end];
|
||||
self.offset += remaining.find(['\r', '\n']).unwrap_or(remaining.len());
|
||||
self.comments.push(self.source.span(start, self.offset));
|
||||
continue;
|
||||
}
|
||||
'/' if self.source.text[start..self.end].starts_with("/*") => {
|
||||
let Some(close) = self.source.text[start + 2..self.end].find("*/") else {
|
||||
self.offset = self.end;
|
||||
return Err(Diagnostic::new(
|
||||
"L007",
|
||||
"unclosed block comment",
|
||||
self.source.span(start, start + 2),
|
||||
));
|
||||
};
|
||||
self.offset = start + close + 4;
|
||||
self.comments.push(self.source.span(start, self.offset));
|
||||
continue;
|
||||
}
|
||||
'\r' | '\n' => {
|
||||
self.advance();
|
||||
if character == '\r' && self.peek() == Some('\n') {
|
||||
self.advance();
|
||||
}
|
||||
Kind::Newline
|
||||
}
|
||||
'"' => Kind::Text(self.text()?),
|
||||
'0'..='9' => Kind::Number(self.number()?),
|
||||
'a'..='z' | 'A'..='Z' | '_' => {
|
||||
while self
|
||||
.peek()
|
||||
.is_some_and(|value| value.is_ascii_alphanumeric() || value == '_')
|
||||
{
|
||||
self.advance();
|
||||
}
|
||||
let name = &self.source.text[start..self.offset];
|
||||
if matches!(
|
||||
name,
|
||||
"if" | "for"
|
||||
| "while"
|
||||
| "return"
|
||||
| "function"
|
||||
| "import"
|
||||
| "use"
|
||||
| "unsafe"
|
||||
| "match"
|
||||
| "switch"
|
||||
| "try"
|
||||
| "throw"
|
||||
| "catch"
|
||||
| "class"
|
||||
| "interface"
|
||||
| "macro"
|
||||
| "async"
|
||||
| "await"
|
||||
) {
|
||||
return Err(Diagnostic::new(
|
||||
"L003",
|
||||
format!("'{name}' is not Dever syntax"),
|
||||
self.source.span(start, self.offset),
|
||||
));
|
||||
}
|
||||
Kind::Name(name.to_owned())
|
||||
}
|
||||
_ => {
|
||||
let remaining = &self.source.text[start..self.end];
|
||||
let symbol = [
|
||||
"=>", "==", "!=", "<=", ">=", "//", "(", ")", "{", "}", "[", "]", ":", ",",
|
||||
".", "?", "=", "+", "-", "*", "/", "%", "<", ">", "|",
|
||||
]
|
||||
.into_iter()
|
||||
.find(|symbol| remaining.starts_with(symbol));
|
||||
match symbol {
|
||||
Some(symbol) => {
|
||||
self.offset += symbol.len();
|
||||
Kind::Symbol(symbol)
|
||||
}
|
||||
None => {
|
||||
self.advance();
|
||||
return Err(Diagnostic::new(
|
||||
"L001",
|
||||
format!("unexpected character '{character}'"),
|
||||
self.source.span(start, start + character.len_utf8()),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
return Ok(Some(Token {
|
||||
kind,
|
||||
span: self.source.span(start, self.offset),
|
||||
}));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<char> {
|
||||
self.source.text[self.offset..self.end].chars().next()
|
||||
}
|
||||
|
||||
fn advance(&mut self) -> Option<char> {
|
||||
let character = self.peek()?;
|
||||
self.offset += character.len_utf8();
|
||||
Some(character)
|
||||
}
|
||||
|
||||
fn number(&mut self) -> Result<String, Diagnostic> {
|
||||
let start = self.offset;
|
||||
self.digits()?;
|
||||
if self.peek() == Some('.')
|
||||
&& self.source.text[self.offset + 1..self.end]
|
||||
.starts_with(|value: char| value.is_ascii_digit())
|
||||
{
|
||||
self.advance();
|
||||
self.digits()?;
|
||||
}
|
||||
if matches!(self.peek(), Some('e' | 'E')) {
|
||||
self.advance();
|
||||
if matches!(self.peek(), Some('+' | '-')) {
|
||||
self.advance();
|
||||
}
|
||||
self.digits()?;
|
||||
}
|
||||
Ok(self.source.text[start..self.offset].to_owned())
|
||||
}
|
||||
|
||||
// 分隔符只能位于数字之间,避免把截断的字面量交给后续类型推断。
|
||||
fn digits(&mut self) -> Result<(), Diagnostic> {
|
||||
let start = self.offset;
|
||||
if !self.peek().is_some_and(|value| value.is_ascii_digit()) {
|
||||
return Err(Diagnostic::new(
|
||||
"L004",
|
||||
"expected digits",
|
||||
self.source.span(start, start),
|
||||
));
|
||||
}
|
||||
self.advance();
|
||||
loop {
|
||||
match self.peek() {
|
||||
Some('0'..='9') => {
|
||||
self.advance();
|
||||
}
|
||||
Some('_') => {
|
||||
let separator = self.offset;
|
||||
self.advance();
|
||||
if !self.peek().is_some_and(|value| value.is_ascii_digit()) {
|
||||
return Err(Diagnostic::new(
|
||||
"L004",
|
||||
"numeric separator must be between digits",
|
||||
self.source.span(separator, self.offset),
|
||||
));
|
||||
}
|
||||
self.advance();
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn text(&mut self) -> Result<String, Diagnostic> {
|
||||
let start = self.offset;
|
||||
self.advance();
|
||||
let mut output = String::new();
|
||||
while let Some(character) = self.advance() {
|
||||
match character {
|
||||
'"' => return Ok(output),
|
||||
'\n' | '\r' => {
|
||||
self.offset -= character.len_utf8();
|
||||
break;
|
||||
}
|
||||
'\\' => {
|
||||
let escaped = match self.advance() {
|
||||
Some('n') => '\n',
|
||||
Some('r') => '\r',
|
||||
Some('t') => '\t',
|
||||
Some('"') => '"',
|
||||
Some('\\') => '\\',
|
||||
Some('u') if self.advance() == Some('{') => {
|
||||
let begin = self.offset;
|
||||
while self.peek().is_some_and(|value| value.is_ascii_hexdigit()) {
|
||||
self.advance();
|
||||
}
|
||||
let hex = &self.source.text[begin..self.offset];
|
||||
let scalar = u32::from_str_radix(hex, 16).ok().and_then(char::from_u32);
|
||||
if hex.len() > 6 || self.advance() != Some('}') || scalar.is_none() {
|
||||
return Err(Diagnostic::new(
|
||||
"L006",
|
||||
"invalid Unicode escape",
|
||||
self.source.span(begin, self.offset),
|
||||
));
|
||||
}
|
||||
scalar.unwrap()
|
||||
}
|
||||
_ => {
|
||||
return Err(Diagnostic::new(
|
||||
"L006",
|
||||
"invalid text escape",
|
||||
self.source.span(start, self.offset),
|
||||
));
|
||||
}
|
||||
};
|
||||
output.push(escaped);
|
||||
}
|
||||
_ => output.push(character),
|
||||
}
|
||||
}
|
||||
Err(Diagnostic::new(
|
||||
"L005",
|
||||
"unclosed text literal",
|
||||
self.source.span(start, self.offset),
|
||||
))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user