// See also: file:///usr/share/doc/python/html/reference/grammar.html?highlight=grammar
// See also: https://github.com/antlr/grammars-v4/blob/master/python3/Python3.g4
// See also: file:///usr/share/doc/python/html/reference/compound_stmts.html#function-definitions
// See also: https://greentreesnakes.readthedocs.io/en/latest/nodes.html#keyword
use std::iter::FromIterator;
use crate::ast;
use crate::fstring::parse_fstring;
use crate::lexer;
use num_bigint::BigInt;
grammar;
// This is a hack to reduce the amount of lalrpop tables generated:
// For each public entry point, a full parse table is generated.
// By having only a single pub function, we reduce this to one.
pub Top: ast::Top = {
StartProgram => ast::Top::Program(p),
StartStatement => ast::Top::Statement(s),
StartExpression => ast::Top::Expression(e),
};
Program: ast::Program = {
=> ast::Program {
statements: Vec::from_iter(lines.into_iter().flatten())
},
};
// A file line either has a declaration, or an empty newline:
FileLine: Vec = {
Statement,
"\n" => vec![],
};
Suite: Vec = {
SimpleStatement,
"\n" indent dedent => s.into_iter().flatten().collect(),
};
Statement: Vec = {
SimpleStatement,
=> vec![s],
};
SimpleStatement: Vec = {
";"? "\n" => {
let mut statements = vec![s1];
statements.extend(s2.into_iter().map(|e| e.1));
statements
}
};
SmallStatement: ast::LocatedStatement = {
ExpressionStatement,
PassStatement,
DelStatement,
FlowStatement,
ImportStatement,
GlobalStatement,
NonlocalStatement,
AssertStatement,
};
PassStatement: ast::LocatedStatement = {
"pass" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Pass,
}
},
};
DelStatement: ast::LocatedStatement = {
"del" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Delete { targets: e },
}
},
};
ExpressionStatement: ast::LocatedStatement = {
=> {
// Just an expression, no assignment:
if suffix.is_empty() {
ast::LocatedStatement {
location: loc.clone(),
node: ast::Statement::Expression { expression: expr }
}
} else {
let mut targets = vec![expr];
let mut values = suffix;
while values.len() > 1 {
targets.push(values.remove(0));
}
let value = values.into_iter().next().unwrap();
ast::LocatedStatement {
location: loc.clone(),
node: ast::Statement::Assign { targets, value },
}
}
},
=> {
ast::LocatedStatement {
location: loc,
node: ast::Statement::AugAssign {
target: Box::new(expr),
op,
value: Box::new(rhs)
},
}
},
};
AssignSuffix: ast::Expression = {
"=" => e,
"=" => e,
};
TestOrStarExprList: ast::Expression = {
> => {
if elements.len() == 1 && comma.is_none() {
elements.into_iter().next().unwrap()
} else {
ast::Expression::Tuple { elements }
}
}
};
TestOrStarExpr: ast::Expression = {
Test,
StarExpr,
};
AugAssign: ast::Operator = {
"+=" => ast::Operator::Add,
"-=" => ast::Operator::Sub,
"*=" => ast::Operator::Mult,
"@=" => ast::Operator::MatMult,
"/=" => ast::Operator::Div,
"%=" => ast::Operator::Mod,
"&=" => ast::Operator::BitAnd,
"|=" => ast::Operator::BitOr,
"^=" => ast::Operator::BitXor,
"<<=" => ast::Operator::LShift,
">>=" => ast::Operator::RShift,
"**=" => ast::Operator::Pow,
"//=" => ast::Operator::FloorDiv,
};
FlowStatement: ast::LocatedStatement = {
"break" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Break,
}
},
"continue" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Continue,
}
},
"return" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Return { value: t.map(Box::new) },
}
},
=> {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Expression { expression: y },
}
},
RaiseStatement,
};
RaiseStatement: ast::LocatedStatement = {
"raise" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Raise { exception: None, cause: None },
}
},
"raise" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Raise { exception: Some(t), cause: c.map(|x| x.1) },
}
},
};
ImportStatement: ast::LocatedStatement = {
"import" >>> => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Import {
import_parts: i
.iter()
.map(|(n, a)|
ast::SingleImport {
module: n.to_string(),
symbols: vec![],
alias: a.clone(),
level: 0,
})
.collect()
},
}
},
"from" "import" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Import {
import_parts: vec![
ast::SingleImport {
module: n.0.to_string(),
symbols: i.iter()
.map(|(i, a)|
ast::ImportSymbol {
symbol: i.to_string(),
alias: a.clone(),
})
.collect(),
alias: None,
level: n.1
}]
},
}
},
};
ImportFromLocation: (String, usize) = {
=> {
(name, dots.len())
},
=> {
("".to_string(), dots.len())
},
};
ImportAsNames: Vec<(String, Option)> = {
>> => i,
"(" >> ")" => i,
"*" => {
// Star import all
vec![("*".to_string(), None)]
},
};
#[inline]
ImportPart: (String, Option) = {
=> (i, a.map(|a| a.1)),
};
// A name like abc or abc.def.ghi
DottedName: String = {
=> n,
=> {
let mut r = n.to_string();
for x in n2 {
r.push_str(".");
r.push_str(&x.1);
}
r
},
};
GlobalStatement: ast::LocatedStatement = {
"global" > => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Global { names }
}
},
};
NonlocalStatement: ast::LocatedStatement = {
"nonlocal" > => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Nonlocal { names }
}
},
};
AssertStatement: ast::LocatedStatement = {
"assert" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::Assert {
test, msg: msg.map(|e| e.1)
}
}
},
};
CompoundStatement: ast::LocatedStatement = {
IfStatement,
WhileStatement,
ForStatement,
TryStatement,
WithStatement,
FuncDef,
ClassDef,
};
IfStatement: ast::LocatedStatement = {
"if" ":" => {
// Determine last else:
let mut last = s3.map(|s| s.2);
// handle elif:
for i in s2.into_iter().rev() {
let x = ast::LocatedStatement {
location: i.0,
node: ast::Statement::If { test: i.2, body: i.4, orelse: last },
};
last = Some(vec![x]);
}
ast::LocatedStatement {
location: loc,
node: ast::Statement::If { test, body: s1, orelse: last }
}
},
};
WhileStatement: ast::LocatedStatement = {
"while" ":" => {
let or_else = s2.map(|s| s.2);
ast::LocatedStatement {
location: loc,
node: ast::Statement::While { test, body, orelse: or_else },
}
},
};
ForStatement: ast::LocatedStatement = {
"for" "in" ":" => {
let orelse = s2.map(|s| s.2);
ast::LocatedStatement {
location: loc,
node: if is_async.is_some() {
ast::Statement::AsyncFor { target, iter, body, orelse }
} else {
ast::Statement::For { target, iter, body, orelse }
},
}
},
};
TryStatement: ast::LocatedStatement = {
"try" ":" => {
let or_else = else_suite.map(|s| s.2);
let finalbody = finally.map(|s| s.2);
ast::LocatedStatement {
location: loc,
node: ast::Statement::Try {
body: body,
handlers: handlers,
orelse: or_else,
finalbody: finalbody,
},
}
},
};
ExceptClause: ast::ExceptHandler = {
"except" ":" => {
ast::ExceptHandler {
typ: typ,
name: None,
body: body,
}
},
"except" ":" => {
ast::ExceptHandler {
typ: Some(x.0),
name: Some(x.2),
body: body,
}
},
};
WithStatement: ast::LocatedStatement = {
"with" > ":" => {
ast::LocatedStatement {
location: loc,
node: ast::Statement::With { items: items, body: s },
}
},
};
WithItem: ast::WithItem = {
=> {
let optional_vars = n.map(|val| val.1);
ast::WithItem { context_expr: t, optional_vars }
},
};
FuncDef: ast::LocatedStatement = {
"def" " Test)?> ":" => {
ast::LocatedStatement {
location: loc,
node: if is_async.is_some() {
ast::Statement::AsyncFunctionDef {
name: i,
args: a,
body: s,
decorator_list: d,
returns: r.map(|x| x.1),
}
} else {
ast::Statement::FunctionDef {
name: i,
args: a,
body: s,
decorator_list: d,
returns: r.map(|x| x.1),
}
}
}
},
};
Parameters: ast::Parameters = {
"(" )?> ")" => a.unwrap_or_else(Default::default),
};
// Note that this is a macro which is used once for function defs, and
// once for lambda defs.
ParameterList: ast::Parameters = {
> )?> ","? => {
let (names, default_elements) = param1;
// Now gather rest of parameters:
let (vararg, kwonlyargs, kw_defaults, kwarg) = args2.map_or((None, vec![], vec![], None), |x| x.1);
ast::Parameters {
args: names,
kwonlyargs: kwonlyargs,
vararg: vararg.into(),
kwarg: kwarg.into(),
defaults: default_elements,
kw_defaults: kw_defaults,
}
},
> )> ","? => {
let (names, default_elements) = param1;
// Now gather rest of parameters:
let vararg = None;
let kwonlyargs = vec![];
let kw_defaults = vec![];
let kwarg = Some(kw.1);
ast::Parameters {
args: names,
kwonlyargs: kwonlyargs,
vararg: vararg.into(),
kwarg: kwarg.into(),
defaults: default_elements,
kw_defaults: kw_defaults,
}
},
> ","? => {
let (vararg, kwonlyargs, kw_defaults, kwarg) = params;
ast::Parameters {
args: vec![],
kwonlyargs: kwonlyargs,
vararg: vararg.into(),
kwarg: kwarg.into(),
defaults: vec![],
kw_defaults: kw_defaults,
}
},
> ","? => {
ast::Parameters {
args: vec![],
kwonlyargs: vec![],
vararg: ast::Varargs::None,
kwarg: Some(kw).into(),
defaults: vec![],
kw_defaults: vec![],
}
},
};
// Use inline here to make sure the "," is not creating an ambiguity.
#[inline]
ParameterDefs: (Vec, Vec) = {
> )*> => {
// Combine first parameters:
let mut args = vec![param1];
args.extend(param2.into_iter().map(|x| x.1));
let mut names = vec![];
let mut default_elements = vec![];
for (name, default) in args.into_iter() {
if let Some(default) = default {
default_elements.push(default);
} else {
if default_elements.len() > 0 {
// Once we have started with defaults, all remaining arguments must
// have defaults
panic!(
"non-default argument follows default argument: {}",
&name.arg
);
}
}
names.push(name);
}
(names, default_elements)
}
};
ParameterDef: (ast::Parameter, Option) = {
=> (i, None),
"=" => (i, Some(e)),
};
UntypedParameter: ast::Parameter = {
=> ast::Parameter { arg: i, annotation: None },
};
TypedParameter: ast::Parameter = {
=> {
let annotation = a.map(|x| Box::new(x.1));
ast::Parameter { arg, annotation }
},
};
// Use inline here to make sure the "," is not creating an ambiguity.
// TODO: figure out another grammar that makes this inline no longer required.
#[inline]
ParameterListStarArgs: (Option