updated rust ast through structs to work

This commit is contained in:
Andrew Segavac
2021-08-08 11:42:26 -06:00
parent 37d998d6b5
commit 10df785c8f
8 changed files with 343 additions and 619 deletions

View File

@@ -1,86 +1,73 @@
use std::collections::HashMap;
use crate::types;
use std::cell::RefCell;
pub struct IdGenerator {
counter: i64,
counter: RefCell<i64>,
}
impl IdGenerator {
pub fn new() -> Self {
IdGenerator{counter: 0}
IdGenerator{counter: RefCell::new(0)}
}
pub fn next(&mut self) -> String {
self.counter += 1;
("S" + self.counter.to_string()).to_string()
pub fn next(&self) -> String {
*self.counter.borrow_mut() += 1;
("S".to_owned() + &self.counter.borrow().to_string()).to_string()
}
}
pub fn new_named(name: String) -> {
ast::TypeUsage::Named(ast::NamedTypeUsage{
name: ast::Identifier{
name: ast::Spanned{
span: ast::Span{left: 0, right: 0}, //todo: figure out a sane value for these
value: name,
}
}
)
}
pub fn new_unit() -> {
ast::TypeUsage::Named(ast::NamedTypeUsage{
name: ast::Identifier{
name: ast::Spanned{
span: ast::Span{left: 0, right: 0}, //todo: figure out a sane value for these
pub fn new_unit() -> TypeUsage {
TypeUsage::Named(NamedTypeUsage{
name: Identifier{
name: Spanned{
span: Span{left: 0, right: 0}, //todo: figure out a sane value for these
value: "()".to_string(),
}
}
)
})
}
pub fn new_never() -> {
ast::TypeUsage::Named(ast::NamedTypeUsage{
name: ast::Identifier{
name: ast::Spanned{
span: ast::Span{left: 0, right: 0}, //todo: figure out a sane value for these
pub fn new_never() -> TypeUsage {
TypeUsage::Named(NamedTypeUsage{
name: Identifier{
name: Spanned{
span: Span{left: 0, right: 0}, //todo: figure out a sane value for these
value: "!".to_string(),
}
}
)
})
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Span {
pub left: usize,
pub right: usize
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Spanned<T> {
pub span: Span,
pub value: T,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FunctionTypeUsage {
pub arguments: Vec<TypeUsage>,
pub return_type: Box<TypeUsage>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NamedTypeUsage {
name: Identifier,
pub name: Identifier,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UnknownTypeUsage {
name: String,
pub name: String,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TypeUsage {
Function(FunctionTypeUsage),
Named(NamedTypeUsage),
@@ -88,38 +75,38 @@ pub enum TypeUsage {
}
impl TypeUsage {
pub fn new_unknown(id_gen: &mut IdGenerator) -> TypeUsage {
pub fn new_unknown(id_gen: &IdGenerator) -> TypeUsage {
return TypeUsage::Unknown(UnknownTypeUsage{
name: id_gen.next(),
});
}
pub fn new_named(identifier: &Identifier) -> TypeUsage {
pub fn new_named(identifier: Identifier) -> TypeUsage {
return TypeUsage::Named(NamedTypeUsage{
name: identifier.clone(),
});
}
pub fn new_builtin(name: String) -> TypeUsage {
ast::TypeUsage::Named(ast::NamedTypeUsage{
name: ast::Identifier{
name: ast::Spanned{
span: ast::Span{left: 0, right: 0}, //todo: figure out a sane value for these
TypeUsage::Named(NamedTypeUsage{
name: Identifier{
name: Spanned{
span: Span{left: 0, right: 0}, //todo: figure out a sane value for these
value: name,
}
}
)
})
}
pub fn new_function(arg_count: usize, id_gen: &mut IdGenerator) -> TypeUsage {
pub fn new_function(arg_count: usize, id_gen: &IdGenerator) -> TypeUsage {
return TypeUsage::Function(FunctionTypeUsage{
arguments: 0..arg_count.map(|_| => TypeUsage.new_unknown(&mut id_gen)).collect(),
return_type: Box::new(TypeUsage.new_unknown(&mut id_gen)),
arguments: (0..arg_count).map(|_| TypeUsage::new_unknown(&id_gen)).collect(),
return_type: Box::new(TypeUsage::new_unknown(&id_gen)),
});
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Operator {
Mul,
Div,
@@ -127,98 +114,100 @@ pub enum Operator {
Minus,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LiteralInt {
pub value: Spanned<i64>,
pub value: Spanned<String>,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LiteralFloat {
pub value: Spanned<f64>,
pub value: Spanned<String>,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LiteralStruct {
pub name: Identifier,
pub fields: HashMap<Identifier, Expression>,
pub fields: Vec<(Identifier, Expression)>,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Identifier {
pub name: Spanned<String>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FunctionCall {
pub source: Expression,
pub arguments: Vec<Expression>,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StructGetter {
pub source: Expression,
pub attribute: Identifier,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Operation {
pub left: Expression,
pub op: Operator,
pub right: Expression,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VariableUsage {
pub name: Identifier,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Subexpression {
LiteralInt(LiteralInt),
LiteralFloat(LiteralFloat),
LiteralStruct(LiteralStruct),
FunctionCall(FunctionCall),
Identifier(Identifier),
VariableUsage(VariableUsage),
StructGetter(StructGetter),
Block(Block),
Op(Operation),
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Expression {
pub subexpression: Spanned<Box<Subexpression>>,
pub subexpression: Box<Subexpression>,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ReturnStatement {
pub source: Expression,
};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct LetStatement {
variable_name: Identifier,
expression: Expression,
type_: TypeUsage,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LetStatement {
pub variable_name: Identifier,
pub expression: Expression,
pub type_: TypeUsage,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AssignmentTarget {
Variable(VariableUsage),
StructAttr(StructGetter),
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AssignmentStatement {
pub source: AssignmentTarget,
pub expression: Expression,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Statement {
Return(ReturnStatement),
Let(LetStatement),
@@ -226,75 +215,75 @@ pub enum Statement {
Expression(Expression),
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Block {
pub statements: Vec<Statement>,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VariableDeclaration {
pub name: Identifier,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FunctionDeclaration {
pub name: Identifier,
pub arguments: Vec<VariableDeclaration>,
pub return_type: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Function {
pub declaration: FunctionDeclaration,
pub block: Block,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PrimitiveTypeDeclaration {
pub name: String, // cannot be identifier as it's not declared anywhere specific, it's builtins
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StructField {
pub name: Identifier,
pub type_: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StructTypeDeclaration {
pub name: Identifier,
pub fields: Vec<StructField>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AliasTypeDeclaration {
pub name: Identifier,
pub replaces: TypeUsage,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TypeDeclaration {
Struct(StructTypeDeclaration),
Primitive(PrimitiveTypeDeclaration),
Alias(AliasTypeDeclaration),
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Impl {
pub struct_name: Identifier,
pub functions: Vec<Function>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ModuleItem {
Function(Function),
TypeDeclaration(TypeDeclaration),
Impl(Impl),
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Module {
pub items: Vec<ModuleItem>,
}

View File

@@ -1,90 +1,129 @@
use std::str::FromStr;
use crate::ast;
use crate::types;
grammar(id_generator: ast::IdGenerator);
grammar(id_generator: &ast::IdGenerator);
match {
r"[0-9]+",
r"[0-9]+\.[0-9]+",
r"[A-Za-z_][A-Za-z0-9_]*",
":",
";",
"{",
"}",
"(",
")",
".",
"+",
"-",
"*",
"/",
"fn",
"return",
"let",
"=",
"type",
"struct",
"impl",
",",
r"\s*" => { },
r"//[^\n\r]*[\n\r]*" => { }, // `// comment`
}
pub TypeUsage: ast::TypeUsage = {
"fn" "(" <args:Comma<TypeUsage>> ")" => ast::TypeUsage::Function(ast::FunctionTypeUsage{arguments: args, return_type: Box::new(ast::new_unit())}),
"fn" "(" <args:Comma<TypeUsage>> ")" ":" <return_type:TypeUsage> => ast::TypeUsage::Function(ast::FunctionTypeUsage{arguments: args, return_type: Box::new(return_type)),
<name:SpannedIdentifier> => ast::TypeUsage::Named(ast::NamedTypeUsage{name: name})
pub LiteralInt: String = {
<literal:r"[0-9]+"> => literal.to_string()
};
pub LiteralInt: i64 = {
<literal:r"[0-9]+"> => i64::from_str(literal).unwrap()
pub SpannedLiteralInt: ast::LiteralInt = {
<literal_int:Spanned<LiteralInt>> => ast::LiteralInt{value: literal_int, type_: ast::TypeUsage::new_builtin("i64".to_string())}
};
pub SpannedLiteralInt: ast::LiteralInt {
<literal_int:Spanned<LiteralInt>> => ast::LiteralInt{value: literal_int, type_: ast::TypeUsage::new_builtin("i64")}
pub LiteralFloat: String = {
<literal:r"[0-9]+\.[0-9]+"> => literal.to_string()
};
pub LiteralFloat: f64 = {
<literal:r"[0-9]+\.[0-9]+"> => f64::from_str(literal).unwrap()
};
pub SpannedLiteralInt: ast::LiteralFloat {
<literal_float:Spanned<LiteralFloat>> => ast::LiteralFloat{value: literal_float, type_: ast::TypeUsage::new_builtin("f64")}
pub SpannedLiteralFloat: ast::LiteralFloat = {
<literal_float:Spanned<LiteralFloat>> => ast::LiteralFloat{value: literal_float, type_: ast::TypeUsage::new_builtin("f64".to_string())}
};
pub Identifier: String = {
<i:r"[A-Za-z_][A-Za-z0-9_]*"> => i.to_string()
};
pub LiteralStructField: (String, Expression) {
pub LiteralStructField: (ast::Identifier, ast::Expression) = {
<field:SpannedIdentifier> ":" <expr:Expression> => (field, expr)
};
pub LiteralStruct: ast::LiteralStruct {
<i:SpannedIdentifier> "{" <field_list:Comma<LiteralStructField>> "}" => LiteralStruct{
name: i,
fields: field_list.into_iter().collect(),
pub LiteralStruct: ast::LiteralStruct = {
<i:SpannedIdentifier> "{" <field_list:Comma<LiteralStructField>> "}" => ast::LiteralStruct{
name: i.clone(),
fields: field_list,
type_: ast::TypeUsage::new_named(i.clone()),
}
};
pub SpannedIdentifier: ast::Identifier {
pub SpannedIdentifier: ast::Identifier = {
<i:Spanned<Identifier>> => ast::Identifier{name: i}
};
pub FunctionCall: ast::FunctionCall = {
<source:Expression> "(" <args:Comma<Expression>> ")" => ast::FunctionCall{source: source, arguments: args, type_: ast::TypeUsage::new_unknown(&mut id_generator)}
<source:Term> "(" <args:Comma<Expression>> ")" => ast::FunctionCall{source: source, arguments: args, type_: ast::TypeUsage::new_unknown(&id_generator)}
};
pub StructGetter: ast::StructGetter = {
<source:Expression> "." <field:SpannedIdentifier> => ast::StructGetter{source: source, attribute: field, type: ast::TypeUsage::new_unknown(&mut id_generator)}
<source:Term> "." <field:SpannedIdentifier> => ast::StructGetter{source: source, attribute: field, type_: ast::TypeUsage::new_unknown(&id_generator)}
};
pub VariableUsage: ast::VariableUsage = {
<identifier:SpannedIdentifier> => ast::VariableUsage{name: identifier, type_: ast::TypeUsage::new_unknown(&mut id_generator)}
};
pub Subxpression: Box<ast::Subexpression> = {
<l:Expression> "+" <r:Factor> => Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Plus, right: r})),
<l:Expression> "-" <r:Factor> => Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Minus, right: r})),
Factor,
};
pub Factor: Box<ast::Subexpression> = {
<l:Factor> "*" <r:Term> => Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Mul, right: r})),
<l:Factor> "/" <r:Term> => Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Div, right: r})),
Term,
};
pub Term: Box<ast::Subexpression> = {
SpannedLiteralInt => Box::new(ast::Subexpression::LiteralInt(<>)),
SpannedLiteralFloat => Box::new(ast::Subexpression::LiteralFloat(<>)),
SpannedLiteralStruct => Box::new(ast::Subexpression::LiteralStruct(<>)),
FunctionCall => Box::new(ast::Subexpression::FunctionCall(<>)),
Identifier => Box::new(ast::Subexpression::Identifier(<>)),
"(" <e:Expression> ")" => e.subexpression,
<identifier:SpannedIdentifier> => ast::VariableUsage{name: identifier, type_: ast::TypeUsage::new_unknown(&id_generator)}
};
pub Expression: ast::Expression = {
<sub:Subxpression> => ast::Expression{subexpression: sub, type_: ast::TypeUsage::new_unknown(&mut id_generator)}
<l:Expression> "+" <r:Factor> => {
ast::Expression{
subexpression: Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Plus, right: r})),
type_: ast::TypeUsage::new_unknown(&id_generator),
}
},
<l:Expression> "-" <r:Factor> => {
ast::Expression{
subexpression: Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Minus, right: r})),
type_: ast::TypeUsage::new_unknown(&id_generator),
}
},
Factor,
};
pub Factor: ast::Expression = {
<l:Factor> "*" <r:Term> => {
ast::Expression{
subexpression: Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Mul, right: r})),
type_: ast::TypeUsage::new_unknown(&id_generator),
}
},
<l:Factor> "/" <r:Term> => {
ast::Expression{
subexpression: Box::new(ast::Subexpression::Op(ast::Operation{left: l, op: ast::Operator::Div, right: r})),
type_: ast::TypeUsage::new_unknown(&id_generator),
}
},
Term,
};
pub Term: ast::Expression = {
SpannedLiteralInt => ast::Expression{subexpression: Box::new(ast::Subexpression::LiteralInt(<>)), type_: ast::TypeUsage::new_unknown(&id_generator)},
SpannedLiteralFloat => ast::Expression{subexpression: Box::new(ast::Subexpression::LiteralFloat(<>)), type_: ast::TypeUsage::new_unknown(&id_generator)},
LiteralStruct => ast::Expression{subexpression: Box::new(ast::Subexpression::LiteralStruct(<>)), type_: ast::TypeUsage::new_unknown(&id_generator)},
FunctionCall => ast::Expression{subexpression: Box::new(ast::Subexpression::FunctionCall(<>)), type_: ast::TypeUsage::new_unknown(&id_generator)},
StructGetter => ast::Expression{subexpression: Box::new(ast::Subexpression::StructGetter(<>)), type_: ast::TypeUsage::new_unknown(&id_generator)},
VariableUsage => ast::Expression{subexpression: Box::new(ast::Subexpression::VariableUsage(<>)), type_: ast::TypeUsage::new_unknown(&id_generator)},
Block => ast::Expression{subexpression: Box::new(ast::Subexpression::Block(<>)), type_: ast::TypeUsage::new_unknown(&id_generator)},
"(" <e:Expression> ")" => e,
};
pub ReturnStatement: ast::ReturnStatement = {
"return" <e:Expression> => ast::ReturnStatement{source: e}
};
@@ -92,82 +131,82 @@ pub ReturnStatement: ast::ReturnStatement = {
pub LetStatement: ast::LetStatement = {
//TODO: support destructuring with tuples, when they exist.
//TODO: add mut, weak
"let" <n:SpannedIdentifier> "=" <e:Expression> => ast::LetStatement{variable_name: n, type_usage: ast::TypeUsage::new_unknown(&mut id_generator), expression: e},
"let" <n:SpannedIdentifier> ":" <t:TypeUsage> "=" <e:Expression> => ast::LetStatement{variable_name: n, type_usage: ast::TypeUsage::Named(ast::NamedTypeUsage{name: t}), expression: e},
"let" <n:SpannedIdentifier> "=" <e:Expression> => ast::LetStatement{variable_name: n, type_: ast::TypeUsage::new_unknown(&id_generator), expression: e},
"let" <n:SpannedIdentifier> ":" <t:TypeUsage> "=" <e:Expression> => ast::LetStatement{variable_name: n, type_: t, expression: e},
};
pub AssignmentStatement: ast::AssignmentStatement {
pub AssignmentStatement: ast::AssignmentStatement = {
<v:VariableUsage> "=" <e:Expression> => ast::AssignmentStatement{source: ast::AssignmentTarget::Variable(v), expression: e},
<sg:StructGetter> "=" <e:Expression> => ast::AssignmentStatement{source: ast::AssignmentTarget::StructAttr(sg), expression: e},
}
};
pub Statement: ast::Statement = {
<r:ReturnStatement> ";" => ast::Statement::Return(r),
<l:LetStatement> ";" => ast::Statement::Let(l),
<a:AssignmentStatement> ";" => ast::Statement::Assignment(l),
<a:AssignmentStatement> ";" => ast::Statement::Assignment(a),
<e:Expression> ";" => ast::Statement::Expression(e),
}
};
pub Block: ast::Block = {
"{" <v:(Statement ";")*> <e:Expression?> "}" => match e {
None => ast::Block{statements: s, type_: ast::new_never()},
"{" <v:(<Statement>)*> <e:Expression?> "}" => match e {
None => ast::Block{statements: v, type_: ast::new_never()},
Some(e) => {
let mut v = v;
v.push(ast::Statement::Expression(e));
ast::Block{statements: v, type_: ast::TypeUsage::new_unknown(&mut id_generator)}
ast::Block{statements: v, type_: ast::TypeUsage::new_unknown(&id_generator)}
}
}
}
};
pub TypeUsage: ast::TypeUsage = {
<n:SpannedIdentifier> => ast::TypeUsage::Named(ast::NamedTypeUsage{name: n}),
"fn" "(" <args:Comma<TypeUsage>> ")" => ast::TypeUsage::Function(ast::FunctionTypeUsage{arguments: args, return_type: Box::new(ast::TypeUsage::new_unknown(&mut id_generator))}),
"fn" "(" <args:Comma<TypeUsage>> ")" => ast::TypeUsage::Function(ast::FunctionTypeUsage{arguments: args, return_type: Box::new(ast::TypeUsage::new_unknown(&id_generator))}),
"fn" "(" <args:Comma<TypeUsage>> ")" ":" <rt:TypeUsage> => ast::TypeUsage::Function(ast::FunctionTypeUsage{arguments: args, return_type: Box::new(rt)}),
}
};
pub VariableDeclaration: ast::VariableDeclaration = {
<i:SpannedIdentifier> ":" <t:TypeUsage> => ast::VariableDeclaration{name: i, type_usage: t},
}
<i:SpannedIdentifier> ":" <t:TypeUsage> => ast::VariableDeclaration{name: i, type_: t},
};
pub FunctionDeclaration: ast::FunctionDeclaration {
"fn" <n:SpannedIdentifier> "(" <args:Comma<VariableDeclaration>> ")" => ast::FunctionDeclaration{name: n, arguments: args, return_type: ast::TypeUsage::new_unknown(&mut id_generator)},
pub FunctionDeclaration: ast::FunctionDeclaration = {
"fn" <n:SpannedIdentifier> "(" <args:Comma<VariableDeclaration>> ")" => ast::FunctionDeclaration{name: n, arguments: args, return_type: ast::TypeUsage::new_unknown(&id_generator)},
"fn" <n:SpannedIdentifier> "(" <args:Comma<VariableDeclaration>> ")" ":" <rt:TypeUsage> => ast::FunctionDeclaration{name: n, arguments: args, return_type: rt},
}
};
pub Function: ast::Function = {
<d:FunctionDeclaration> <b:Block> => ast::Function{declaration: d, block: b}
}
};
pub StructField: ast::StructField = {
<i:SpannedIdentifier> ":" <t:TypeUsage> => (i, t),
}
<i:SpannedIdentifier> ":" <t:TypeUsage> => ast::StructField{name: i, type_: t},
};
pub StructTypeDeclaration: ast::StructTypeDeclaration {
"type" <i:SpannedIdentifier> "struct" "{" Comma<StructField> "}"
}
pub StructTypeDeclaration: ast::StructTypeDeclaration = {
"type" <i:SpannedIdentifier> "struct" "{" <f:Comma<StructField>> "}" => ast::StructTypeDeclaration{name: i, fields: f}
};
pub TypeAliasDeclaration: ast::TypeAliasDeclaration {
pub AliasTypeDeclaration: ast::AliasTypeDeclaration = {
"type" <i:SpannedIdentifier> "=" <t:TypeUsage> ";" => ast::AliasTypeDeclaration{name: i, replaces: t}
}
};
pub TypeDeclaration: ast::TypeDeclaration {
pub TypeDeclaration: ast::TypeDeclaration = {
<s:StructTypeDeclaration> => ast::TypeDeclaration::Struct(s),
<a:AliasTypeDeclaration> => ast::TypeDeclaration::Alias(a),
}
};
pub Impl: ast::Impl {
"impl" <i:SpannedIdentifier> "{" <f:Function*> "}" => ast::Impl{struct_name: i, functions: s}
}
pub Impl: ast::Impl = {
"impl" <i:SpannedIdentifier> "{" <f:Function*> "}" => ast::Impl{struct_name: i, functions: f}
};
pub ModuleItem: ast::ModuleItem {
pub ModuleItem: ast::ModuleItem = {
<f:Function> => ast::ModuleItem::Function(f),
<td:TypeDeclaration> => ast::ModuleItem::TypeDeclaration(td),
<i:Impl> => ast::ModuleItem::Impl(i),
}
};
pub Module: ast::Module = {
<i:ModuleItem*> => ast::Module{items: i}
}
};
// From https://lalrpop.github.io/lalrpop/tutorial/006_macros.html
// Comma seperated list of T with optional trailing comma

View File

@@ -1,4 +1,4 @@
mod types;
// mod types;
mod ast;
#[macro_use] extern crate lalrpop_util;
@@ -7,7 +7,7 @@ lalrpop_mod!(pub grammar); // synthesized by LALRPOP
use std::fs;
use std::io::Write;
// mod compiler;
use inkwell::context::Context;
// use inkwell::context::Context;
extern crate clap;
use clap::{Arg, App};
@@ -38,7 +38,9 @@ fn main() {
let output = matches.value_of("OUTPUT").unwrap_or(default_output);
let contents = fs::read_to_string(input).expect("input file not found");
let module_ast = grammar::ModuleParser::new().parse(&contents).unwrap(); //TODO: convert to error
let unknown_id_gen = ast::IdGenerator::new();
let module_ast = grammar::ModuleParser::new().parse(&unknown_id_gen, &contents).unwrap(); //TODO: convert to error
println!("ast: {:#?}", &module_ast);
// let context = Context::create();
@@ -52,33 +54,34 @@ fn main() {
#[test]
fn grammar() {
assert!(grammar::LiteralIntParser::new().parse("22").is_ok());
assert!(grammar::IdentifierParser::new().parse("foo").is_ok());
assert!(grammar::LiteralIntParser::new().parse("2a").is_err());
let id_gen = ast::IdGenerator::new();
assert!(grammar::LiteralIntParser::new().parse(&id_gen, "22").is_ok());
assert!(grammar::IdentifierParser::new().parse(&id_gen, "foo").is_ok());
assert!(grammar::LiteralIntParser::new().parse(&id_gen, "2a").is_err());
assert!(grammar::TermParser::new().parse("22").is_ok());
assert!(grammar::TermParser::new().parse("foo").is_ok());
assert!(grammar::TermParser::new().parse(&id_gen, "22").is_ok());
assert!(grammar::TermParser::new().parse(&id_gen, "foo").is_ok());
assert!(grammar::ExpressionParser::new().parse("22 * foo").is_ok());
assert!(grammar::ExpressionParser::new().parse("22 * 33").is_ok());
assert!(grammar::ExpressionParser::new().parse("(22 * 33) + 24").is_ok());
assert!(grammar::ExpressionParser::new().parse(&id_gen, "22 * foo").is_ok());
assert!(grammar::ExpressionParser::new().parse(&id_gen, "22 * 33").is_ok());
assert!(grammar::ExpressionParser::new().parse(&id_gen, "(22 * 33) + 24").is_ok());
assert!(grammar::BlockParser::new().parse("{ (22 * 33) + 24 }").is_ok());
assert!(grammar::BlockParser::new().parse("{ (22 * 33) + 24; 24 }").is_ok());
assert!(grammar::BlockParser::new().parse(&id_gen, "{ (22 * 33) + 24 }").is_ok());
assert!(grammar::BlockParser::new().parse(&id_gen, "{ (22 * 33) + 24; 25 }").is_ok());
// assert!(grammar::BlockParser::new().parse("{ (22 * 33) + 24\n 24 }").is_ok());
assert!(grammar::BlockParser::new().parse("{ }").is_err());
assert!(grammar::BlockParser::new().parse(&id_gen, "{ }").is_ok());
assert!(grammar::VariableDeclarationParser::new().parse("foo: Int32").is_ok());
assert!(grammar::VariableDeclarationParser::new().parse("foo").is_err());
assert!(grammar::VariableDeclarationParser::new().parse("1234").is_err());
assert!(grammar::VariableDeclarationParser::new().parse(&id_gen, "foo: Int32").is_ok());
assert!(grammar::VariableDeclarationParser::new().parse(&id_gen, "foo").is_err());
assert!(grammar::VariableDeclarationParser::new().parse(&id_gen, "1234").is_err());
assert!(grammar::FunctionParser::new().parse("fn add(a: Int32, b: Int32) Int32 { a + b }").is_ok());
assert!(grammar::FunctionParser::new().parse("fn random_dice_roll() Int32 { 4 }").is_ok());
assert!(grammar::FunctionParser::new().parse("fn add(a: Int32, b: Int32) Int32 { a + }").is_err());
assert!(grammar::FunctionParser::new().parse("fn add(a: Int32, b: Int32) Int32").is_err());
assert!(grammar::FunctionParser::new().parse(&id_gen, "fn add(a: Int32, b: Int32): Int32 { a + b }").is_ok());
assert!(grammar::FunctionParser::new().parse(&id_gen, "fn random_dice_roll(): Int32 { 4 }").is_ok());
assert!(grammar::FunctionParser::new().parse(&id_gen, "fn add(a: Int32, b: Int32): Int32 { a + }").is_err());
assert!(grammar::FunctionParser::new().parse(&id_gen, "fn add(a: Int32, b: Int32): Int32").is_err());
assert!(grammar::FunctionCallParser::new().parse("foo(1, 2)").is_ok());
assert!(grammar::FunctionCallParser::new().parse(&id_gen, "foo(1, 2)").is_ok());
assert!(grammar::ModuleParser::new().parse("fn add(a: Int32, b: Int32) Int32 { a + b }").is_ok());
assert!(grammar::ModuleParser::new().parse("fn add(a: Int32, b: Int32) Int32 { a + b } fn subtract(a: Int32, b: Int32) Int32 { a - b }").is_ok());
assert!(grammar::ModuleParser::new().parse(&id_gen, "fn add(a: Int32, b: Int32): Int32 { a + b }").is_ok());
assert!(grammar::ModuleParser::new().parse(&id_gen, "fn add(a: Int32, b: Int32): Int32 { a + b } fn subtract(a: Int32, b: Int32): Int32 { a - b }").is_ok());
}