Add token-based PEG frontend and CLI source parsing
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m30s
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m30s
This commit is contained in:
+3
-2
@@ -5,11 +5,12 @@
|
||||
| 目录 | 包名/产物 | 职责 |
|
||||
| --- | --- | --- |
|
||||
| [core](core/README.md) | core,库 endor_core | 零外部依赖的对象运行时、堆与字节码 VM |
|
||||
| [frontend](frontend/README.md) | frontend | 手写 lexer、token PEG parser、基础函数/表达式 AST,不执行源码 |
|
||||
| [host](host/README.md) | host | UTF-8 JSON 文件基础信息,与数据库分离 |
|
||||
| [storage](storage/README.md) | storage | 为数据库特殊类保留的显式连接适配,不提供基础信息存储 |
|
||||
| [cli](cli/README.md) | cli,二进制 cli | 引导演示与文件信息命令,不使用数据库 |
|
||||
| [cli](cli/README.md) | cli,二进制 cli | 引导演示、源码解析与文件信息命令,不使用数据库 |
|
||||
| [server](server/README.md) | server,二进制 server | HTTP 宿主与文件版本信息,不使用数据库 |
|
||||
|
||||
CLI 和 Server 依赖 Core 与 Host,不依赖 Storage;Core 与 Storage 也互不依赖。未来特殊类的宿主实现按需依赖 Storage,见 [数据库对象](../docs/runtime/database-objects.md)。
|
||||
CLI 依赖 Core、Frontend 与 Host,Server 依赖 Core 与 Host,二者不依赖 Storage;Frontend 依赖 peg,不依赖 Core;Core 与 Storage 也互不依赖。未来特殊类的宿主实现按需依赖 Storage,见 [数据库对象](../docs/runtime/database-objects.md)。
|
||||
|
||||
core 的 Rust 库名为 endor_core,避免与标准库 core 重名,见 [Cargo 目标说明](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-name-field)。网络、数据库、进程配置和信号不进入 Core。全局说明见 [架构](../docs/architecture/README.md),返回 [项目入口](../README.md)。
|
||||
|
||||
@@ -11,6 +11,7 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
core.workspace = true
|
||||
frontend.workspace = true
|
||||
host.workspace = true
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# cli
|
||||
|
||||
同步命令行宿主,提供 bootstrap、help 和文件 metadata 命令。bootstrap 演示两个运行时对象并释放,不读取数据库配置、不连接或写入数据库。
|
||||
同步命令行宿主,提供 bootstrap、parse、help 和文件 metadata 命令。bootstrap 演示两个运行时对象并释放,不读取数据库配置、不连接或写入数据库。
|
||||
|
||||
| 内容 | 职责 |
|
||||
| --- | --- |
|
||||
| Cargo.toml | cli 二进制与 core/host 依赖;无 storage 或 Tokio 依赖 |
|
||||
| [src](src/README.md) | 参数路由、引导演示和退出码 |
|
||||
| Cargo.toml | cli 二进制与 core/frontend/host 依赖;无 storage 或 Tokio 依赖 |
|
||||
| [src](src/README.md) | 参数路由、引导演示、源码解析和退出码 |
|
||||
| [tests](tests/README.md) | parse 命令的 AST 输出、错误位置和严格 UTF-8 检查 |
|
||||
|
||||
运行方式见 [运行指南](../../docs/operations/README.md),输入边界见 [配置](../../docs/operations/configuration.md)。当前不是 Endor 源码解释命令,metadata put/get 和只导入缺失项的 import 均使用文件,见 [宿主信息](../../docs/operations/host-information.md)。返回 [工作区](../README.md)。
|
||||
运行方式见 [运行指南](../../docs/operations/README.md),输入边界见 [配置](../../docs/operations/configuration.md)。parse 严格读取 UTF-8 文件并输出 AST,不执行源码,见 [前端](../../docs/runtime/frontend.md);metadata put/get 和只导入缺失项的 import 均使用文件,见 [宿主信息](../../docs/operations/host-information.md)。返回 [工作区](../README.md)。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# CLI 入口
|
||||
|
||||
[main.rs](main.rs) 是唯一入口:同步 main 将 run 的结果转成进程退出码;run 处理 bootstrap、help、文件 metadata put/get/import,错误打印到 stderr 并返回失败。
|
||||
[main.rs](main.rs) 是唯一入口:同步 main 将 run 的结果转成进程退出码;run 处理 bootstrap、parse 文件、help、文件 metadata put/get/import,错误打印到 stderr 并返回失败。
|
||||
|
||||
bootstrap 创建并显式释放两个对象,不读取数据库环境、不打开数据库。未知命令报错;metadata 通过 host::MetadataStore 读写文件,import 从标准输入接收旧记录且不覆盖已有文件。参数目前由 std::env::args 读取,非 Unicode 参数可能 panic,边界见 [配置](../../../docs/operations/configuration.md)。
|
||||
bootstrap 创建并显式释放两个对象,不读取数据库环境、不打开数据库。parse 使用 frontend 输出 AST,词法/语法错误显示文件、行、列;不创建 VM 或执行源码。未知命令报错;metadata 通过 host::MetadataStore 读写文件,import 从标准输入接收旧记录且不覆盖已有文件。参数目前由 std::env::args 读取,非 Unicode 参数可能 panic,边界见 [配置](../../../docs/operations/configuration.md)。
|
||||
|
||||
新增命令时更新用法、[运行指南](../../../docs/operations/README.md) 和 [smoke.py 的导航](../../../scripts/README.md)。返回 [cli](../README.md)。
|
||||
|
||||
+13
-1
@@ -4,7 +4,7 @@ use std::process::ExitCode;
|
||||
use endor_core::{Value, Vm};
|
||||
use host::MetadataStore;
|
||||
|
||||
const USAGE: &str = "Usage: cli [bootstrap | metadata put <key> <value> | metadata get <key> | metadata import | help]";
|
||||
const USAGE: &str = "Usage: cli [bootstrap | parse <file> | metadata put <key> <value> | metadata get <key> | metadata import | help]";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
@@ -45,6 +45,18 @@ fn run() -> Result<(), Box<dyn Error>> {
|
||||
println!("bootstrap uses no database");
|
||||
}
|
||||
["help"] | ["--help"] | ["-h"] => println!("{USAGE}"),
|
||||
["parse", path] => {
|
||||
let source =
|
||||
std::fs::read_to_string(path).map_err(|error| format!("{path}: {error}"))?;
|
||||
let program = frontend::parse(&source).map_err(|error| {
|
||||
let location = error.location(&source);
|
||||
format!(
|
||||
"{path}:{}:{}: {}",
|
||||
location.line, location.column, error.message
|
||||
)
|
||||
})?;
|
||||
println!("{program:#?}");
|
||||
}
|
||||
["metadata", "put", key, value] => {
|
||||
MetadataStore::from_env()?.put(key, value)?;
|
||||
println!("stored (file)");
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# CLI 命令检查
|
||||
|
||||
[parse.rs](parse.rs) 使用 Cargo 提供的 cli 测试二进制检查 parse 命令:合法 UTF-8 源码输出 AST 且不执行名称调用;非法语法输出文件/行/列并返回失败;非法 UTF-8 不替换字符。
|
||||
|
||||
测试仅在 ces-control 的工作区检查中运行,本地不执行。测试临时文件使用独立名称并在结束时清理。返回 [cli](../README.md),验证约定见 [验证](../../../docs/operations/validation.md)。
|
||||
@@ -0,0 +1,67 @@
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static NEXT_FILE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct SourceFile(PathBuf);
|
||||
|
||||
impl SourceFile {
|
||||
fn new(content: &[u8]) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"aster-parse-{}-{}.endor",
|
||||
std::process::id(),
|
||||
NEXT_FILE.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
std::fs::write(&path, content).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SourceFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_command_prints_ast_without_executing_source() {
|
||||
let source = SourceFile::new("function 表示(): String { return 未定義() }".as_bytes());
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_cli"))
|
||||
.arg("parse")
|
||||
.arg(&source.0)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8(output.stdout).unwrap();
|
||||
assert!(stdout.contains("表示"));
|
||||
assert!(stdout.contains("未定義"));
|
||||
assert!(stdout.contains("Call"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_command_reports_source_locations_and_rejects_invalid_utf8() {
|
||||
let source = SourceFile::new(b"function f(): Number {\n return )\n}");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_cli"))
|
||||
.arg("parse")
|
||||
.arg(&source.0)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let stderr = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(stderr.contains(":2:10:"), "{stderr}");
|
||||
assert!(stderr.contains("expected"));
|
||||
let source = SourceFile::new(&[0xff]);
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_cli"))
|
||||
.arg("parse")
|
||||
.arg(&source.0)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
}
|
||||
@@ -8,6 +8,6 @@ Endor VM 内核,保持零外部依赖。负责 EndorObject、堆、代际句
|
||||
| [src](src/README.md) | 文件职责、公开接口和常见修改位置 |
|
||||
| [tests](tests/README.md) | 对象、基本载荷、执行语义与生命周期检查 |
|
||||
|
||||
内核通过 Vm::new 从空堆启动;代码对象和全局字典由宿主显式创建,再 execute/call。没有环境变量探测、数据库、HTTP、Python type 系统或源码前端。
|
||||
内核通过 Vm::new 从空堆启动;代码对象和全局字典由宿主显式创建,再 execute/call。内核没有环境变量探测、数据库、HTTP、Python type 系统或源码解析;源码 lexer/parser 在独立 [frontend](../frontend/README.md) 包中,尚未接入字节码编译。
|
||||
|
||||
对象结果所有权见 [生命周期](../../docs/runtime/lifecycle.md),对象/字节码设计见 [运行时](../../docs/runtime/README.md),限额与 UTF-8 边界见 [配置](../../docs/operations/configuration.md)。本地不构建或运行测试,验证入口见 [验证](../../docs/operations/validation.md)。返回 [工作区](../README.md)。
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "frontend"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
peg.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,12 @@
|
||||
# frontend
|
||||
|
||||
独立源码前端:手写 Rust lexer → token → rust-peg parser → 拥有文本的 AST。当前解析基础函数与表达式,不生成字节码、不进行类型/名称解析、不执行源码。语法是可继续调整的首版实现,当前契约见 [源码前端](../../docs/runtime/frontend.md)。
|
||||
|
||||
| 内容 | 职责 |
|
||||
| --- | --- |
|
||||
| Cargo.toml | frontend 包与 peg 0.8.6 依赖,不依赖 core、Host 或 Storage |
|
||||
| [src](src/README.md) | token、源码范围、诊断、AST、词法与 PEG 规则 |
|
||||
| [tests](tests/README.md) | Unicode、优先级、函数、完整输入与错误位置验证 |
|
||||
| [examples](examples/README.md) | 可交给 cli parse 的源码样例 |
|
||||
|
||||
公开入口为 lex、parse、parse_expression;CLI 文件读取在宿主层。Core 仍为零外部依赖;未来编译器将 AST 转成已有字节码,不改为 AST 直接解释。返回 [工作区](../README.md)。
|
||||
@@ -0,0 +1,5 @@
|
||||
# Frontend 源码样例
|
||||
|
||||
[basic.endor](basic.endor) 包含字符串函数、位置参数、let 绑定、return 与算术表达式。它展示当前能解析的源码,不表示已能编译和执行运算。
|
||||
|
||||
在指定远端环境使用 `cli parse crates/frontend/examples/basic.endor` 输出 AST;工作区运行方法见 [运行指南](../../../docs/operations/README.md)。syntax.rs 包含此样例的解析检查。返回 [frontend](../README.md)。
|
||||
@@ -0,0 +1,9 @@
|
||||
// Parsing produces an AST; it does not execute these functions.
|
||||
function echo(text: String): String {
|
||||
let result = text
|
||||
return result
|
||||
}
|
||||
|
||||
function discountedPrice(price: Number, discount: Number): Number {
|
||||
return price - discount
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# Frontend 源码
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | 公开 AST 模块、lex/parse/parse_expression 与 token、诊断导出 |
|
||||
| [token.rs](token.rs) | 可复制的 token 种类和原始源码范围,文本由源码切片取得 |
|
||||
| [diagnostic.rs](diagnostic.rs) | UTF-8 字节范围、词法/语法诊断与一基行列转换 |
|
||||
| [lexer.rs](lexer.rs) | 名称、数字、字符串、标点、空白与注释扫描;字符串校验及解码 |
|
||||
| [ast.rs](ast.rs) | 拥有文本的函数、参数、绑定、return、表达式与运算符结构 |
|
||||
| [parser.rs](parser.rs) | token 输入的 peg::parser! 规则、优先级、AST 构造及错误映射 |
|
||||
|
||||
改词法时同步 token 和错误检查;改语法时同步 AST、PEG 规则、[测试](../tests/README.md)、样例与 [前端契约](../../../docs/runtime/frontend.md)。不在语法动作中做 VM 分配、I/O 或修改外部状态,避免回溯造成副作用。返回 [frontend](../README.md)。
|
||||
@@ -0,0 +1,90 @@
|
||||
use crate::Span;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Name {
|
||||
pub text: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Program {
|
||||
pub functions: Vec<Function>,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Function {
|
||||
pub name: Name,
|
||||
pub parameters: Vec<Parameter>,
|
||||
pub return_type: Name,
|
||||
pub body: Block,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Parameter {
|
||||
pub name: Name,
|
||||
pub type_name: Name,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
/// Basic draft function body: zero or more bindings and one final return.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Block {
|
||||
pub bindings: Vec<Binding>,
|
||||
pub result: Expr,
|
||||
pub return_span: Span,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Binding {
|
||||
pub name: Name,
|
||||
pub value: Expr,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Expr {
|
||||
pub kind: ExprKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ExprKind {
|
||||
Name(String),
|
||||
/// The decimal spelling is retained, without f64 conversion.
|
||||
Number(String),
|
||||
String(String),
|
||||
Symbol(Name),
|
||||
Unary {
|
||||
operation: UnaryOp,
|
||||
operand: Box<Expr>,
|
||||
},
|
||||
Binary {
|
||||
operation: BinaryOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>,
|
||||
},
|
||||
Member {
|
||||
object: Box<Expr>,
|
||||
name: Name,
|
||||
},
|
||||
Call {
|
||||
callee: Box<Expr>,
|
||||
arguments: Vec<Expr>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UnaryOp {
|
||||
Negate,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BinaryOp {
|
||||
Add,
|
||||
Subtract,
|
||||
Multiply,
|
||||
Divide,
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
/// Half-open UTF-8 byte range in the original source, including trivia between
|
||||
/// the first and last syntax token. EOF has an empty range at source.len().
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Span {
|
||||
pub const fn new(start: usize, end: usize) -> Self {
|
||||
Self { start, end }
|
||||
}
|
||||
|
||||
pub(crate) fn through(self, last: Self) -> Self {
|
||||
Self::new(self.start, last.end)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DiagnosticKind {
|
||||
Lexical,
|
||||
Syntax,
|
||||
}
|
||||
|
||||
/// Lines and Unicode scalar columns are one-based. CRLF counts as one newline.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SourceLocation {
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Diagnostic {
|
||||
pub kind: DiagnosticKind,
|
||||
pub span: Span,
|
||||
pub message: String,
|
||||
pub expected: Vec<String>,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub(crate) fn lexical(span: Span, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: DiagnosticKind::Lexical,
|
||||
span,
|
||||
message: message.into(),
|
||||
expected: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn location(&self, source: &str) -> SourceLocation {
|
||||
let mut location = SourceLocation { line: 1, column: 1 };
|
||||
let mut previous_cr = false;
|
||||
for (offset, character) in source.char_indices() {
|
||||
if offset >= self.span.start {
|
||||
break;
|
||||
}
|
||||
match character {
|
||||
'\r' => {
|
||||
location.line += 1;
|
||||
location.column = 1;
|
||||
}
|
||||
'\n' if previous_cr => {}
|
||||
'\n' => {
|
||||
location.line += 1;
|
||||
location.column = 1;
|
||||
}
|
||||
_ => location.column += 1,
|
||||
}
|
||||
previous_cr = character == '\r';
|
||||
}
|
||||
location
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Diagnostic {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"{} at bytes {}..{}",
|
||||
self.message, self.span.start, self.span.end
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for Diagnostic {}
|
||||
@@ -0,0 +1,183 @@
|
||||
use crate::{Diagnostic, Span, Token, TokenKind};
|
||||
|
||||
/// Lex the basic Endorphin draft syntax without reading files or changing
|
||||
/// locale. Positions always refer to bytes in this exact UTF-8 source.
|
||||
pub fn lex(source: &str) -> Result<Vec<Token>, Diagnostic> {
|
||||
let mut lexer = Lexer { source, offset: 0 };
|
||||
let mut tokens = Vec::new();
|
||||
while let Some(character) = lexer.peek() {
|
||||
if matches!(character, ' ' | '\t' | '\r' | '\n') {
|
||||
let _ = lexer.advance();
|
||||
continue;
|
||||
}
|
||||
if lexer.remaining().starts_with("//") {
|
||||
while lexer
|
||||
.peek()
|
||||
.is_some_and(|character| !matches!(character, '\r' | '\n'))
|
||||
{
|
||||
let _ = lexer.advance();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let start = lexer.offset;
|
||||
let kind = match character {
|
||||
character if name_start(character) => {
|
||||
let _ = lexer.advance();
|
||||
while lexer.peek().is_some_and(name_continue) {
|
||||
let _ = lexer.advance();
|
||||
}
|
||||
TokenKind::Name
|
||||
}
|
||||
'0'..='9' => lexer.number()?,
|
||||
'"' => lexer.string()?,
|
||||
_ => {
|
||||
let _ = lexer.advance();
|
||||
match character {
|
||||
'(' => TokenKind::LeftParen,
|
||||
')' => TokenKind::RightParen,
|
||||
'{' => TokenKind::LeftBrace,
|
||||
'}' => TokenKind::RightBrace,
|
||||
':' => TokenKind::Colon,
|
||||
',' => TokenKind::Comma,
|
||||
'.' => TokenKind::Dot,
|
||||
'=' => TokenKind::Equal,
|
||||
'+' => TokenKind::Plus,
|
||||
'-' => TokenKind::Minus,
|
||||
'*' => TokenKind::Star,
|
||||
'/' => TokenKind::Slash,
|
||||
_ => {
|
||||
return Err(Diagnostic::lexical(
|
||||
Span::new(start, lexer.offset),
|
||||
"unexpected source character",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
tokens.push(Token {
|
||||
kind,
|
||||
span: Span::new(start, lexer.offset),
|
||||
});
|
||||
}
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
struct Lexer<'source> {
|
||||
source: &'source str,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
impl<'source> Lexer<'source> {
|
||||
fn remaining(&self) -> &'source str {
|
||||
&self.source[self.offset..]
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<char> {
|
||||
self.remaining().chars().next()
|
||||
}
|
||||
|
||||
fn advance(&mut self) -> Option<char> {
|
||||
let character = self.peek()?;
|
||||
self.offset += character.len_utf8();
|
||||
Some(character)
|
||||
}
|
||||
|
||||
fn digits(&mut self) {
|
||||
while self
|
||||
.peek()
|
||||
.is_some_and(|character| character.is_ascii_digit())
|
||||
{
|
||||
let _ = self.advance();
|
||||
}
|
||||
}
|
||||
|
||||
fn number(&mut self) -> Result<TokenKind, Diagnostic> {
|
||||
let start = self.offset;
|
||||
self.digits();
|
||||
let mut following = self.remaining().chars();
|
||||
if following.next() == Some('.')
|
||||
&& following
|
||||
.next()
|
||||
.is_some_and(|character| character.is_ascii_digit())
|
||||
{
|
||||
let _ = self.advance();
|
||||
self.digits();
|
||||
}
|
||||
if self.peek().is_some_and(name_continue) {
|
||||
while self.peek().is_some_and(name_continue) {
|
||||
let _ = self.advance();
|
||||
}
|
||||
return Err(Diagnostic::lexical(
|
||||
Span::new(start, self.offset),
|
||||
"unsupported numeric suffix or missing token separator",
|
||||
));
|
||||
}
|
||||
Ok(TokenKind::Number)
|
||||
}
|
||||
|
||||
fn string(&mut self) -> Result<TokenKind, Diagnostic> {
|
||||
let start = self.offset;
|
||||
let _ = self.advance();
|
||||
loop {
|
||||
let position = self.offset;
|
||||
match self.advance() {
|
||||
Some('"') => return Ok(TokenKind::String),
|
||||
Some('\\') => match self.advance() {
|
||||
Some('n' | 't' | '"' | '\\') => {}
|
||||
Some(_) => {
|
||||
return Err(Diagnostic::lexical(
|
||||
Span::new(position, self.offset),
|
||||
"unsupported string escape",
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(Diagnostic::lexical(
|
||||
Span::new(start, self.offset),
|
||||
"unterminated string",
|
||||
));
|
||||
}
|
||||
},
|
||||
Some('\r' | '\n' | '\0') => {
|
||||
return Err(Diagnostic::lexical(
|
||||
Span::new(position, self.offset),
|
||||
"unescaped newline or NUL in string",
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(Diagnostic::lexical(
|
||||
Span::new(start, self.offset),
|
||||
"unterminated string",
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn name_start(character: char) -> bool {
|
||||
character == '_' || character.is_alphabetic()
|
||||
}
|
||||
|
||||
fn name_continue(character: char) -> bool {
|
||||
character == '_' || character.is_alphanumeric()
|
||||
}
|
||||
|
||||
pub(crate) fn decode_string(raw: &str) -> String {
|
||||
let mut result = String::new();
|
||||
let mut characters = raw.chars();
|
||||
while let Some(character) = characters.next() {
|
||||
if character == '\\' {
|
||||
result.push(match characters.next().expect("lexer validated escape") {
|
||||
'n' => '\n',
|
||||
't' => '\t',
|
||||
'"' => '"',
|
||||
'\\' => '\\',
|
||||
_ => unreachable!("lexer validated escape"),
|
||||
});
|
||||
} else {
|
||||
result.push(character);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! UTF-8 source frontend: a handwritten lexer and token-based rust-peg parser.
|
||||
//! Produces syntax only; it does not resolve types, generate code or execute VM
|
||||
//! operations. AST data owns its text and does not borrow the source buffer.
|
||||
|
||||
pub mod ast;
|
||||
mod diagnostic;
|
||||
mod lexer;
|
||||
mod parser;
|
||||
mod token;
|
||||
|
||||
pub use diagnostic::{Diagnostic, DiagnosticKind, SourceLocation, Span};
|
||||
pub use lexer::lex;
|
||||
pub use parser::{parse, parse_expression};
|
||||
pub use token::{Token, TokenKind};
|
||||
@@ -0,0 +1,182 @@
|
||||
use crate::ast::{
|
||||
BinaryOp, Binding, Block, Expr, ExprKind, Function, Name, Parameter, Program, UnaryOp,
|
||||
};
|
||||
use crate::lexer::decode_string;
|
||||
use crate::{Diagnostic, DiagnosticKind, Span, Token, TokenKind, lex};
|
||||
|
||||
/// Parse one or more basic typed function declarations. This is a syntax
|
||||
/// operation: type names and name references are retained without resolution.
|
||||
pub fn parse(source: &str) -> Result<Program, Diagnostic> {
|
||||
let tokens = lex(source)?;
|
||||
syntax::program(&tokens, source).map_err(|error| diagnostic(error, &tokens, source.len()))
|
||||
}
|
||||
|
||||
/// Parse exactly one complete expression, useful independently of declarations.
|
||||
pub fn parse_expression(source: &str) -> Result<Expr, Diagnostic> {
|
||||
let tokens = lex(source)?;
|
||||
syntax::expression(&tokens, source).map_err(|error| diagnostic(error, &tokens, source.len()))
|
||||
}
|
||||
|
||||
fn diagnostic(error: peg::error::ParseError<usize>, tokens: &[Token], end: usize) -> Diagnostic {
|
||||
let span = tokens
|
||||
.get(error.location)
|
||||
.map_or(Span::new(end, end), |token| token.span);
|
||||
let expected: Vec<String> = error.expected.tokens().map(str::to_owned).collect();
|
||||
Diagnostic {
|
||||
kind: DiagnosticKind::Syntax,
|
||||
span,
|
||||
message: format!("expected {}", expected.join(" or ")),
|
||||
expected,
|
||||
}
|
||||
}
|
||||
|
||||
fn binary(left: Expr, operation: BinaryOp, right: Expr) -> Expr {
|
||||
Expr {
|
||||
span: left.span.through(right.span),
|
||||
kind: ExprKind::Binary {
|
||||
operation,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
enum Suffix {
|
||||
Member(Name),
|
||||
Call(Vec<Expr>, Span),
|
||||
}
|
||||
|
||||
fn postfix(expression: Expr, suffix: Suffix) -> Expr {
|
||||
match suffix {
|
||||
Suffix::Member(name) => Expr {
|
||||
span: expression.span.through(name.span),
|
||||
kind: ExprKind::Member {
|
||||
object: Box::new(expression),
|
||||
name,
|
||||
},
|
||||
},
|
||||
Suffix::Call(arguments, end) => Expr {
|
||||
span: expression.span.through(end),
|
||||
kind: ExprKind::Call {
|
||||
callee: Box::new(expression),
|
||||
arguments,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
peg::parser! {
|
||||
grammar syntax(source: &str) for [Token] {
|
||||
rule keyword(word: &str) -> Span
|
||||
= [Token { kind: TokenKind::Name, span } if &source[span.start..span.end] == word] { span }
|
||||
|
||||
rule function_keyword() -> Span
|
||||
= quiet!{keyword("function")} / expected!("'function'")
|
||||
rule let_keyword() -> Span
|
||||
= quiet!{keyword("let")} / expected!("'let'")
|
||||
rule return_keyword() -> Span
|
||||
= quiet!{keyword("return")} / expected!("'return'")
|
||||
|
||||
rule name() -> Name
|
||||
= span:quiet!{[Token { kind: TokenKind::Name, span }] { span }} {
|
||||
Name { text: source[span.start..span.end].into(), span }
|
||||
}
|
||||
/ expected!("identifier")
|
||||
|
||||
rule lparen() -> Span
|
||||
= quiet!{[Token { kind: TokenKind::LeftParen, span }] { span }} / expected!("'('")
|
||||
rule rparen() -> Span
|
||||
= quiet!{[Token { kind: TokenKind::RightParen, span }] { span }} / expected!("')'")
|
||||
rule lbrace() -> Span
|
||||
= quiet!{[Token { kind: TokenKind::LeftBrace, span }] { span }} / expected!("'{'")
|
||||
rule rbrace() -> Span
|
||||
= quiet!{[Token { kind: TokenKind::RightBrace, span }] { span }} / expected!("'}'")
|
||||
rule colon()
|
||||
= quiet!{[Token { kind: TokenKind::Colon, .. }]} / expected!("':'")
|
||||
rule comma()
|
||||
= quiet!{[Token { kind: TokenKind::Comma, .. }]} / expected!("','")
|
||||
rule equal()
|
||||
= quiet!{[Token { kind: TokenKind::Equal, .. }]} / expected!("'='")
|
||||
rule dot() -> Span
|
||||
= quiet!{[Token { kind: TokenKind::Dot, span }] { span }} / expected!("'.'")
|
||||
rule plus()
|
||||
= [Token { kind: TokenKind::Plus, .. }]
|
||||
rule minus() -> Span
|
||||
= [Token { kind: TokenKind::Minus, span }] { span }
|
||||
rule star()
|
||||
= [Token { kind: TokenKind::Star, .. }]
|
||||
rule slash()
|
||||
= [Token { kind: TokenKind::Slash, .. }]
|
||||
|
||||
pub rule program() -> Program
|
||||
= functions:function()+ {
|
||||
let span = functions[0].span.through(functions.last().unwrap().span);
|
||||
Program { functions, span }
|
||||
}
|
||||
|
||||
rule function() -> Function
|
||||
= start:function_keyword() name:name() lparen()
|
||||
parameters:(parameter() ** comma()) rparen() colon() return_type:name() body:block() {
|
||||
Function { span: start.through(body.span), name, parameters, return_type, body }
|
||||
}
|
||||
|
||||
rule parameter() -> Parameter
|
||||
= name:name() colon() type_name:name() {
|
||||
Parameter { span: name.span.through(type_name.span), name, type_name }
|
||||
}
|
||||
|
||||
rule block() -> Block
|
||||
= start:lbrace() bindings:binding()* returned:return_statement() end:rbrace() {
|
||||
Block { bindings, result: returned.0, return_span: returned.1, span: start.through(end) }
|
||||
}
|
||||
|
||||
rule binding() -> Binding
|
||||
= start:let_keyword() name:name() equal() value:expression() {
|
||||
Binding { span: start.through(value.span), name, value }
|
||||
}
|
||||
|
||||
rule return_statement() -> (Expr, Span)
|
||||
= start:return_keyword() value:expression() {
|
||||
let span = start.through(value.span);
|
||||
(value, span)
|
||||
}
|
||||
|
||||
pub rule expression() -> Expr = precedence! {
|
||||
left:(@) plus() right:@ { binary(left, BinaryOp::Add, right) }
|
||||
left:(@) minus() right:@ { binary(left, BinaryOp::Subtract, right) }
|
||||
--
|
||||
left:(@) star() right:@ { binary(left, BinaryOp::Multiply, right) }
|
||||
left:(@) slash() right:@ { binary(left, BinaryOp::Divide, right) }
|
||||
--
|
||||
start:minus() operand:@ {
|
||||
Expr { span: start.through(operand.span), kind: ExprKind::Unary { operation: UnaryOp::Negate, operand: Box::new(operand) } }
|
||||
}
|
||||
--
|
||||
expression:postfix_expression() { expression }
|
||||
}
|
||||
|
||||
rule postfix_expression() -> Expr
|
||||
= expression:primary() suffixes:suffix()* {
|
||||
suffixes.into_iter().fold(expression, postfix)
|
||||
}
|
||||
|
||||
rule suffix() -> Suffix
|
||||
= dot() name:name() { Suffix::Member(name) }
|
||||
/ lparen() arguments:(expression() ** comma()) end:rparen() { Suffix::Call(arguments, end) }
|
||||
|
||||
rule primary() -> Expr
|
||||
= start:lparen() expression:expression() end:rparen() {
|
||||
Expr { span: start.through(end), ..expression }
|
||||
}
|
||||
/ start:dot() name:name() {
|
||||
Expr { span: start.through(name.span), kind: ExprKind::Symbol(name) }
|
||||
}
|
||||
/ [Token { kind: TokenKind::Number, span }] {
|
||||
Expr { span, kind: ExprKind::Number(source[span.start..span.end].into()) }
|
||||
}
|
||||
/ [Token { kind: TokenKind::String, span }] {
|
||||
Expr { span, kind: ExprKind::String(decode_string(&source[span.start + 1..span.end - 1])) }
|
||||
}
|
||||
/ name:name() { Expr { span: name.span, kind: ExprKind::Name(name.text) } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use crate::Span;
|
||||
|
||||
/// Text is located by span in the original source. Names stay contextual: the
|
||||
/// lexer does not turn syntax words into globally reserved keywords.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TokenKind {
|
||||
Name,
|
||||
Number,
|
||||
/// Span includes quotes. Escapes have been checked, not decoded.
|
||||
String,
|
||||
LeftParen,
|
||||
RightParen,
|
||||
LeftBrace,
|
||||
RightBrace,
|
||||
Colon,
|
||||
Comma,
|
||||
Dot,
|
||||
Equal,
|
||||
Plus,
|
||||
Minus,
|
||||
Star,
|
||||
Slash,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Token {
|
||||
pub kind: TokenKind,
|
||||
pub span: Span,
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Frontend 行为检查
|
||||
|
||||
[syntax.rs](syntax.rs) 覆盖 UTF-8 token 范围、中文/日文名称、数字原文、负号、字符串转义与错误、算术优先级和结合性、成员/调用链、函数与绑定、上下文名称、完整输入、非法/未支持语法以及 CRLF 和 EOF 诊断位置。
|
||||
|
||||
样例也通过此文件解析。只验证语法和 AST,不宣称类型检查或运行求值通过。随工作区检查在 ces-control 执行,本地不运行;入口见 [验证](../../../docs/operations/validation.md)。返回 [frontend](../README.md)。
|
||||
@@ -0,0 +1,278 @@
|
||||
use frontend::ast::{BinaryOp, Expr, ExprKind, UnaryOp};
|
||||
use frontend::{DiagnosticKind, Span, TokenKind, lex, parse, parse_expression};
|
||||
|
||||
fn binary(expression: &Expr, expected: BinaryOp) -> (&Expr, &Expr) {
|
||||
let ExprKind::Binary {
|
||||
operation,
|
||||
left,
|
||||
right,
|
||||
} = &expression.kind
|
||||
else {
|
||||
panic!("expected a binary expression: {expression:?}");
|
||||
};
|
||||
assert_eq!(*operation, expected);
|
||||
(left, right)
|
||||
}
|
||||
|
||||
fn number(expression: &Expr, expected: &str) {
|
||||
assert_eq!(expression.kind, ExprKind::Number(expected.into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_tokens_refer_to_exact_original_byte_ranges() {
|
||||
let source = "// 日本語\r\nlet 商品_2 = \"こんにちは🌸\"";
|
||||
let tokens = lex(source).unwrap();
|
||||
assert_eq!(tokens.len(), 4);
|
||||
assert_eq!(tokens[0].kind, TokenKind::Name);
|
||||
assert_eq!(&source[tokens[0].span.start..tokens[0].span.end], "let");
|
||||
assert_eq!(&source[tokens[1].span.start..tokens[1].span.end], "商品_2");
|
||||
assert_eq!(tokens[2].kind, TokenKind::Equal);
|
||||
assert_eq!(tokens[3].kind, TokenKind::String);
|
||||
for token in tokens {
|
||||
assert!(source.is_char_boundary(token.span.start));
|
||||
assert!(source.is_char_boundary(token.span.end));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_spelling_and_minus_tokens_are_preserved_without_float_conversion() {
|
||||
let source = "-000123456789012345678901234567890.00100 / 7 // comment";
|
||||
let tokens = lex(source).unwrap();
|
||||
assert_eq!(
|
||||
tokens.iter().map(|token| token.kind).collect::<Vec<_>>(),
|
||||
vec![
|
||||
TokenKind::Minus,
|
||||
TokenKind::Number,
|
||||
TokenKind::Slash,
|
||||
TokenKind::Number,
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
&source[tokens[1].span.start..tokens[1].span.end],
|
||||
"000123456789012345678901234567890.00100"
|
||||
);
|
||||
let expression = parse_expression(source).unwrap();
|
||||
let (negative, divisor) = binary(&expression, BinaryOp::Divide);
|
||||
let ExprKind::Unary {
|
||||
operation: UnaryOp::Negate,
|
||||
operand,
|
||||
} = &negative.kind
|
||||
else {
|
||||
panic!("expected unary minus");
|
||||
};
|
||||
number(operand, "000123456789012345678901234567890.00100");
|
||||
number(divisor, "7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_decode_only_the_supported_escapes_and_keep_comments_inside_strings() {
|
||||
let expression = parse_expression(r#""商品\n\t\"\\// text""#).unwrap();
|
||||
assert_eq!(
|
||||
expression.kind,
|
||||
ExprKind::String("商品\n\t\"\\// text".into())
|
||||
);
|
||||
assert_eq!(
|
||||
expression.span,
|
||||
Span::new(0, r#""商品\n\t\"\\// text""#.len())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_strings_numbers_and_unknown_characters_report_lexical_errors() {
|
||||
for source in [
|
||||
"\"unfinished",
|
||||
"\"bad\\q\"",
|
||||
"\"bad\nline\"",
|
||||
"\"bad\rline\"",
|
||||
"\"bad\0\"",
|
||||
"\"trailing\\",
|
||||
"1e3",
|
||||
"12name",
|
||||
"1_000",
|
||||
"'text'",
|
||||
";",
|
||||
"🌸",
|
||||
"\0",
|
||||
] {
|
||||
let error = lex(source).unwrap_err();
|
||||
assert_eq!(error.kind, DiagnosticKind::Lexical, "{source:?}");
|
||||
assert!(error.span.start <= error.span.end);
|
||||
assert!(error.span.end <= source.len());
|
||||
assert!(source.is_char_boundary(error.span.start));
|
||||
assert!(source.is_char_boundary(error.span.end));
|
||||
}
|
||||
let source = "\"日\\q\"";
|
||||
let error = lex(source).unwrap_err();
|
||||
assert_eq!(&source[error.span.start..error.span.end], "\\q");
|
||||
assert_eq!(error.location(source).column, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arithmetic_precedence_and_left_associativity_form_the_expected_tree() {
|
||||
let expression = parse_expression("1 - 2 - 3 * 4 / 5 + 6").unwrap();
|
||||
let (subtract, last) = binary(&expression, BinaryOp::Add);
|
||||
number(last, "6");
|
||||
let (first_subtract, divide) = binary(subtract, BinaryOp::Subtract);
|
||||
let (first, second) = binary(first_subtract, BinaryOp::Subtract);
|
||||
number(first, "1");
|
||||
number(second, "2");
|
||||
let (multiply, fifth) = binary(divide, BinaryOp::Divide);
|
||||
number(fifth, "5");
|
||||
let (third, fourth) = binary(multiply, BinaryOp::Multiply);
|
||||
number(third, "3");
|
||||
number(fourth, "4");
|
||||
let grouped = parse_expression("(1 + 2) * 3").unwrap();
|
||||
let (sum, _) = binary(&grouped, BinaryOp::Multiply);
|
||||
binary(sum, BinaryOp::Add);
|
||||
assert_eq!(sum.span, Span::new(0, 7));
|
||||
let nested = parse_expression("--1").unwrap();
|
||||
let ExprKind::Unary { operand, .. } = nested.kind else {
|
||||
panic!("expected outer negate");
|
||||
};
|
||||
assert!(matches!(
|
||||
operand.kind,
|
||||
ExprKind::Unary {
|
||||
operation: UnaryOp::Negate,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_and_call_chains_bind_more_tightly_than_unary_minus() {
|
||||
let expression = parse_expression("-factory(1).build(.title)(\"日\", 2)").unwrap();
|
||||
let ExprKind::Unary {
|
||||
operation: UnaryOp::Negate,
|
||||
operand,
|
||||
} = expression.kind
|
||||
else {
|
||||
panic!("expected negate");
|
||||
};
|
||||
let ExprKind::Call { callee, arguments } = operand.kind else {
|
||||
panic!("expected last call");
|
||||
};
|
||||
assert_eq!(arguments.len(), 2);
|
||||
assert_eq!(arguments[0].kind, ExprKind::String("日".into()));
|
||||
let ExprKind::Call { callee, arguments } = callee.kind else {
|
||||
panic!("expected build call");
|
||||
};
|
||||
let ExprKind::Symbol(name) = &arguments[0].kind else {
|
||||
panic!("expected a symbol");
|
||||
};
|
||||
assert_eq!(name.text, "title");
|
||||
let ExprKind::Member { object, name } = callee.kind else {
|
||||
panic!("expected member");
|
||||
};
|
||||
assert_eq!(name.text, "build");
|
||||
let ExprKind::Call { callee, arguments } = object.kind else {
|
||||
panic!("expected factory call");
|
||||
};
|
||||
assert_eq!(callee.kind, ExprKind::Name("factory".into()));
|
||||
number(&arguments[0], "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_typed_functions_bindings_and_multiple_top_level_definitions() {
|
||||
let example = parse(include_str!("../examples/basic.endor")).unwrap();
|
||||
assert_eq!(example.functions.len(), 2);
|
||||
let source = r#"
|
||||
// Basic draft syntax, including a Unicode name.
|
||||
function discountedPrice(price: Number, discount: Number): Number {
|
||||
let amount = price - discount
|
||||
return amount
|
||||
}
|
||||
function 表示(): String { return "こんにちは" }
|
||||
"#;
|
||||
let program = parse(source).unwrap();
|
||||
assert_eq!(program.functions.len(), 2);
|
||||
let function = &program.functions[0];
|
||||
assert_eq!(function.name.text, "discountedPrice");
|
||||
assert_eq!(function.parameters.len(), 2);
|
||||
assert_eq!(function.parameters[0].type_name.text, "Number");
|
||||
assert_eq!(function.return_type.text, "Number");
|
||||
assert_eq!(function.body.bindings[0].name.text, "amount");
|
||||
binary(&function.body.bindings[0].value, BinaryOp::Subtract);
|
||||
assert_eq!(function.body.result.kind, ExprKind::Name("amount".into()));
|
||||
assert_eq!(
|
||||
&source[function.body.return_span.start..function.body.return_span.end],
|
||||
"return amount"
|
||||
);
|
||||
assert_eq!(
|
||||
program.functions[1].body.result.kind,
|
||||
ExprKind::String("こんにちは".into())
|
||||
);
|
||||
assert_eq!(
|
||||
&source[program.functions[1].span.start..program.functions[1].span.end],
|
||||
"function 表示(): String { return \"こんにちは\" }"
|
||||
);
|
||||
// The output owns its text and can outlive the input buffer.
|
||||
let owned = {
|
||||
let source = String::from("function f(): String { return \"ok\" }");
|
||||
parse(&source).unwrap()
|
||||
};
|
||||
assert_eq!(owned.functions[0].name.text, "f");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syntax_words_are_contextual_and_block_layout_does_not_depend_on_newlines() {
|
||||
let program =
|
||||
parse("function class(function: Type): Type { let agent = function return agent }")
|
||||
.unwrap();
|
||||
assert_eq!(program.functions[0].name.text, "class");
|
||||
assert_eq!(program.functions[0].parameters[0].name.text, "function");
|
||||
assert_eq!(program.functions[0].body.bindings[0].name.text, "agent");
|
||||
let multiline =
|
||||
parse("function f\r\n(\r\nx: Number\r\n): Number\r\n{\r\nreturn x\r\n}").unwrap();
|
||||
assert_eq!(
|
||||
multiline.functions[0].body.result.kind,
|
||||
ExprKind::Name("x".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_requires_complete_input_and_rejects_unimplemented_or_malformed_syntax() {
|
||||
for source in [
|
||||
"",
|
||||
"// empty",
|
||||
"let x = 1",
|
||||
"use atelier:shop.data",
|
||||
"class Product {}",
|
||||
"agent Worker {}",
|
||||
"function f() { return 1 }",
|
||||
"function f(x): Number { return x }",
|
||||
"function f(x: Number,): Number { return x }",
|
||||
"function f(): Number {}",
|
||||
"function f(): Number { return 1 let x = 2 }",
|
||||
"function f(): Number { let x = 1 }",
|
||||
"function f(): Number { return 1 } extra",
|
||||
"function f(): Number { function g(): Number { return 1 } return 2 }",
|
||||
] {
|
||||
assert!(parse(source).is_err(), "{source}");
|
||||
}
|
||||
for source in [
|
||||
"", "x y", "1 +", "+1", ".5", "1.", "f(1,)", "f(,1)", "f(1 2)", "(1", "obj.", "[1]",
|
||||
"a == b", "1.2.3",
|
||||
] {
|
||||
assert!(parse_expression(source).is_err(), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syntax_errors_map_token_indexes_to_utf8_source_and_eof_locations() {
|
||||
let source = "function f(): String {\r\n let 商品 = \"日\"\r\n return )\r\n}";
|
||||
let error = parse(source).unwrap_err();
|
||||
assert_eq!(error.kind, DiagnosticKind::Syntax);
|
||||
assert_eq!(&source[error.span.start..error.span.end], ")");
|
||||
assert_eq!(error.location(source).line, 3);
|
||||
assert_eq!(error.location(source).column, 10);
|
||||
assert!(!error.expected.is_empty());
|
||||
let source = "function f(): Number { return 1\r\n ";
|
||||
let error = parse(source).unwrap_err();
|
||||
assert_eq!(error.span, Span::new(source.len(), source.len()));
|
||||
assert_eq!(error.location(source).line, 2);
|
||||
assert_eq!(error.location(source).column, 3);
|
||||
let source = "\r\n\r\n🌸";
|
||||
let error = lex(source).unwrap_err();
|
||||
assert_eq!(error.location(source).line, 3);
|
||||
assert_eq!(error.location(source).column, 1);
|
||||
}
|
||||
Reference in New Issue
Block a user