Implement better standard library interface
This commit is contained in:
parent
eaff59c88d
commit
004b7be27a
@ -16,17 +16,17 @@ use crate::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
|
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
|
||||||
pub struct BuiltInFunction {
|
pub enum BuiltInFunction {
|
||||||
name: WithPosition<Identifier>,
|
ReadLine,
|
||||||
|
WriteLine,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BuiltInFunction {
|
impl BuiltInFunction {
|
||||||
pub fn new(name: WithPosition<Identifier>) -> Self {
|
pub fn name(&self) -> &'static str {
|
||||||
Self { name }
|
match self {
|
||||||
}
|
BuiltInFunction::ReadLine => todo!(),
|
||||||
|
BuiltInFunction::WriteLine => todo!(),
|
||||||
pub fn name(&self) -> &Identifier {
|
}
|
||||||
&self.name.node
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn as_value(self) -> Value {
|
pub fn as_value(self) -> Value {
|
||||||
@ -34,8 +34,8 @@ impl BuiltInFunction {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn r#type(&self) -> Type {
|
pub fn r#type(&self) -> Type {
|
||||||
match self.name.node.as_str() {
|
match self {
|
||||||
"WRITE_LINE" => Type::Function {
|
BuiltInFunction::WriteLine => Type::Function {
|
||||||
parameter_types: vec![Type::String],
|
parameter_types: vec![Type::String],
|
||||||
return_type: Box::new(Type::None),
|
return_type: Box::new(Type::None),
|
||||||
},
|
},
|
||||||
@ -46,8 +46,8 @@ impl BuiltInFunction {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn call(&self, arguments: Vec<Value>, context: &Context) -> Result<Action, RuntimeError> {
|
pub fn call(&self, arguments: Vec<Value>, context: &Context) -> Result<Action, RuntimeError> {
|
||||||
match self.name.node.as_str() {
|
match self {
|
||||||
"INT_PARSE" => {
|
BuiltInFunction::ReadLine => {
|
||||||
let string = arguments.get(0).unwrap();
|
let string = arguments.get(0).unwrap();
|
||||||
|
|
||||||
if let ValueInner::String(_string) = string.inner().as_ref() {
|
if let ValueInner::String(_string) = string.inner().as_ref() {
|
||||||
@ -73,36 +73,36 @@ impl BuiltInFunction {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"INT_RANDOM_RANGE" => {
|
// "INT_RANDOM_RANGE" => {
|
||||||
let range = arguments.get(0).unwrap();
|
// let range = arguments.get(0).unwrap();
|
||||||
|
|
||||||
if let ValueInner::Range(range) = range.inner().as_ref() {
|
// if let ValueInner::Range(range) = range.inner().as_ref() {
|
||||||
let random = thread_rng().gen_range(range.clone());
|
// let random = thread_rng().gen_range(range.clone());
|
||||||
|
|
||||||
Ok(Action::Return(Value::integer(random)))
|
// Ok(Action::Return(Value::integer(random)))
|
||||||
} else {
|
// } else {
|
||||||
panic!("Built-in function cannot have a non-function type.")
|
// panic!("Built-in function cannot have a non-function type.")
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
"READ_LINE" => {
|
BuiltInFunction::ReadLine => {
|
||||||
let mut input = String::new();
|
let mut input = String::new();
|
||||||
|
|
||||||
stdin().read_line(&mut input)?;
|
stdin().read_line(&mut input)?;
|
||||||
|
|
||||||
Ok(Action::Return(Value::string(input)))
|
Ok(Action::Return(Value::string(input)))
|
||||||
}
|
}
|
||||||
"WRITE_LINE" => {
|
BuiltInFunction::WriteLine => {
|
||||||
println!("{}", arguments[0]);
|
println!("{}", arguments[0]);
|
||||||
|
|
||||||
Ok(Action::None)
|
Ok(Action::None)
|
||||||
}
|
}
|
||||||
"SLEEP" => {
|
// "SLEEP" => {
|
||||||
if let ValueInner::Integer(milliseconds) = arguments[0].inner().as_ref() {
|
// if let ValueInner::Integer(milliseconds) = arguments[0].inner().as_ref() {
|
||||||
thread::sleep(Duration::from_millis(*milliseconds as u64));
|
// thread::sleep(Duration::from_millis(*milliseconds as u64));
|
||||||
}
|
// }
|
||||||
|
|
||||||
Ok(Action::None)
|
// Ok(Action::None)
|
||||||
}
|
// }
|
||||||
_ => {
|
_ => {
|
||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
@ -112,6 +112,6 @@ impl BuiltInFunction {
|
|||||||
|
|
||||||
impl Display for BuiltInFunction {
|
impl Display for BuiltInFunction {
|
||||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
write!(f, "{}", self.name.node)
|
write!(f, "{}", self.name())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::BTreeMap,
|
collections::BTreeMap,
|
||||||
sync::{Arc, OnceLock, RwLock, RwLockReadGuard},
|
sync::{Arc, RwLock, RwLockReadGuard},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@ -9,17 +9,13 @@ use crate::{
|
|||||||
Interpreter, Value,
|
Interpreter, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
static STD_CONTEXT: OnceLock<Context> = OnceLock::new();
|
pub fn std_context() -> Context {
|
||||||
|
let context = Context::new();
|
||||||
|
let mut interpreter = Interpreter::new(context.clone());
|
||||||
|
|
||||||
pub fn std_context<'a>() -> &'a Context {
|
interpreter.run(include_str!("../../std/io.ds")).unwrap();
|
||||||
STD_CONTEXT.get_or_init(|| {
|
|
||||||
let context = Context::new();
|
|
||||||
let mut interpreter = Interpreter::new(context.clone());
|
|
||||||
|
|
||||||
interpreter.run(include_str!("../../std/io.ds")).unwrap();
|
context
|
||||||
|
|
||||||
context
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
|
@ -200,7 +200,6 @@ impl Error {
|
|||||||
ValidationError::ExpectedValue(_) => todo!(),
|
ValidationError::ExpectedValue(_) => todo!(),
|
||||||
ValidationError::PropertyNotFound { .. } => todo!(),
|
ValidationError::PropertyNotFound { .. } => todo!(),
|
||||||
ValidationError::WrongArguments { .. } => todo!(),
|
ValidationError::WrongArguments { .. } => todo!(),
|
||||||
ValidationError::TypeNotFound(_) => todo!(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -317,7 +316,6 @@ pub enum ValidationError {
|
|||||||
actual: Vec<Type>,
|
actual: Vec<Type>,
|
||||||
},
|
},
|
||||||
VariableNotFound(Identifier),
|
VariableNotFound(Identifier),
|
||||||
TypeNotFound(Identifier),
|
|
||||||
PropertyNotFound {
|
PropertyNotFound {
|
||||||
identifier: Identifier,
|
identifier: Identifier,
|
||||||
position: SourcePosition,
|
position: SourcePosition,
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
use std::fmt::{self, Display, Formatter};
|
use std::{
|
||||||
|
f64::{INFINITY, NAN, NEG_INFINITY},
|
||||||
|
fmt::{self, Display, Formatter},
|
||||||
|
};
|
||||||
|
|
||||||
use chumsky::prelude::*;
|
use chumsky::prelude::*;
|
||||||
|
|
||||||
@ -7,6 +10,7 @@ use crate::error::Error;
|
|||||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
pub enum Token<'src> {
|
pub enum Token<'src> {
|
||||||
Boolean(bool),
|
Boolean(bool),
|
||||||
|
BuiltInIdentifier(BuiltInIdentifier),
|
||||||
Integer(i64),
|
Integer(i64),
|
||||||
Float(f64),
|
Float(f64),
|
||||||
String(&'src str),
|
String(&'src str),
|
||||||
@ -16,6 +20,37 @@ pub enum Token<'src> {
|
|||||||
Keyword(Keyword),
|
Keyword(Keyword),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'src> Display for Token<'src> {
|
||||||
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Token::Boolean(boolean) => write!(f, "{boolean}"),
|
||||||
|
Token::BuiltInIdentifier(built_in_identifier) => write!(f, "{built_in_identifier}"),
|
||||||
|
Token::Integer(integer) => write!(f, "{integer}"),
|
||||||
|
Token::Float(float) => write!(f, "{float}"),
|
||||||
|
Token::String(string) => write!(f, "{string}"),
|
||||||
|
Token::Identifier(string) => write!(f, "{string}"),
|
||||||
|
Token::Operator(operator) => write!(f, "{operator}"),
|
||||||
|
Token::Control(control) => write!(f, "{control}"),
|
||||||
|
Token::Keyword(keyword) => write!(f, "{keyword}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum BuiltInIdentifier {
|
||||||
|
ReadLine,
|
||||||
|
WriteLine,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for BuiltInIdentifier {
|
||||||
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
BuiltInIdentifier::ReadLine => write!(f, "__READ_LINE__"),
|
||||||
|
BuiltInIdentifier::WriteLine => write!(f, "__WRITE_LINE__"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
pub enum Keyword {
|
pub enum Keyword {
|
||||||
Any,
|
Any,
|
||||||
@ -143,21 +178,6 @@ impl Display for Control {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'src> Display for Token<'src> {
|
|
||||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
Token::Boolean(boolean) => write!(f, "{boolean}"),
|
|
||||||
Token::Integer(integer) => write!(f, "{integer}"),
|
|
||||||
Token::Float(float) => write!(f, "{float}"),
|
|
||||||
Token::String(string) => write!(f, "{string}"),
|
|
||||||
Token::Identifier(string) => write!(f, "{string}"),
|
|
||||||
Token::Operator(operator) => write!(f, "{operator}"),
|
|
||||||
Token::Control(control) => write!(f, "{control}"),
|
|
||||||
Token::Keyword(keyword) => write!(f, "{keyword}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lex<'src>(source: &'src str) -> Result<Vec<(Token<'src>, SimpleSpan)>, Vec<Error>> {
|
pub fn lex<'src>(source: &'src str) -> Result<Vec<(Token<'src>, SimpleSpan)>, Vec<Error>> {
|
||||||
lexer()
|
lexer()
|
||||||
.parse(source)
|
.parse(source)
|
||||||
@ -184,17 +204,19 @@ pub fn lexer<'src>() -> impl Parser<
|
|||||||
.to_slice()
|
.to_slice()
|
||||||
.map(|text: &str| Token::Float(text.parse().unwrap()));
|
.map(|text: &str| Token::Float(text.parse().unwrap()));
|
||||||
|
|
||||||
let float_other = choice((just("Infinity"), just("-Infinity"), just("NaN")))
|
let float = choice((
|
||||||
.map(|text| Token::Float(text.parse().unwrap()));
|
float_numeric,
|
||||||
|
just("Infinity").to(Token::Float(INFINITY)),
|
||||||
let float = choice((float_numeric, float_other));
|
just("-Infinity").to(Token::Float(NEG_INFINITY)),
|
||||||
|
just("NaN").to(Token::Float(NAN)),
|
||||||
|
));
|
||||||
|
|
||||||
let integer = just('-')
|
let integer = just('-')
|
||||||
.or_not()
|
.or_not()
|
||||||
.then(text::int(10))
|
.then(text::int(10))
|
||||||
.to_slice()
|
.to_slice()
|
||||||
.map(|text: &str| {
|
.map(|text: &str| {
|
||||||
let integer = text.parse::<i64>().unwrap();
|
let integer = text.parse().unwrap();
|
||||||
|
|
||||||
Token::Integer(integer)
|
Token::Integer(integer)
|
||||||
});
|
});
|
||||||
@ -278,8 +300,22 @@ pub fn lexer<'src>() -> impl Parser<
|
|||||||
))
|
))
|
||||||
.map(Token::Keyword);
|
.map(Token::Keyword);
|
||||||
|
|
||||||
|
let built_in_identifier = choice((
|
||||||
|
just("__READ_LINE__").to(BuiltInIdentifier::ReadLine),
|
||||||
|
just("__WRITE_LINE__").to(BuiltInIdentifier::WriteLine),
|
||||||
|
))
|
||||||
|
.map(Token::BuiltInIdentifier);
|
||||||
|
|
||||||
choice((
|
choice((
|
||||||
boolean, float, integer, string, keyword, identifier, control, operator,
|
boolean,
|
||||||
|
float,
|
||||||
|
integer,
|
||||||
|
string,
|
||||||
|
keyword,
|
||||||
|
identifier,
|
||||||
|
control,
|
||||||
|
operator,
|
||||||
|
built_in_identifier,
|
||||||
))
|
))
|
||||||
.map_with(|token, state| (token, state.span()))
|
.map_with(|token, state| (token, state.span()))
|
||||||
.padded()
|
.padded()
|
||||||
|
@ -13,7 +13,7 @@ use parser::parse;
|
|||||||
pub use value::Value;
|
pub use value::Value;
|
||||||
|
|
||||||
pub fn interpret(source: &str) -> Result<Option<Value>, Vec<Error>> {
|
pub fn interpret(source: &str) -> Result<Option<Value>, Vec<Error>> {
|
||||||
let mut interpreter = Interpreter::new(std_context().clone());
|
let mut interpreter = Interpreter::new(std_context());
|
||||||
|
|
||||||
interpreter.run(source)
|
interpreter.run(source)
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,7 @@ use crate::{
|
|||||||
abstract_tree::*,
|
abstract_tree::*,
|
||||||
built_in_functions::BuiltInFunction,
|
built_in_functions::BuiltInFunction,
|
||||||
error::Error,
|
error::Error,
|
||||||
lexer::{Control, Keyword, Operator, Token},
|
lexer::{BuiltInIdentifier, Control, Keyword, Operator, Token},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub type ParserInput<'src> =
|
pub type ParserInput<'src> =
|
||||||
@ -233,12 +233,20 @@ pub fn parser<'src>() -> impl Parser<
|
|||||||
.with_position(state.span())
|
.with_position(state.span())
|
||||||
});
|
});
|
||||||
|
|
||||||
let built_in_function = just(Token::Control(Control::Dollar))
|
let built_in_function = {
|
||||||
.ignore_then(positioned_identifier.clone())
|
select! {
|
||||||
.map_with(|identifier, state| {
|
Token::BuiltInIdentifier(built_in_identifier) => {
|
||||||
Expression::Value(ValueNode::BuiltInFunction(BuiltInFunction::new(identifier)))
|
match built_in_identifier {
|
||||||
.with_position(state.span())
|
BuiltInIdentifier::ReadLine => BuiltInFunction::ReadLine,
|
||||||
});
|
BuiltInIdentifier::WriteLine => BuiltInFunction::WriteLine,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.map_with(|built_in_function, state| {
|
||||||
|
Expression::Value(ValueNode::BuiltInFunction(built_in_function))
|
||||||
|
.with_position(state.span())
|
||||||
|
});
|
||||||
|
|
||||||
let atom = choice((
|
let atom = choice((
|
||||||
built_in_function.clone(),
|
built_in_function.clone(),
|
||||||
@ -535,11 +543,9 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn built_in_function() {
|
fn built_in_function() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parse(&lex("$READ_LINE").unwrap()).unwrap()[0].node,
|
parse(&lex("__READ_LINE__").unwrap()).unwrap()[0].node,
|
||||||
Statement::Expression(Expression::Value(ValueNode::BuiltInFunction(
|
Statement::Expression(Expression::Value(ValueNode::BuiltInFunction(
|
||||||
BuiltInFunction::new(
|
BuiltInFunction::ReadLine
|
||||||
Identifier::new("READ_LINE".to_string()).with_position((1, 10))
|
|
||||||
)
|
|
||||||
)))
|
)))
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -230,7 +230,7 @@ impl ValueInner {
|
|||||||
if let Some(r#type) = context.get_type(name)? {
|
if let Some(r#type) = context.get_type(name)? {
|
||||||
r#type
|
r#type
|
||||||
} else {
|
} else {
|
||||||
return Err(ValidationError::TypeNotFound(name.clone()));
|
return Err(ValidationError::VariableNotFound(name.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -3,7 +3,6 @@ use dust_lang::{
|
|||||||
error::{Error, TypeConflict, ValidationError},
|
error::{Error, TypeConflict, ValidationError},
|
||||||
*,
|
*,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn simple_structure() {
|
fn simple_structure() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@ -101,7 +100,7 @@ fn undefined_struct() {
|
|||||||
"
|
"
|
||||||
),
|
),
|
||||||
Err(vec![Error::Validation {
|
Err(vec![Error::Validation {
|
||||||
error: error::ValidationError::TypeNotFound(Identifier::new("Foo")),
|
error: error::ValidationError::VariableNotFound(Identifier::new("Foo")),
|
||||||
position: (17, 69).into()
|
position: (17, 69).into()
|
||||||
}])
|
}])
|
||||||
)
|
)
|
||||||
|
Loading…
Reference in New Issue
Block a user