mirror of
https://github.com/exoticorn/curlywas.git
synced 2026-01-21 04:06:42 +01:00
Compare commits
2 Commits
ce8435e3dc
...
132aea3996
| Author | SHA1 | Date | |
|---|---|---|---|
| 132aea3996 | |||
| 1b434f6b30 |
16
examples/microw8/mem_intrinsics.cwa
Normal file
16
examples/microw8/mem_intrinsics.cwa
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import "env.memory" memory(4);
|
||||||
|
import "env.random" fn random() -> i32;
|
||||||
|
|
||||||
|
export fn upd() {
|
||||||
|
let i: i32;
|
||||||
|
loop pixels {
|
||||||
|
let inline left = i32.load8_u((i + (320*240 - 319)) % (320*240), 120);
|
||||||
|
let inline top = i32.load8_u((i + 320*239) % (320*240), 120, 0);
|
||||||
|
let inline here = i32.load16_u(i, 119);
|
||||||
|
let inline all = (left << 24) | (top << 16) | here;
|
||||||
|
let lazy r = random();
|
||||||
|
let inline new = (all #>> ((r & 3) * 8)) ^ ((r & 31) * !(r #>> 22));
|
||||||
|
i32.store8(new, i, 120);
|
||||||
|
branch_if (i := i + 1) < 320*240: pixels;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -288,7 +288,7 @@ impl Expr {
|
|||||||
Expression {
|
Expression {
|
||||||
type_: None,
|
type_: None,
|
||||||
expr: self,
|
expr: self,
|
||||||
span: span,
|
span,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -337,6 +337,7 @@ pub enum BinOp {
|
|||||||
pub enum MemSize {
|
pub enum MemSize {
|
||||||
Byte,
|
Byte,
|
||||||
Word,
|
Word,
|
||||||
|
Float
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||||
|
|||||||
47
src/emit.rs
47
src/emit.rs
@@ -6,7 +6,11 @@ use wasm_encoder::{
|
|||||||
MemArg, MemoryType, Module, NameMap, NameSection, StartSection, TypeSection, ValType,
|
MemArg, MemoryType, Module, NameMap, NameSection, StartSection, TypeSection, ValType,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{ast, intrinsics::Intrinsics, Options};
|
use crate::{
|
||||||
|
ast,
|
||||||
|
intrinsics::{Intrinsics, MemInstruction},
|
||||||
|
Options,
|
||||||
|
};
|
||||||
|
|
||||||
pub fn emit(script: &ast::Script, module_name: &str, options: &Options) -> Vec<u8> {
|
pub fn emit(script: &ast::Script, module_name: &str, options: &Options) -> Vec<u8> {
|
||||||
let mut module = Module::new();
|
let mut module = Module::new();
|
||||||
@@ -65,9 +69,7 @@ pub fn emit(script: &ast::Script, module_name: &str, options: &Options) -> Vec<u
|
|||||||
} => {
|
} => {
|
||||||
function_map.insert(name.clone(), function_map.len() as u32);
|
function_map.insert(name.clone(), function_map.len() as u32);
|
||||||
EntityType::Function(
|
EntityType::Function(
|
||||||
*function_types
|
*function_types.get(&(params.clone(), *result)).unwrap() as u32
|
||||||
.get(&(params.clone(), result.clone()))
|
|
||||||
.unwrap() as u32,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -254,9 +256,7 @@ fn collect_function_types(script: &ast::Script) -> HashMap<FunctionTypeKey, usiz
|
|||||||
} = import.type_
|
} = import.type_
|
||||||
{
|
{
|
||||||
let index = types.len();
|
let index = types.len();
|
||||||
types
|
types.entry((params.clone(), *result)).or_insert(index);
|
||||||
.entry((params.clone(), result.clone()))
|
|
||||||
.or_insert(index);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -346,6 +346,11 @@ fn mem_arg_for_location(mem_location: &ast::MemoryLocation) -> MemArg {
|
|||||||
memory_index: 0,
|
memory_index: 0,
|
||||||
offset,
|
offset,
|
||||||
},
|
},
|
||||||
|
ast::MemSize::Float => MemArg {
|
||||||
|
align: 2,
|
||||||
|
memory_index: 0,
|
||||||
|
offset,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,6 +396,7 @@ fn emit_expression<'a>(ctx: &mut FunctionContext<'a>, expr: &'a ast::Expression)
|
|||||||
ctx.function.instruction(&match mem_location.size {
|
ctx.function.instruction(&match mem_location.size {
|
||||||
ast::MemSize::Byte => Instruction::I32Load8_U(mem_arg),
|
ast::MemSize::Byte => Instruction::I32Load8_U(mem_arg),
|
||||||
ast::MemSize::Word => Instruction::I32Load(mem_arg),
|
ast::MemSize::Word => Instruction::I32Load(mem_arg),
|
||||||
|
ast::MemSize::Float => Instruction::F32Load(mem_arg),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
ast::Expr::Poke {
|
ast::Expr::Poke {
|
||||||
@@ -403,6 +409,7 @@ fn emit_expression<'a>(ctx: &mut FunctionContext<'a>, expr: &'a ast::Expression)
|
|||||||
ctx.function.instruction(&match mem_location.size {
|
ctx.function.instruction(&match mem_location.size {
|
||||||
ast::MemSize::Byte => Instruction::I32Store8(mem_arg),
|
ast::MemSize::Byte => Instruction::I32Store8(mem_arg),
|
||||||
ast::MemSize::Word => Instruction::I32Store(mem_arg),
|
ast::MemSize::Word => Instruction::I32Store(mem_arg),
|
||||||
|
ast::MemSize::Float => Instruction::F32Store(mem_arg),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
ast::Expr::UnaryOp { op, value } => {
|
ast::Expr::UnaryOp { op, value } => {
|
||||||
@@ -654,6 +661,31 @@ fn emit_expression<'a>(ctx: &mut FunctionContext<'a>, expr: &'a ast::Expression)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ast::Expr::FuncCall { name, params, .. } => {
|
ast::Expr::FuncCall { name, params, .. } => {
|
||||||
|
fn mem_instruction(
|
||||||
|
inst: MemInstruction,
|
||||||
|
params: &[ast::Expression],
|
||||||
|
) -> Instruction<'static> {
|
||||||
|
let offset = params
|
||||||
|
.get(0)
|
||||||
|
.map(|e| e.const_i32() as u32 as u64)
|
||||||
|
.unwrap_or(0);
|
||||||
|
let alignment = params.get(1).map(|e| e.const_i32() as u32);
|
||||||
|
(inst.instruction)(MemArg {
|
||||||
|
offset,
|
||||||
|
align: alignment.unwrap_or(inst.natural_alignment),
|
||||||
|
memory_index: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if let Some(load) = ctx.intrinsics.find_load(name) {
|
||||||
|
emit_expression(ctx, ¶ms[0]);
|
||||||
|
ctx.function
|
||||||
|
.instruction(&mem_instruction(load, ¶ms[1..]));
|
||||||
|
} else if let Some(store) = ctx.intrinsics.find_store(name) {
|
||||||
|
emit_expression(ctx, ¶ms[1]);
|
||||||
|
emit_expression(ctx, ¶ms[0]);
|
||||||
|
ctx.function
|
||||||
|
.instruction(&mem_instruction(store, ¶ms[2..]));
|
||||||
|
} else {
|
||||||
for param in params {
|
for param in params {
|
||||||
emit_expression(ctx, param);
|
emit_expression(ctx, param);
|
||||||
}
|
}
|
||||||
@@ -669,6 +701,7 @@ fn emit_expression<'a>(ctx: &mut FunctionContext<'a>, expr: &'a ast::Expression)
|
|||||||
.instruction(&ctx.intrinsics.get_instr(name, &types).unwrap());
|
.instruction(&ctx.intrinsics.get_instr(name, &types).unwrap());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
ast::Expr::Select {
|
ast::Expr::Select {
|
||||||
condition,
|
condition,
|
||||||
if_true,
|
if_true,
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ pub fn resolve_includes(script: &mut ast::Script, path: &Path) -> Result<()> {
|
|||||||
let script_dir = path.parent().expect("Script path has no parent");
|
let script_dir = path.parent().expect("Script path has no parent");
|
||||||
for data in &mut script.data {
|
for data in &mut script.data {
|
||||||
for values in &mut data.data {
|
for values in &mut data.data {
|
||||||
match values {
|
if let ast::DataValues::File {
|
||||||
ast::DataValues::File {
|
|
||||||
ref path,
|
ref path,
|
||||||
ref mut data,
|
ref mut data,
|
||||||
} => {
|
} = values
|
||||||
|
{
|
||||||
let mut full_path = script_dir.to_path_buf();
|
let mut full_path = script_dir.to_path_buf();
|
||||||
full_path.push(path);
|
full_path.push(path);
|
||||||
File::open(&full_path)
|
File::open(&full_path)
|
||||||
@@ -22,8 +22,6 @@ pub fn resolve_includes(script: &mut ast::Script, path: &Path) -> Result<()> {
|
|||||||
})?
|
})?
|
||||||
.read_to_end(data)?;
|
.read_to_end(data)?;
|
||||||
}
|
}
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use crate::ast::Type;
|
use crate::ast::Type;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use enc::MemArg;
|
||||||
use wasm_encoder as enc;
|
use wasm_encoder as enc;
|
||||||
|
|
||||||
pub struct Intrinsics(HashMap<String, HashMap<Vec<Type>, (Type, enc::Instruction<'static>)>>);
|
pub struct Intrinsics(HashMap<String, HashMap<Vec<Type>, (Type, enc::Instruction<'static>)>>);
|
||||||
@@ -137,4 +138,59 @@ impl Intrinsics {
|
|||||||
.or_default()
|
.or_default()
|
||||||
.insert(params.to_vec(), (ret, ins.clone()));
|
.insert(params.to_vec(), (ret, ins.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn find_load(&self, name: &str) -> Option<MemInstruction> {
|
||||||
|
use enc::Instruction as I;
|
||||||
|
use Type::*;
|
||||||
|
let ins = match name {
|
||||||
|
"i32.load" => MemInstruction::new(I32, I::I32Load, 2),
|
||||||
|
"i32.load8_s" => MemInstruction::new(I32, I::I32Load8_S, 0),
|
||||||
|
"i32.load8_u" => MemInstruction::new(I32, I::I32Load8_U, 0),
|
||||||
|
"i32.load16_s" => MemInstruction::new(I32, I::I32Load16_S, 1),
|
||||||
|
"i32.load16_u" => MemInstruction::new(I32, I::I32Load16_U, 1),
|
||||||
|
"i64.load" => MemInstruction::new(I64, I::I64Load, 3),
|
||||||
|
"i64.load8_s" => MemInstruction::new(I64, I::I64Load8_S, 0),
|
||||||
|
"i64.load8_u" => MemInstruction::new(I64, I::I64Load8_U, 0),
|
||||||
|
"i64.load16_s" => MemInstruction::new(I64, I::I64Load16_S, 1),
|
||||||
|
"i64.load16_u" => MemInstruction::new(I64, I::I64Load16_U, 1),
|
||||||
|
"i64.load32_s" => MemInstruction::new(I64, I::I64Load32_S, 2),
|
||||||
|
"i64.load32_u" => MemInstruction::new(I64, I::I64Load32_U, 2),
|
||||||
|
"f32.load" => MemInstruction::new(F32, I::F32Load, 2),
|
||||||
|
"f64.load" => MemInstruction::new(F64, I::F64Load, 3),
|
||||||
|
_ => return None
|
||||||
|
};
|
||||||
|
return Some(ins);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_store(&self, name: &str) -> Option<MemInstruction> {
|
||||||
|
use enc::Instruction as I;
|
||||||
|
use Type::*;
|
||||||
|
let ins = match name {
|
||||||
|
"i32.store" => MemInstruction::new(I32, I::I32Store, 2),
|
||||||
|
"i32.store8" => MemInstruction::new(I32, I::I32Store8, 0),
|
||||||
|
"i32.store16" => MemInstruction::new(I32, I::I32Store16, 1),
|
||||||
|
"i64.store" => MemInstruction::new(I64, I::I64Store, 3),
|
||||||
|
"i64.store8" => MemInstruction::new(I64, I::I64Store8, 0),
|
||||||
|
"i64.store16" => MemInstruction::new(I64, I::I64Store16, 1),
|
||||||
|
"i64.store32" => MemInstruction::new(I64, I::I64Store32, 2),
|
||||||
|
"f32.store" => MemInstruction::new(F32, I::F32Store, 2),
|
||||||
|
"f64.store" => MemInstruction::new(F64, I::F64Store, 3),
|
||||||
|
_ => return None
|
||||||
|
};
|
||||||
|
return Some(ins);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MemInstruction {
|
||||||
|
pub type_: Type,
|
||||||
|
pub instruction: fn(MemArg) -> enc::Instruction<'static>,
|
||||||
|
pub natural_alignment: u32
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemInstruction {
|
||||||
|
fn new(type_: Type, instruction: fn(MemArg) -> enc::Instruction<'static>, natural_alignment: u32) -> MemInstruction {
|
||||||
|
MemInstruction {
|
||||||
|
type_, instruction, natural_alignment
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,10 +20,7 @@ pub struct Options {
|
|||||||
|
|
||||||
impl Options {
|
impl Options {
|
||||||
pub fn with_debug(self) -> Self {
|
pub fn with_debug(self) -> Self {
|
||||||
Options {
|
Options { debug: true }
|
||||||
debug: true,
|
|
||||||
..self
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +33,7 @@ pub fn compile_file<P: AsRef<Path>>(path: P, options: Options) -> Result<Vec<u8>
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn compile_str(input: &str, path: &Path, options: Options) -> Result<Vec<u8>> {
|
pub fn compile_str(input: &str, path: &Path, options: Options) -> Result<Vec<u8>> {
|
||||||
let mut script = match parser::parse(&input) {
|
let mut script = match parser::parse(input) {
|
||||||
Ok(script) => script,
|
Ok(script) => script,
|
||||||
Err(_) => bail!("Parse failed"),
|
Err(_) => bail!("Parse failed"),
|
||||||
};
|
};
|
||||||
@@ -44,7 +41,7 @@ pub fn compile_str(input: &str, path: &Path, options: Options) -> Result<Vec<u8>
|
|||||||
includes::resolve_includes(&mut script, path)?;
|
includes::resolve_includes(&mut script, path)?;
|
||||||
|
|
||||||
constfold::fold_script(&mut script);
|
constfold::fold_script(&mut script);
|
||||||
if let Err(_) = typecheck::tc_script(&mut script, &input) {
|
if typecheck::tc_script(&mut script, input).is_err() {
|
||||||
bail!("Type check failed");
|
bail!("Type check failed");
|
||||||
}
|
}
|
||||||
let wasm = emit::emit(
|
let wasm = emit::emit(
|
||||||
|
|||||||
@@ -183,7 +183,8 @@ fn lexer() -> impl Parser<char, Vec<(Token, Span)>, Error = Simple<char>> {
|
|||||||
u64::from_str_radix(&n, 16).map_err(|err| Simple::custom(span, err.to_string()))
|
u64::from_str_radix(&n, 16).map_err(|err| Simple::custom(span, err.to_string()))
|
||||||
})
|
})
|
||||||
.or(text::int(10).try_map(|n: String, span: Span| {
|
.or(text::int(10).try_map(|n: String, span: Span| {
|
||||||
u64::from_str_radix(&n, 10).map_err(|err| Simple::custom(span, err.to_string()))
|
n.parse::<u64>()
|
||||||
|
.map_err(|err| Simple::custom(span, err.to_string()))
|
||||||
}))
|
}))
|
||||||
.boxed();
|
.boxed();
|
||||||
|
|
||||||
@@ -211,7 +212,7 @@ fn lexer() -> impl Parser<char, Vec<(Token, Span)>, Error = Simple<char>> {
|
|||||||
.collect::<String>()
|
.collect::<String>()
|
||||||
.map(Token::Op);
|
.map(Token::Op);
|
||||||
|
|
||||||
let ctrl = one_of("(){};,:?!".chars()).map(Token::Ctrl);
|
let ctrl = one_of("(){};,:?!$".chars()).map(Token::Ctrl);
|
||||||
|
|
||||||
fn ident() -> impl Parser<char, String, Error = Simple<char>> + Copy + Clone {
|
fn ident() -> impl Parser<char, String, Error = Simple<char>> + Copy + Clone {
|
||||||
filter(|c: &char| c.is_ascii_alphabetic() || *c == '_')
|
filter(|c: &char| c.is_ascii_alphabetic() || *c == '_')
|
||||||
@@ -358,7 +359,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
|
|
||||||
let branch = just(Token::Branch)
|
let branch = just(Token::Branch)
|
||||||
.ignore_then(identifier)
|
.ignore_then(identifier)
|
||||||
.map(|label| ast::Expr::Branch(label));
|
.map(ast::Expr::Branch);
|
||||||
|
|
||||||
let branch_if = just(Token::BranchIf)
|
let branch_if = just(Token::BranchIf)
|
||||||
.ignore_then(expression.clone())
|
.ignore_then(expression.clone())
|
||||||
@@ -377,7 +378,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
.or(just(Token::Inline).to(ast::LetType::Inline)))
|
.or(just(Token::Inline).to(ast::LetType::Inline)))
|
||||||
.or_not(),
|
.or_not(),
|
||||||
)
|
)
|
||||||
.then(identifier.clone())
|
.then(identifier)
|
||||||
.then(just(Token::Ctrl(':')).ignore_then(type_parser()).or_not())
|
.then(just(Token::Ctrl(':')).ignore_then(type_parser()).or_not())
|
||||||
.then(
|
.then(
|
||||||
just(Token::Op("=".to_string()))
|
just(Token::Op("=".to_string()))
|
||||||
@@ -394,7 +395,6 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
.boxed();
|
.boxed();
|
||||||
|
|
||||||
let assign = identifier
|
let assign = identifier
|
||||||
.clone()
|
|
||||||
.then_ignore(just(Token::Op("=".to_string())))
|
.then_ignore(just(Token::Op("=".to_string())))
|
||||||
.then(expression.clone())
|
.then(expression.clone())
|
||||||
.map(|(name, value)| ast::Expr::Assign {
|
.map(|(name, value)| ast::Expr::Assign {
|
||||||
@@ -422,7 +422,6 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
.boxed();
|
.boxed();
|
||||||
|
|
||||||
let function_call = identifier
|
let function_call = identifier
|
||||||
.clone()
|
|
||||||
.then(
|
.then(
|
||||||
expression
|
expression
|
||||||
.clone()
|
.clone()
|
||||||
@@ -499,7 +498,8 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
|
|
||||||
let mem_size = just(Token::Ctrl('?'))
|
let mem_size = just(Token::Ctrl('?'))
|
||||||
.to(ast::MemSize::Byte)
|
.to(ast::MemSize::Byte)
|
||||||
.or(just(Token::Ctrl('!')).to(ast::MemSize::Word));
|
.or(just(Token::Ctrl('!')).to(ast::MemSize::Word))
|
||||||
|
.or(just(Token::Ctrl('$')).to(ast::MemSize::Float));
|
||||||
|
|
||||||
let mem_op = mem_size.then(op_cast.clone());
|
let mem_op = mem_size.then(op_cast.clone());
|
||||||
|
|
||||||
@@ -676,7 +676,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
})
|
})
|
||||||
.boxed();
|
.boxed();
|
||||||
|
|
||||||
let op_first = op_bit
|
op_bit
|
||||||
.clone()
|
.clone()
|
||||||
.then(
|
.then(
|
||||||
just(Token::Op("<|".to_string()))
|
just(Token::Op("<|".to_string()))
|
||||||
@@ -691,9 +691,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
}
|
}
|
||||||
.with_span(span)
|
.with_span(span)
|
||||||
})
|
})
|
||||||
.boxed();
|
.boxed()
|
||||||
|
|
||||||
op_first
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expression_out = Some(expression.clone());
|
expression_out = Some(expression.clone());
|
||||||
@@ -718,7 +716,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
}
|
}
|
||||||
ast::Expr::Block {
|
ast::Expr::Block {
|
||||||
statements: statements.into_iter().map(|(expr, _)| expr).collect(),
|
statements: statements.into_iter().map(|(expr, _)| expr).collect(),
|
||||||
final_expression: final_expression.map(|e| Box::new(e)),
|
final_expression: final_expression.map(Box::new),
|
||||||
}
|
}
|
||||||
.with_span(span)
|
.with_span(span)
|
||||||
})
|
})
|
||||||
@@ -740,7 +738,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
|
|
||||||
let import_global = just(Token::Global)
|
let import_global = just(Token::Global)
|
||||||
.ignore_then(just(Token::Mut).or_not())
|
.ignore_then(just(Token::Mut).or_not())
|
||||||
.then(identifier.clone())
|
.then(identifier)
|
||||||
.then_ignore(just(Token::Ctrl(':')))
|
.then_ignore(just(Token::Ctrl(':')))
|
||||||
.then(type_parser())
|
.then(type_parser())
|
||||||
.map(|((mut_opt, name), type_)| ast::ImportType::Variable {
|
.map(|((mut_opt, name), type_)| ast::ImportType::Variable {
|
||||||
@@ -751,7 +749,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
.boxed();
|
.boxed();
|
||||||
|
|
||||||
let import_function = just(Token::Fn)
|
let import_function = just(Token::Fn)
|
||||||
.ignore_then(identifier.clone())
|
.ignore_then(identifier)
|
||||||
.then(
|
.then(
|
||||||
type_parser()
|
type_parser()
|
||||||
.separated_by(just(Token::Ctrl(',')))
|
.separated_by(just(Token::Ctrl(',')))
|
||||||
@@ -783,7 +781,6 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
.boxed();
|
.boxed();
|
||||||
|
|
||||||
let parameter = identifier
|
let parameter = identifier
|
||||||
.clone()
|
|
||||||
.then_ignore(just(Token::Ctrl(':')))
|
.then_ignore(just(Token::Ctrl(':')))
|
||||||
.then(type_parser())
|
.then(type_parser())
|
||||||
.boxed();
|
.boxed();
|
||||||
@@ -792,7 +789,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
.or_not()
|
.or_not()
|
||||||
.then(just(Token::Ident("start".to_string())).or_not())
|
.then(just(Token::Ident("start".to_string())).or_not())
|
||||||
.then_ignore(just(Token::Fn))
|
.then_ignore(just(Token::Fn))
|
||||||
.then(identifier.clone())
|
.then(identifier)
|
||||||
.then(
|
.then(
|
||||||
parameter
|
parameter
|
||||||
.separated_by(just(Token::Ctrl(',')))
|
.separated_by(just(Token::Ctrl(',')))
|
||||||
@@ -820,7 +817,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
|
|
||||||
let global = just(Token::Global)
|
let global = just(Token::Global)
|
||||||
.ignore_then(just(Token::Mut).or_not())
|
.ignore_then(just(Token::Mut).or_not())
|
||||||
.then(identifier.clone())
|
.then(identifier)
|
||||||
.then(just(Token::Ctrl(':')).ignore_then(type_parser()).or_not())
|
.then(just(Token::Ctrl(':')).ignore_then(type_parser()).or_not())
|
||||||
.then(just(Token::Op("=".to_string())).ignore_then(expression.clone()))
|
.then(just(Token::Op("=".to_string())).ignore_then(expression.clone()))
|
||||||
.then_ignore(just(Token::Ctrl(';')))
|
.then_ignore(just(Token::Ctrl(';')))
|
||||||
@@ -850,7 +847,7 @@ fn script_parser() -> impl Parser<Token, ast::Script, Error = Simple<Token>> + C
|
|||||||
)
|
)
|
||||||
.map(|(type_, values)| ast::DataValues::Array { type_, values });
|
.map(|(type_, values)| ast::DataValues::Array { type_, values });
|
||||||
|
|
||||||
let data_string = string.clone().map(|s| ast::DataValues::String(s));
|
let data_string = string.clone().map(ast::DataValues::String);
|
||||||
|
|
||||||
let data_file = just(Token::Ident("file".to_string()))
|
let data_file = just(Token::Ident("file".to_string()))
|
||||||
.ignore_then(
|
.ignore_then(
|
||||||
|
|||||||
169
src/typecheck.rs
169
src/typecheck.rs
@@ -1,7 +1,7 @@
|
|||||||
use ariadne::{Color, Label, Report, ReportKind, Source};
|
use ariadne::{Color, Label, Report, ReportKind, Source};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::ast;
|
use crate::ast::{self, MemSize};
|
||||||
use crate::intrinsics::Intrinsics;
|
use crate::intrinsics::Intrinsics;
|
||||||
use crate::Span;
|
use crate::Span;
|
||||||
use ast::Type::*;
|
use ast::Type::*;
|
||||||
@@ -160,7 +160,7 @@ pub fn tc_script(script: &mut ast::Script, source: &str) -> Result<()> {
|
|||||||
context.locals.locals[index].index = Some((locals_start + id) as u32);
|
context.locals.locals[index].index = Some((locals_start + id) as u32);
|
||||||
}
|
}
|
||||||
|
|
||||||
f.locals = std::mem::replace(&mut context.locals, ast::Locals::default());
|
f.locals = std::mem::take(&mut context.locals);
|
||||||
|
|
||||||
if f.body.type_ != f.type_ {
|
if f.body.type_ != f.type_ {
|
||||||
result = type_mismatch(f.type_, &f.span, f.body.type_, &f.body.span, source);
|
result = type_mismatch(f.type_, &f.span, f.body.type_, &f.body.span, source);
|
||||||
@@ -333,7 +333,7 @@ fn type_mismatch(
|
|||||||
"Expected type {:?}...",
|
"Expected type {:?}...",
|
||||||
type1
|
type1
|
||||||
.map(|t| format!("{:?}", t))
|
.map(|t| format!("{:?}", t))
|
||||||
.unwrap_or("void".to_string())
|
.unwrap_or_else(|| "void".to_string())
|
||||||
))
|
))
|
||||||
.with_color(Color::Yellow),
|
.with_color(Color::Yellow),
|
||||||
)
|
)
|
||||||
@@ -343,7 +343,7 @@ fn type_mismatch(
|
|||||||
"...but found type {}",
|
"...but found type {}",
|
||||||
type2
|
type2
|
||||||
.map(|t| format!("{:?}", t))
|
.map(|t| format!("{:?}", t))
|
||||||
.unwrap_or("void".to_string())
|
.unwrap_or_else(|| "void".to_string())
|
||||||
))
|
))
|
||||||
.with_color(Color::Red),
|
.with_color(Color::Red),
|
||||||
)
|
)
|
||||||
@@ -353,12 +353,12 @@ fn type_mismatch(
|
|||||||
Err(())
|
Err(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn expected_type(span: &Span, source: &str) -> Result<()> {
|
fn report_error(msg: &str, span: &Span, source: &str) -> Result<()> {
|
||||||
Report::build(ReportKind::Error, (), span.start)
|
Report::build(ReportKind::Error, (), span.start)
|
||||||
.with_message("Expected value but found expression of type void")
|
.with_message(msg)
|
||||||
.with_label(
|
.with_label(
|
||||||
Label::new(span.clone())
|
Label::new(span.clone())
|
||||||
.with_message("Expected value but found expression of type void")
|
.with_message(msg)
|
||||||
.with_color(Color::Red),
|
.with_color(Color::Red),
|
||||||
)
|
)
|
||||||
.finish()
|
.finish()
|
||||||
@@ -367,46 +367,24 @@ fn expected_type(span: &Span, source: &str) -> Result<()> {
|
|||||||
Err(())
|
Err(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn expected_type(span: &Span, source: &str) -> Result<()> {
|
||||||
|
report_error(
|
||||||
|
"Expected value but found expression of type void",
|
||||||
|
span,
|
||||||
|
source,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn unknown_variable(span: &Span, source: &str) -> Result<()> {
|
fn unknown_variable(span: &Span, source: &str) -> Result<()> {
|
||||||
Report::build(ReportKind::Error, (), span.start)
|
report_error("Unknown variable", span, source)
|
||||||
.with_message("Unknown variable")
|
|
||||||
.with_label(
|
|
||||||
Label::new(span.clone())
|
|
||||||
.with_message("Unknown variable")
|
|
||||||
.with_color(Color::Red),
|
|
||||||
)
|
|
||||||
.finish()
|
|
||||||
.eprint(Source::from(source))
|
|
||||||
.unwrap();
|
|
||||||
Err(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn immutable_assign(span: &Span, source: &str) -> Result<()> {
|
fn immutable_assign(span: &Span, source: &str) -> Result<()> {
|
||||||
Report::build(ReportKind::Error, (), span.start)
|
report_error("Trying to assign to immutable variable", span, source)
|
||||||
.with_message("Trying to assign to immutable variable")
|
|
||||||
.with_label(
|
|
||||||
Label::new(span.clone())
|
|
||||||
.with_message("Trying to assign to immutable variable")
|
|
||||||
.with_color(Color::Red),
|
|
||||||
)
|
|
||||||
.finish()
|
|
||||||
.eprint(Source::from(source))
|
|
||||||
.unwrap();
|
|
||||||
Err(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn missing_label(span: &Span, source: &str) -> Result<()> {
|
fn missing_label(span: &Span, source: &str) -> Result<()> {
|
||||||
Report::build(ReportKind::Error, (), span.start)
|
report_error("Label not found", span, source)
|
||||||
.with_message("Label not found")
|
|
||||||
.with_label(
|
|
||||||
Label::new(span.clone())
|
|
||||||
.with_message("Label not found")
|
|
||||||
.with_color(Color::Red),
|
|
||||||
)
|
|
||||||
.finish()
|
|
||||||
.eprint(Source::from(source))
|
|
||||||
.unwrap();
|
|
||||||
return Err(());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn tc_expression(context: &mut Context, expr: &mut ast::Expression) -> Result<()> {
|
fn tc_expression(context: &mut Context, expr: &mut ast::Expression) -> Result<()> {
|
||||||
@@ -471,23 +449,17 @@ fn tc_expression(context: &mut Context, expr: &mut ast::Expression) -> Result<()
|
|||||||
*local_id = Some(id);
|
*local_id = Some(id);
|
||||||
context.local_vars.insert(name.clone(), id);
|
context.local_vars.insert(name.clone(), id);
|
||||||
} else {
|
} else {
|
||||||
Report::build(ReportKind::Error, (), expr.span.start)
|
return report_error("Type missing", &expr.span, context.source);
|
||||||
.with_message("Type missing")
|
|
||||||
.with_label(
|
|
||||||
Label::new(expr.span.clone())
|
|
||||||
.with_message("Type missing")
|
|
||||||
.with_color(Color::Red),
|
|
||||||
)
|
|
||||||
.finish()
|
|
||||||
.eprint(Source::from(context.source))
|
|
||||||
.unwrap();
|
|
||||||
return Err(());
|
|
||||||
}
|
}
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
ast::Expr::Peek(ref mut mem_location) => {
|
ast::Expr::Peek(ref mut mem_location) => {
|
||||||
tc_mem_location(context, mem_location)?;
|
tc_mem_location(context, mem_location)?;
|
||||||
Some(I32)
|
let ty = match mem_location.size {
|
||||||
|
MemSize::Float => F32,
|
||||||
|
_ => I32,
|
||||||
|
};
|
||||||
|
Some(ty)
|
||||||
}
|
}
|
||||||
ast::Expr::Poke {
|
ast::Expr::Poke {
|
||||||
ref mut mem_location,
|
ref mut mem_location,
|
||||||
@@ -495,9 +467,13 @@ fn tc_expression(context: &mut Context, expr: &mut ast::Expression) -> Result<()
|
|||||||
} => {
|
} => {
|
||||||
tc_mem_location(context, mem_location)?;
|
tc_mem_location(context, mem_location)?;
|
||||||
tc_expression(context, value)?;
|
tc_expression(context, value)?;
|
||||||
if value.type_ != Some(I32) {
|
let ty = match mem_location.size {
|
||||||
|
MemSize::Float => F32,
|
||||||
|
_ => I32,
|
||||||
|
};
|
||||||
|
if value.type_ != Some(ty) {
|
||||||
return type_mismatch(
|
return type_mismatch(
|
||||||
Some(I32),
|
Some(ty),
|
||||||
&expr.span,
|
&expr.span,
|
||||||
value.type_,
|
value.type_,
|
||||||
&value.span,
|
&value.span,
|
||||||
@@ -725,7 +701,27 @@ fn tc_expression(context: &mut Context, expr: &mut ast::Expression) -> Result<()
|
|||||||
return expected_type(¶m.span, context.source);
|
return expected_type(¶m.span, context.source);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(type_map) = context
|
if let Some(load) = context.intrinsics.find_load(name) {
|
||||||
|
tc_memarg(context, params.as_mut_slice(), &expr.span)?;
|
||||||
|
Some(load.type_)
|
||||||
|
} else if let Some(store) = context.intrinsics.find_store(name) {
|
||||||
|
if let Some(value) = params.first_mut() {
|
||||||
|
tc_expression(context, value)?;
|
||||||
|
if value.type_ != Some(store.type_) {
|
||||||
|
type_mismatch(
|
||||||
|
Some(store.type_),
|
||||||
|
&expr.span,
|
||||||
|
value.type_,
|
||||||
|
&value.span,
|
||||||
|
context.source,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return report_error("Missing parameters", &expr.span, context.source);
|
||||||
|
}
|
||||||
|
tc_memarg(context, &mut params[1..], &expr.span)?;
|
||||||
|
None
|
||||||
|
} else if let Some(type_map) = context
|
||||||
.functions
|
.functions
|
||||||
.get(name)
|
.get(name)
|
||||||
.map(|fnc| HashMap::from_iter([(fnc.params.clone(), fnc.type_)]))
|
.map(|fnc| HashMap::from_iter([(fnc.params.clone(), fnc.type_)]))
|
||||||
@@ -759,17 +755,11 @@ fn tc_expression(context: &mut Context, expr: &mut ast::Expression) -> Result<()
|
|||||||
return Err(());
|
return Err(());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Report::build(ReportKind::Error, (), expr.span.start)
|
return report_error(
|
||||||
.with_message(format!("Unknown function {}", name))
|
&format!("Unknown function {}", name),
|
||||||
.with_label(
|
&expr.span,
|
||||||
Label::new(expr.span.clone())
|
context.source,
|
||||||
.with_message(format!("Unknown function {}", name))
|
);
|
||||||
.with_color(Color::Red),
|
|
||||||
)
|
|
||||||
.finish()
|
|
||||||
.eprint(Source::from(context.source))
|
|
||||||
.unwrap();
|
|
||||||
return Err(());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ast::Expr::Select {
|
ast::Expr::Select {
|
||||||
@@ -890,19 +880,40 @@ fn tc_const(expr: &mut ast::Expression, source: &str) -> Result<()> {
|
|||||||
I64Const(_) => I64,
|
I64Const(_) => I64,
|
||||||
F32Const(_) => F32,
|
F32Const(_) => F32,
|
||||||
F64Const(_) => F64,
|
F64Const(_) => F64,
|
||||||
_ => {
|
_ => return report_error("Expected constant value", &expr.span, source),
|
||||||
Report::build(ReportKind::Error, (), expr.span.start)
|
|
||||||
.with_message("Expected constant value")
|
|
||||||
.with_label(
|
|
||||||
Label::new(expr.span.clone())
|
|
||||||
.with_message("Expected constant value")
|
|
||||||
.with_color(Color::Red),
|
|
||||||
)
|
|
||||||
.finish()
|
|
||||||
.eprint(Source::from(source))
|
|
||||||
.unwrap();
|
|
||||||
return Err(());
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn tc_memarg(context: &mut Context, params: &mut [ast::Expression], span: &Span) -> Result<()> {
|
||||||
|
if params.is_empty() || params.len() > 3 {
|
||||||
|
let msg = if params.is_empty() {
|
||||||
|
"Missing base address parameter"
|
||||||
|
} else {
|
||||||
|
"Too many MemArg parameters"
|
||||||
|
};
|
||||||
|
return report_error(msg, span, context.source);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (index, param) in params.iter_mut().enumerate() {
|
||||||
|
tc_expression(context, param)?;
|
||||||
|
if param.type_ != Some(I32) {
|
||||||
|
return type_mismatch(Some(I32), &span, param.type_, ¶m.span, context.source);
|
||||||
|
}
|
||||||
|
if index > 0 {
|
||||||
|
tc_const(param, context.source)?;
|
||||||
|
}
|
||||||
|
if index == 2 {
|
||||||
|
let align = param.const_i32();
|
||||||
|
if align < 0 || align > 4 {
|
||||||
|
return report_error(
|
||||||
|
&format!("Alignment {} out of range (0-4)", align),
|
||||||
|
¶m.span,
|
||||||
|
context.source,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user