1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use crate::language::InternSymbol;
use crate::parser::primary::{Primary, AccessItem, Atom};
use crate::parser::operator::BinaryOp;
use crate::parser::expr::{Expr, ExprMeta};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AssignType {
AssignLocal,
AssignNonLocal,
DeclImmutable,
DeclMutable,
}
#[derive(Debug, Clone)]
pub enum LValue {
Identifier(InternSymbol),
Attribute(Box<AttributeTarget>),
Index(Box<IndexTarget>),
Tuple(Box<[LValue]>),
PackItem(Option<Box<LValue>>),
Modifier {
modifier: AssignType,
lvalue: Box<LValue>,
},
}
#[derive(Debug, Clone)]
pub struct AttributeTarget {
pub receiver: Primary,
pub name: InternSymbol,
}
#[derive(Debug, Clone)]
pub struct IndexTarget {
pub receiver: Primary,
pub index: ExprMeta,
}
#[derive(Debug, Clone)]
pub struct Assignment {
pub lhs: LValue,
pub assign: AssignType,
pub op: Option<BinaryOp>,
pub rhs: Expr,
}
pub struct IntoLValueError;
impl TryFrom<Atom> for LValue {
type Error = IntoLValueError;
fn try_from(atom: Atom) -> Result<Self, Self::Error> {
match atom {
Atom::Identifier(name) => Ok(LValue::Identifier(name)),
Atom::Group { modifier, inner } => {
let lvalue = (*inner).try_into()?;
if let Some(modifier) = modifier {
Ok(Self::Modifier {
modifier,
lvalue: Box::new(lvalue),
})
} else {
Ok(lvalue)
}
},
_ => Err(IntoLValueError)
}
}
}
impl TryFrom<Primary> for LValue {
type Error = IntoLValueError;
fn try_from(primary: Primary) -> Result<Self, Self::Error> {
let (atom, mut path) = primary.take();
let tail = path.pop();
let receiver = Primary::new(atom, path);
let lvalue = match tail {
Some(AccessItem::Attribute(name))
=> LValue::Attribute(Box::new(AttributeTarget { receiver, name })),
Some(AccessItem::Index(index))
=> LValue::Index(Box::new(IndexTarget { receiver, index })),
_ => return Err(IntoLValueError),
};
Ok(lvalue)
}
}
impl TryFrom<Expr> for LValue {
type Error = IntoLValueError;
fn try_from(expr: Expr) -> Result<Self, Self::Error> {
match expr {
Expr::Atom(atom) => atom.try_into(),
Expr::Primary(primary) => primary.try_into(),
Expr::Ellipsis(Some(expr)) => {
let inner = LValue::try_from(*expr)?;
Ok(Self::PackItem(Some(Box::new(inner))))
}
Expr::Ellipsis(None) => Ok(Self::PackItem(None)),
Expr::Tuple(items) if !items.is_empty() => {
let mut lvalue_items = Vec::new();
for expr in items.into_vec().into_iter() {
let lvalue = LValue::try_from(expr.take_variant())?;
lvalue_items.push(lvalue);
}
Ok(Self::Tuple(lvalue_items.into_boxed_slice()))
},
_ => Err(IntoLValueError),
}
}
}