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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use crate::SourceRead;
use super::super::display::{Display, Displayer};
use super::super::obj;
use super::super::objects::{DeclInfoKey, ObjKey, PackageKey, ScopeKey, TCObjects, TypeKey};
use super::super::operand::{Operand, OperandMode};
use super::super::package::Package;
use super::super::scope::Scope;
use super::super::typ::{self, BasicType, Type};
use super::super::universe::{Builtin, BuiltinInfo};
use super::check::{Checker, FilesContext};
use super::resolver::DeclInfo;
use std::cmp::Ordering;
use go_parser::{ast, ast::Expr, FilePos, IdentKey, Map, Pos};
macro_rules! error_operand {
($x:ident, $fmt:expr, $checker:ident) => {
let xd = $checker.new_dis(&$x);
$checker.error(xd.pos(), format!($fmt, xd));
};
}
#[derive(Debug)]
pub enum UnpackResult<'a> {
Tuple(Option<Expr>, Vec<Option<TypeKey>>, Ordering), CommaOk(Option<Expr>, [TypeKey; 2]), Mutliple(&'a Vec<Expr>, Ordering), Single(Operand, Ordering), Nothing(Ordering), Error, }
impl<'a> UnpackResult<'a> {
pub fn get<S: SourceRead>(
&self,
checker: &mut Checker<S>,
x: &mut Operand,
i: usize,
fctx: &mut FilesContext<S>,
) {
match self {
UnpackResult::Tuple(expr, types, _) => {
x.mode = OperandMode::Value;
x.expr = expr.clone();
x.typ = types[i];
}
UnpackResult::CommaOk(expr, types) => {
x.mode = OperandMode::Value;
x.expr = expr.clone();
x.typ = Some(types[i]);
}
UnpackResult::Mutliple(exprs, _) => {
checker.multi_expr(x, &exprs[i], fctx);
}
UnpackResult::Single(sx, _) => {
x.mode = sx.mode.clone();
x.expr = sx.expr.clone();
x.typ = sx.typ;
}
UnpackResult::Nothing(_) => unreachable!(),
UnpackResult::Error => unreachable!(),
}
}
pub fn rhs_count(&self) -> (usize, Ordering) {
match self {
UnpackResult::Tuple(_, types, ord) => (types.len(), *ord),
UnpackResult::CommaOk(_, types) => (types.len(), Ordering::Equal),
UnpackResult::Mutliple(exprs, ord) => (exprs.len(), *ord),
UnpackResult::Single(_, ord) => (1, *ord),
UnpackResult::Nothing(ord) => (0, *ord),
UnpackResult::Error => unreachable!(),
}
}
pub fn use_<S: SourceRead>(
&self,
checker: &mut Checker<S>,
from: usize,
fctx: &mut FilesContext<S>,
) {
let exprs = match self {
UnpackResult::Mutliple(exprs, _) => exprs,
_ => {
return;
}
};
let mut x = Operand::new();
for i in from..exprs.len() {
checker.multi_expr(&mut x, &exprs[i], fctx);
}
}
pub fn is_err(&self) -> bool {
match self {
UnpackResult::Error => true,
_ => false,
}
}
}
#[derive(Debug)]
pub struct UnpackedResultLeftovers<'a> {
pub leftovers: &'a UnpackResult<'a>,
pub consumed: Option<&'a Vec<Operand>>,
}
impl<'a> UnpackedResultLeftovers<'a> {
pub fn new(
re: &'a UnpackResult<'a>,
consumed: Option<&'a Vec<Operand>>,
) -> UnpackedResultLeftovers<'a> {
UnpackedResultLeftovers {
leftovers: re,
consumed: consumed,
}
}
pub fn use_all<S: SourceRead>(&self, checker: &mut Checker<S>, fctx: &mut FilesContext<S>) {
let from = if self.consumed.is_none() {
0
} else {
self.consumed.unwrap().len()
};
self.leftovers.use_(checker, from, fctx);
}
pub fn get<S: SourceRead>(
&self,
checker: &mut Checker<S>,
x: &mut Operand,
i: usize,
fctx: &mut FilesContext<S>,
) {
if self.consumed.is_none() {
self.leftovers.get(checker, x, i, fctx);
return;
}
let consumed = self.consumed.unwrap();
if i < consumed.len() {
let c = &consumed[i];
x.mode = c.mode.clone();
x.expr = c.expr.clone();
x.typ = c.typ;
} else {
self.leftovers.get(checker, x, i, fctx);
}
}
}
impl<'a, S: SourceRead> Checker<'a, S> {
pub fn unparen(x: &Expr) -> &Expr {
if let Expr::Paren(p) = x {
Checker::<S>::unparen(&p.expr)
} else {
x
}
}
pub fn invalid_ast(&self, pos: Pos, err: &str) {
self.error(pos, format!("invalid AST: {}", err));
}
pub fn invalid_arg(&self, pos: Pos, err: &str) {
self.error(pos, format!("invalid argument: {}", err));
}
pub fn invalid_op(&self, pos: Pos, err: &str) {
self.error(pos, format!("invalid operation: {}", err));
}
pub fn obj_path_str(&self, path: &Vec<ObjKey>) -> String {
let names: Vec<&str> = path.iter().map(|p| self.lobj(*p).name().as_str()).collect();
names[..].join("->")
}
pub fn dump(&self, pos: Option<Pos>, msg: &str) {
if let Some(p) = pos {
let p = self.fset.position(p);
print!("checker dump({}):{}\n", p.unwrap_or(FilePos::null()), msg);
} else {
print!("checker dump:{}\n", msg);
}
}
pub fn print_trace(&self, pos: Pos, msg: &str) {
let p = self.fset.position(pos);
print!(
"{}:\t{}{}\n",
p.unwrap_or(FilePos::null()),
". ".repeat(*self.indent.borrow()),
msg
);
}
pub fn trace_begin(&self, pos: Pos, msg: &str) {
self.print_trace(pos, msg);
*self.indent.borrow_mut() += 1;
}
pub fn trace_end(&self, pos: Pos, msg: &str) {
*self.indent.borrow_mut() -= 1;
self.print_trace(pos, msg);
}
pub fn has_cycle(&self, okey: ObjKey, path: &[ObjKey], report: bool) -> bool {
if let Some((i, _)) = path.iter().enumerate().find(|(_, &x)| x == okey) {
if report {
let obj_val = self.lobj(okey);
self.error(
obj_val.pos(),
format!("illegal cycle in declaration of {}", obj_val.name()),
);
for o in path[i..].iter() {
let oval = self.lobj(*o);
self.error(oval.pos(), format!("\t{} refers to", oval.name()));
}
self.error(obj_val.pos(), format!("\t{}", obj_val.name()));
}
return true;
}
false
}
pub fn comma_ok_type(
tc_objs: &mut TCObjects,
pos: usize,
pkg: PackageKey,
t: &[TypeKey; 2],
) -> TypeKey {
let vars = vec![
tc_objs.lobjs.insert(obj::LangObj::new_var(
pos,
Some(pkg),
String::new(),
Some(t[0]),
)),
tc_objs.lobjs.insert(obj::LangObj::new_var(
pos,
Some(pkg),
String::new(),
Some(t[1]),
)),
];
tc_objs.new_t_tuple(vars)
}
pub fn unpack<'b>(
&mut self,
rhs: &'b Vec<Expr>,
lhs_len: usize,
allow_comma_ok: bool,
variadic: bool,
fctx: &mut FilesContext<S>,
) -> UnpackResult<'b> {
let do_match = |rhs_len: usize| {
let order = rhs_len.cmp(&lhs_len);
if variadic && order == Ordering::Greater {
Ordering::Equal
} else {
order
}
};
if rhs.len() != 1 {
let matching = do_match(rhs.len());
return if rhs.len() == 0 {
UnpackResult::Nothing(matching)
} else {
UnpackResult::Mutliple(rhs, matching)
};
}
let mut x = Operand::new();
self.multi_expr(&mut x, &rhs[0], fctx);
if x.invalid() {
return UnpackResult::Error;
}
if let Some(t) = self.otype(x.typ.unwrap()).try_as_tuple() {
let types: Vec<Option<TypeKey>> =
t.vars().iter().map(|x| self.lobj(*x).typ()).collect();
let matching = do_match(types.len());
return UnpackResult::Tuple(x.expr.clone(), types, matching);
} else if x.mode == OperandMode::MapIndex || x.mode == OperandMode::CommaOk {
if allow_comma_ok {
let types = [x.typ.unwrap(), self.basic_type(BasicType::UntypedBool)];
return UnpackResult::CommaOk(x.expr.clone(), types);
}
x.mode = OperandMode::Value;
}
UnpackResult::Single(x, do_match(1))
}
pub fn use_exprs(&mut self, exprs: &Vec<Expr>, fctx: &mut FilesContext<S>) {
let x = &mut Operand::new();
for e in exprs.iter() {
self.raw_expr(x, &e, None, fctx);
}
}
pub fn use_lhs(&mut self, lhs: &Vec<Expr>, fctx: &mut FilesContext<S>) {
let x = &mut Operand::new();
for e in lhs.iter() {
let v = match Checker::<S>::unparen(e) {
Expr::Ident(ikey) => match &self.ast_ident(*ikey).name {
s if s == "_" => continue,
s => Scope::lookup_parent(
self.octx.scope.as_ref().unwrap(),
s,
None,
self.tc_objs,
)
.map(|(_, okey)| okey)
.map(|okey| {
let lobj = self.lobj(okey);
match lobj.entity_type() {
obj::EntityType::Var(vp) => match lobj.pkg() == Some(self.pkg) {
true => Some((okey, vp.used)),
false => None,
},
_ => None,
}
}),
},
_ => None,
}
.flatten();
self.raw_expr(x, &e, None, fctx);
if let Some((okey, used)) = v {
match self.lobj_mut(okey).entity_type_mut() {
obj::EntityType::Var(vp) => vp.used = used,
_ => unreachable!(),
}
}
}
}
pub fn lookup(&self, name: &str) -> Option<ObjKey> {
Scope::lookup_parent(
self.octx.scope.as_ref().unwrap(),
name,
self.octx.pos,
self.tc_objs,
)
.map(|(_, okey)| okey)
}
pub fn add_decl_dep(&mut self, to: ObjKey) {
if self.octx.decl.is_none() {
return;
}
if !self.obj_map.contains_key(&to) {
return;
}
self.tc_objs.decls[self.octx.decl.unwrap()].add_dep(to);
}
pub fn insert_obj_to_set(&self, set: &mut Map<String, ObjKey>, okey: ObjKey) -> Option<ObjKey> {
let obj_val = self.lobj(okey);
let id = obj_val.id(self.tc_objs).to_string();
set.insert(id, okey)
}
pub fn ast_ident(&self, key: IdentKey) -> &ast::Ident {
&self.ast_objs.idents[key]
}
pub fn lobj(&self, key: ObjKey) -> &obj::LangObj {
&self.tc_objs.lobjs[key]
}
pub fn lobj_mut(&mut self, key: ObjKey) -> &mut obj::LangObj {
&mut self.tc_objs.lobjs[key]
}
pub fn otype(&self, key: TypeKey) -> &Type {
&self.tc_objs.types[key]
}
pub fn otype_mut(&mut self, key: TypeKey) -> &mut Type {
&mut self.tc_objs.types[key]
}
pub fn otype_interface(&self, key: TypeKey) -> &typ::InterfaceDetail {
self.otype(key).try_as_interface().unwrap()
}
pub fn otype_signature(&self, key: TypeKey) -> &typ::SignatureDetail {
self.otype(key).try_as_signature().unwrap()
}
pub fn otype_interface_mut(&mut self, key: TypeKey) -> &mut typ::InterfaceDetail {
self.otype_mut(key).try_as_interface_mut().unwrap()
}
pub fn otype_signature_mut(&mut self, key: TypeKey) -> &mut typ::SignatureDetail {
self.otype_mut(key).try_as_signature_mut().unwrap()
}
pub fn package(&self, key: PackageKey) -> &Package {
&self.tc_objs.pkgs[key]
}
pub fn package_mut(&mut self, key: PackageKey) -> &mut Package {
&mut self.tc_objs.pkgs[key]
}
pub fn scope(&self, key: ScopeKey) -> &Scope {
&self.tc_objs.scopes[key]
}
pub fn decl_info(&self, key: DeclInfoKey) -> &DeclInfo {
&self.tc_objs.decls[key]
}
pub fn position(&self, pos: Pos) -> FilePos {
self.fset.file(pos).unwrap().position(pos)
}
pub fn builtin_info(&self, id: Builtin) -> &BuiltinInfo {
&self.tc_objs.universe().builtins()[&id]
}
pub fn basic_type(&self, t: typ::BasicType) -> TypeKey {
self.tc_objs.universe().types()[&t]
}
pub fn invalid_type(&self) -> TypeKey {
self.basic_type(typ::BasicType::Invalid)
}
pub fn new_dis<'b>(&'b self, x: &'b impl Display) -> Displayer<'b> {
Displayer::new(x, Some(self.ast_objs), Some(self.tc_objs))
}
pub fn new_td_o<'t>(&'t self, t: &'t Option<TypeKey>) -> Displayer<'t> {
Displayer::new(t.as_ref().unwrap(), Some(self.ast_objs), Some(self.tc_objs))
}
}