implement parens for function calling syntax
This commit is contained in:
55
README.md
55
README.md
@@ -78,42 +78,47 @@ All functions in Lamm are **scoped** similarly to variables. Functions are decla
|
|||||||
|
|
||||||
```
|
```
|
||||||
: inc x + x 1
|
: inc x + x 1
|
||||||
inc 24 # => 25
|
(inc 24) # => 25
|
||||||
|
|
||||||
:. pythag a b sqrt + ** a 2.0 ** b 2.0
|
:. pythag a b sqrt + ** a 2.0 ** b 2.0
|
||||||
pythag 3 4 # => 5
|
(pythag 3 4) # => 5
|
||||||
|
|
||||||
:::::. ten'args a b c d e f g h i j
|
:::::. ten'args a b c d e f g h i j
|
||||||
[a b c d e f g h i j]
|
[a b c d e f g h i j]
|
||||||
```
|
```
|
||||||
|
|
||||||
The parameter types and return type of functions can be declared using a special syntax unique to function and lambda definitions.
|
The parameter types and return type of functions can be declared using a special syntax unique to function and lambda definitions.
|
||||||
|
Calling a function requires parenthises around the call.
|
||||||
|
|
||||||
```
|
```
|
||||||
# Takes an x of `Any` type
|
# Takes an x of `Any` type
|
||||||
: inc x + x 1
|
: inc x
|
||||||
inc 12 # => 13
|
+ x 1
|
||||||
|
(inc 12) # => 13
|
||||||
|
|
||||||
# Takes an x of `Int` and returns an `Int`
|
# Takes an x of `Int` and returns an `Int`
|
||||||
: inc ?. x Int -> Int + x 1
|
: inc ?. x Int -> Int
|
||||||
inc 9 # => 10
|
+ x 1
|
||||||
|
(inc 9) # => 10
|
||||||
```
|
```
|
||||||
|
|
||||||
The `?.` operator is unique to function declarations and is used to specify the type of an argument. There are also first class functions, here is the syntax for it.
|
The `?.` operator is unique to function declarations and is used to specify the type of an argument. There are also first class functions, here is the syntax for it.
|
||||||
|
|
||||||
```
|
```
|
||||||
# Applies a function to any value
|
# Applies a function to any value
|
||||||
:. apply : f x f x
|
:. apply : f x
|
||||||
apply \sqrt 9 # => 3
|
(f x)
|
||||||
|
(apply sqrt 9) # => 3
|
||||||
|
|
||||||
# Applies a function f which maps an Int to an Int to x
|
# Applies a function f which maps an Int to an Int to x
|
||||||
:. apply'int ?: f Int -> Int ?. x Int -> Int f x
|
:. apply'int ?: f Int -> Int ?. x Int -> Int
|
||||||
apply'int \sqrt 36 # => 6
|
(f x)
|
||||||
|
(apply'int sqrt 36) # => 6
|
||||||
```
|
```
|
||||||
|
|
||||||
The `:` operator inside of a function prototype tells Lamm that this argument must be a function where every argument and it's return type are all `Any`. This means that `: f` is essentially syntactic sugar for `?: f Any -> Any`. Also, in order to pass a function to a function, you must use the `\` operator, which tells Lamm not to call the function.
|
The `:` operator inside of a function prototype tells Lamm that this argument must be a function where every argument and it's return type are all `Any`. This means that `: f` is essentially syntactic sugar for `?: f Any -> Any`. You can pass a function with just it's identifier.
|
||||||
|
|
||||||
And off course, `:` and `?:` in function prototypes can also be extended depending on the number of arguments the function must take.
|
And of course, `:` and `?:` in function prototypes can also be extended depending on the number of arguments the function must take.
|
||||||
|
|
||||||
## Branching
|
## Branching
|
||||||
|
|
||||||
@@ -171,28 +176,28 @@ Using these, you can build a lot of fundamental functional paradigm functions.
|
|||||||
|
|
||||||
```
|
```
|
||||||
:. map : f ?. x [] -> []
|
:. map : f ?. x [] -> []
|
||||||
?? bool x
|
?? bool x
|
||||||
+ f head x map \f tail x
|
[+ (f head x) (map f tail x)
|
||||||
empty
|
empty
|
||||||
map ;x ** x 2 [1 2 3 4 5 6 7 8 9 10] # => [1 4 9 16 25 36 49 64 81 100]
|
(map ;x ** x 2 [1 2 3 4 5 6 7 8 9 10]) # => [1 4 9 16 25 36 49 64 81 100]
|
||||||
|
|
||||||
:: iterate : f i count -> []
|
:: iterate : f i count -> []
|
||||||
?? > count 0
|
?? > count 0
|
||||||
+ i iterate \f f i - count 1
|
[+ i (iterate f (f i) - count 1)
|
||||||
empty
|
empty
|
||||||
iterate (+ 1) 0 10 # => [0 1 2 3 4 5 6 7 8 9]
|
(iterate (+ 1) 0 10) # => [0 1 2 3 4 5 6 7 8 9]
|
||||||
|
|
||||||
:. take ?. n Int ?. x [] -> []
|
:. take ?. n Int ?. x [] -> []
|
||||||
?? > n 0
|
?? > n 0
|
||||||
+ head x take - n 1 tail x
|
[+ head x (take - n 1 tail x)
|
||||||
empty
|
empty
|
||||||
take 3 [1 2 3 4 5] # => [1 2 3]
|
(take 3 [1 2 3 4 5]) # => [1 2 3]
|
||||||
|
|
||||||
:. take'while ?: pred Any -> Bool ?. x [] -> []
|
:. take'while ?: pred Any -> Bool ?. x [] -> []
|
||||||
?? && bool x pred head x
|
?? && bool x (pred head x)
|
||||||
+ head x take'while \pred tail x
|
[+ head x (take'while pred tail x)
|
||||||
empty
|
empty
|
||||||
take'while (> 10) [1 3 5 7 9 11 13 15 16] # => [1 3 5 7 9]
|
(take'while (> 10) [1 3 5 7 9 11 13 15 16]) # => [1 3 5 7 9]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Lambdas
|
## Lambdas
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use super::error::Error;
|
|||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::iter::Peekable;
|
use std::iter::Peekable;
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub(crate) enum ParseTree {
|
pub(crate) enum ParseTree {
|
||||||
@@ -176,40 +177,7 @@ impl Parser {
|
|||||||
|
|
||||||
match token.token() {
|
match token.token() {
|
||||||
TokenType::Constant(c) => Ok(Some(ParseTree::Value(c))),
|
TokenType::Constant(c) => Ok(Some(ParseTree::Value(c))),
|
||||||
TokenType::Identifier(ident) => {
|
TokenType::Identifier(ident) => Ok(Some(ParseTree::Variable(ident))),
|
||||||
match self.get_object_type(&ident).ok_or(
|
|
||||||
Error::new(format!("undefined identifier {ident}"))
|
|
||||||
.location(token.line, token.location))? {
|
|
||||||
Type::Function(f) => {
|
|
||||||
let f = f.clone();
|
|
||||||
let args = self.get_args(tokens, f.1.len())?;
|
|
||||||
|
|
||||||
if args.len() < f.1.len() {
|
|
||||||
let mut counter = 0;
|
|
||||||
let func_args: Vec<Type> = f.1.iter().skip(args.len()).cloned().collect();
|
|
||||||
let (names, types): (Vec<String>, Vec<Type>) = func_args
|
|
||||||
.into_iter()
|
|
||||||
.map(|t| {
|
|
||||||
counter += 1;
|
|
||||||
(format!("{counter}"), t)
|
|
||||||
}).unzip();
|
|
||||||
let function_type = FunctionType(f.0.clone(), types);
|
|
||||||
|
|
||||||
Ok(Some(ParseTree::Value(Value::Function(Function::lambda(
|
|
||||||
function_type,
|
|
||||||
names.clone(),
|
|
||||||
Box::new(ParseTree::FunctionCall(ident,
|
|
||||||
vec![
|
|
||||||
args,
|
|
||||||
names.into_iter().map(|x| ParseTree::Variable(x)).collect()
|
|
||||||
].concat())))))))
|
|
||||||
} else {
|
|
||||||
Ok(Some(ParseTree::FunctionCall(ident, args)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => Ok(Some(ParseTree::Variable(ident))),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
TokenType::Operator(op) => match op {
|
TokenType::Operator(op) => match op {
|
||||||
Op::OpenArray => {
|
Op::OpenArray => {
|
||||||
let mut depth = 1;
|
let mut depth = 1;
|
||||||
@@ -253,7 +221,7 @@ impl Parser {
|
|||||||
|
|
||||||
// take tokens until we reach the end of this array
|
// take tokens until we reach the end of this array
|
||||||
// if we don't collect them here it causes rust to overflow computing the types
|
// if we don't collect them here it causes rust to overflow computing the types
|
||||||
let array_tokens = tokens.by_ref().take_while(|t| match t {
|
let tokens = tokens.by_ref().take_while(|t| match t {
|
||||||
Ok(t) => match t.token() {
|
Ok(t) => match t.token() {
|
||||||
TokenType::Operator(Op::OpenStatement) => {
|
TokenType::Operator(Op::OpenStatement) => {
|
||||||
depth += 1;
|
depth += 1;
|
||||||
@@ -268,22 +236,59 @@ impl Parser {
|
|||||||
_ => true,
|
_ => true,
|
||||||
}).collect::<Result<Vec<_>, Error>>()?;
|
}).collect::<Result<Vec<_>, Error>>()?;
|
||||||
|
|
||||||
let array_tokens = array_tokens
|
let mut tokens = tokens
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|t| Ok(t))
|
.map(|t| Ok(t))
|
||||||
.collect::<Vec<Result<Token, Error>>>()
|
.collect::<Vec<Result<Token, Error>>>()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.peekable();
|
.peekable();
|
||||||
|
|
||||||
let trees: Vec<ParseTree> = self.clone().trees(array_tokens)
|
if let Some(Ok(Some(Type::Function(f)))) = tokens.peek()
|
||||||
.collect::<Result<_, Error>>()?;
|
.map(|t| t.clone().and_then(|t| match t.token() {
|
||||||
|
TokenType::Identifier(ident) =>
|
||||||
|
Ok(Some(self.get_object_type(&ident).ok_or(
|
||||||
|
Error::new(format!("undefined identifier {ident}"))
|
||||||
|
.location(token.line, token.location))?)),
|
||||||
|
_ => Ok(None),
|
||||||
|
}))
|
||||||
|
{
|
||||||
|
let token = tokens.next().unwrap().unwrap();
|
||||||
|
let params: Vec<ParseTree> = self.clone().trees(tokens).collect::<Result<_, Error>>()?;
|
||||||
|
|
||||||
let tree = trees.into_iter().fold(
|
match params.len().cmp(&f.1.len()) {
|
||||||
ParseTree::Nop,
|
Ordering::Equal => Ok(Some(ParseTree::FunctionCall(token.lexeme, params))),
|
||||||
|acc, x| ParseTree::Operator(Op::Compose, vec![acc, x.clone()]),
|
Ordering::Greater => Err(Error::new(format!("too many arguments to {}", token.lexeme)).location(token.line, token.location)),
|
||||||
);
|
Ordering::Less => {
|
||||||
|
let mut counter = 0;
|
||||||
|
let func_args: Vec<Type> = f.1.iter().skip(params.len()).cloned().collect();
|
||||||
|
let (names, types): (Vec<String>, Vec<Type>) = func_args
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| {
|
||||||
|
counter += 1;
|
||||||
|
(format!("{counter}"), t)
|
||||||
|
}).unzip();
|
||||||
|
let function_type = FunctionType(f.0.clone(), types);
|
||||||
|
|
||||||
|
Ok(Some(ParseTree::Value(Value::Function(Function::lambda(
|
||||||
|
function_type,
|
||||||
|
names.clone(),
|
||||||
|
Box::new(ParseTree::FunctionCall(token.lexeme,
|
||||||
|
vec![
|
||||||
|
params,
|
||||||
|
names.into_iter().map(|x| ParseTree::Variable(x)).collect()
|
||||||
|
].concat())))))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let trees: Vec<ParseTree> = self.clone().trees(tokens).collect::<Result<_, Error>>()?;
|
||||||
|
|
||||||
Ok(Some(tree))
|
let tree = trees.into_iter().fold(
|
||||||
|
ParseTree::Nop,
|
||||||
|
|acc, x| ParseTree::Operator(Op::Compose, vec![acc, x.clone()]),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(Some(tree))
|
||||||
|
}
|
||||||
},
|
},
|
||||||
Op::Equ => {
|
Op::Equ => {
|
||||||
let token = tokens.next()
|
let token = tokens.next()
|
||||||
@@ -361,10 +366,6 @@ impl Parser {
|
|||||||
},
|
},
|
||||||
Op::LambdaDefine(arg_count) => Ok(Some(ParseTree::LambdaDefinition(self.parse_lambda_definition(tokens, arg_count)?))),
|
Op::LambdaDefine(arg_count) => Ok(Some(ParseTree::LambdaDefinition(self.parse_lambda_definition(tokens, arg_count)?))),
|
||||||
Op::Empty => Ok(Some(ParseTree::Value(Value::Array(Type::Any, vec![])))),
|
Op::Empty => Ok(Some(ParseTree::Value(Value::Array(Type::Any, vec![])))),
|
||||||
Op::NonCall => {
|
|
||||||
let name = Self::get_identifier(tokens.next())?;
|
|
||||||
Ok(Some(ParseTree::NonCall(name)))
|
|
||||||
},
|
|
||||||
Op::If => {
|
Op::If => {
|
||||||
let cond = self.parse(tokens)?
|
let cond = self.parse(tokens)?
|
||||||
.ok_or(Error::new("? statement requires a condition".into())
|
.ok_or(Error::new("? statement requires a condition".into())
|
||||||
|
|||||||
@@ -59,7 +59,6 @@ pub enum Op {
|
|||||||
Init,
|
Init,
|
||||||
Fini,
|
Fini,
|
||||||
Export,
|
Export,
|
||||||
NonCall,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Op {
|
impl fmt::Display for Op {
|
||||||
@@ -112,7 +111,6 @@ impl fmt::Display for Op {
|
|||||||
Op::Init => "init",
|
Op::Init => "init",
|
||||||
Op::Fini => "fini",
|
Op::Fini => "fini",
|
||||||
Op::Export => "export",
|
Op::Export => "export",
|
||||||
Op::NonCall => "\\",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
write!(f, "{s}")
|
write!(f, "{s}")
|
||||||
@@ -281,7 +279,6 @@ impl<R: BufRead> Tokenizer<R> {
|
|||||||
("!", Op::Not),
|
("!", Op::Not),
|
||||||
("&&", Op::And),
|
("&&", Op::And),
|
||||||
("||", Op::Or),
|
("||", Op::Or),
|
||||||
("\\", Op::NonCall),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let c = if let Some(c) = self.next_char() {
|
let c = if let Some(c) = self.next_char() {
|
||||||
|
|||||||
Reference in New Issue
Block a user