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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
// Copyright (c) 2016-2021 Fabian Schuiki
//! A mapping from a pattern expression's arguments to the underlying type's
//! fields.
use crate::crate_prelude::*;
use crate::{ast_map::AstNode, common::arenas::Alloc, hir::HirNode, value::ValueKind};
use num::cast::ToPrimitive;
use std::{collections::HashMap, sync::Arc};
/// A mapping of the indices/members of a pattern's type to an expression.
#[derive(Clone, Debug)]
pub struct PatternMapping<'a> {
/// The corresponding pattern expression.
pub hir: &'a hir::Expr<'a>,
/// The type the pattern maps to.
pub ty: &'a ty::UnpackedType<'a>,
/// The mapped expression for each field. The fields are in type order.
/// Multiple fields may be assigned the same expression.
pub fields: Vec<(PatternField<'a>, &'a hir::Expr<'a>)>,
}
/// A field correspondence in a mapped pattern.
///
/// This enum further details the kind of field an expression is mapped to. The
/// indices of the corresponding field are implied by the position of the
/// `PatternField` within the `fields` vector.
#[derive(Copy, Clone, Debug)]
pub enum PatternField<'a> {
/// The expression is assigned to a single bit of the given type.
Bit(ty::SbvType),
/// The expression is assigned to an array element of the given type.
Array(&'a ty::UnpackedType<'a>),
/// The expression is assigned to the given struct member.
Struct(&'a ty::StructMember<'a>),
}
impl<'a> PatternField<'a> {
/// Determine the type of the underlying field.
pub fn ty(&self, cx: &impl ty::TypeContext<'a>) -> &'a ty::UnpackedType<'a> {
match self {
Self::Bit(sbv) => sbv.to_unpacked(cx),
Self::Array(ty) => ty,
Self::Struct(m) => m.ty,
}
}
}
/// Determine the mapping of a named or positional `'{...}` pattern.
#[moore_derive::query]
pub(crate) fn map_pattern<'a>(
cx: &impl Context<'a>,
Ref(expr): Ref<'a, hir::Expr<'a>>,
env: ParamEnv,
) -> Result<Arc<PatternMapping<'a>>> {
// First determine the type the pattern will have.
let ty = cx.need_type_context(Ref(expr), env);
if ty.is_error() {
return Err(());
}
let ty = ty.ty();
// Then handle the different pattern styles.
let fields = match expr.kind {
hir::ExprKind::PositionalPattern(ref mapping) => {
map_positional_pattern(cx, mapping, 1, ty, expr.span)?
}
hir::ExprKind::RepeatPattern(count, ref mapping) => {
let const_count = cx.constant_int_value_of(count, env)?;
let const_count = match const_count.to_usize() {
Some(c) => c,
None => {
cx.emit(
DiagBuilder2::error(format!(
"repetition count {} is outside copable range",
const_count,
))
.span(cx.span(count)),
);
return Err(());
}
};
map_positional_pattern(cx, mapping, const_count, ty, expr.span)?
}
hir::ExprKind::NamedPattern(ref mapping) => {
if let Some(dim) = ty.outermost_dim() {
map_named_array_pattern(cx, mapping, ty, dim, expr.span, env)?
} else if let Some(strukt) = ty.get_struct() {
map_named_struct_pattern(cx, expr, mapping, strukt, expr.span, env)?
} else {
cx.emit(
DiagBuilder2::error(format!(
"cannot construct a value of type `{}` with `'{{...}}`",
ty
))
.span(expr.span)
.add_note("Named patterns can only construct arrays or structs."),
);
return Err(());
}
}
_ => bug_span!(expr.span, cx, "expression is not a pattern"),
};
// Assemble the full mapping information.
Ok(Arc::new(PatternMapping {
hir: expr,
ty,
fields,
}))
}
/// Helper function to get the HIR expr associated with a node ID. This should
/// eventually go into the HIR module.
fn hir_of_expr<'a>(cx: &impl Context<'a>, node: NodeId) -> Result<&'a hir::Expr<'a>> {
match cx.hir_of(node)? {
HirNode::Expr(e) => Ok(e),
x => unreachable!("expected HIR expression, got {:?}", x),
}
}
/// Determine the mapping of a named `'{...}` array pattern.
fn map_named_array_pattern<'a>(
cx: &impl Context<'a>,
mapping: &[(hir::PatternMapping, NodeId)],
ty: &'a ty::UnpackedType<'a>,
dim: ty::Dim<'a>,
span: Span,
env: ParamEnv,
) -> Result<Vec<(PatternField<'a>, &'a hir::Expr<'a>)>> {
// Determine the length of the array and the offset of the indexes.
let (length, offset) = match dim
.get_range()
.map(|r| (r.size, r.offset))
.or_else(|| dim.get_size().map(|s| (s, 0)))
{
Some(x) => x,
None => bug_span!(
span,
cx,
"array pattern with invalid input dimension `{}`",
dim
),
};
// Determine the element type.
let elem_ty = ty.pop_dim(cx).unwrap();
// Map things.
let mut failed = false;
let mut default: Option<&hir::Expr> = None;
let mut values = HashMap::<usize, (PatternField, &hir::Expr)>::new();
for &(map, to) in mapping {
let to = match hir_of_expr(cx, to) {
Ok(h) => h,
_ => {
failed = true;
continue;
}
};
match map {
hir::PatternMapping::Type(type_id) => {
cx.emit(
DiagBuilder2::error("types cannot index into an array").span(cx.span(type_id)),
);
continue;
}
hir::PatternMapping::Member(member_id) => {
// Determine the index for the mapping.
let index = match || -> Result<usize> {
let index = cx.constant_value_of(member_id, env);
let index = match &index.kind {
ValueKind::Int(i, ..) => i - num::BigInt::from(offset),
ValueKind::Error => return Err(()),
_ => {
cx.emit(
DiagBuilder2::error("array index must be a constant integer")
.span(cx.span(member_id)),
);
return Err(());
}
};
let index = match index.to_isize() {
Some(i) if i >= 0 && i < length as isize => i as usize,
_ => {
cx.emit(
DiagBuilder2::error(format!("index `{}` out of bounds", index))
.span(cx.span(member_id)),
);
return Err(());
}
};
Ok(index)
}() {
Ok(i) => i,
Err(_) => {
failed = true;
continue;
}
};
// Determine the value and insert into the mappings.
let entry = (PatternField::Array(elem_ty), to);
if let Some((_, prev)) = values.insert(index, entry) {
cx.emit(
DiagBuilder2::warning(format!(
"`{}` overwrites previous value `{}` at index {}",
to.span.extract(),
prev.span.extract(),
index
))
.span(to.span)
.add_note("Previous value was here:")
.span(prev.span),
);
}
}
hir::PatternMapping::Default => match default {
Some(ref default) => {
cx.emit(
DiagBuilder2::error("pattern has multiple default mappings")
.span(to.span)
.add_note("Previous default mapping was here:")
.span(default.span),
);
failed = true;
continue;
}
None => {
default = Some(to);
}
},
}
}
// In case the list of indices provided by the user is incomplete, use the
// default to fill in the other elements.
let values: Vec<_> = if values.len() != length {
let default = if let Some(default) = default {
default
} else {
cx.emit(
DiagBuilder2::error("`default:` missing in non-exhaustive array pattern")
.span(span)
.add_note("Array patterns must assign a value to every index."),
);
return Err(());
};
(0..length)
.map(|i| {
values
.get(&i)
.copied()
.unwrap_or((PatternField::Array(elem_ty), default))
})
.collect()
} else {
(0..length).map(|i| values[&i]).collect()
};
if failed {
Err(())
} else {
Ok(values)
}
}
/// Determine the mapping of a named `'{...}` struct pattern.
fn map_named_struct_pattern<'a>(
cx: &impl Context<'a>,
expr: &'a hir::Expr<'a>,
mapping: &[(hir::PatternMapping, NodeId)],
strukt: &'a ty::StructType<'a>,
span: Span,
env: ParamEnv,
) -> Result<Vec<(PatternField<'a>, &'a hir::Expr<'a>)>> {
// Determine the field names and types for the struct to be assembled.
let name_lookup: HashMap<Name, usize> = strukt
.members
.iter()
.enumerate()
.map(|(i, f)| (f.name.value, i))
.collect();
// Disassemble the user's mapping into actual field bindings and defaults.
let mut failed = false;
let mut default: Option<&ast::Expr> = None;
let mut type_defaults = HashMap::<&ty::UnpackedType, &hir::Expr>::new();
let mut values = HashMap::<usize, (PatternField, &hir::Expr)>::new();
for &(map, to) in mapping {
let to = match hir_of_expr(cx, to) {
Ok(h) => h,
_ => {
failed = true;
continue;
}
};
match map {
hir::PatternMapping::Type(type_id) => {
let ty = cx.packed_type_from_ast(
Ref(cx.ast_for_id(type_id).as_all().get_type().unwrap()),
env,
None,
);
if ty.is_error() {
failed = true;
continue;
}
type_defaults.insert(ty.resolve_full(), to);
}
hir::PatternMapping::Member(member_id) => match cx.hir_of(member_id) {
Ok(HirNode::Expr(&hir::Expr {
kind: hir::ExprKind::Ident(name),
..
})) => {
// Determine the index for the mapping.
let index = match name_lookup.get(&name.value) {
Some(&index) => index,
None => {
cx.emit(
DiagBuilder2::error(format!("`{}` member does not exist", name))
.span(name.span)
.add_note("Struct definition was here:")
.span(strukt.ast.span()),
);
failed = true;
continue;
}
};
// Determine the value and insert into the mappings.
let entry = (PatternField::Struct(&strukt.members[index]), to);
if let Some((_, prev)) = values.insert(index, entry) {
cx.emit(
DiagBuilder2::warning(format!(
"`{}` overwrites previous value `{}` for member `{}`",
to.span.extract(),
prev.span.extract(),
name
))
.span(to.span)
.add_note("Previous value was here:")
.span(prev.span),
);
}
}
Ok(_) => {
let span = cx.span(member_id);
cx.emit(
DiagBuilder2::error(format!(
"`{}` is not a valid struct member name",
span.extract()
))
.span(span),
);
failed = true;
continue;
}
Err(()) => {
failed = true;
continue;
}
},
hir::PatternMapping::Default => match default {
Some(default) => {
cx.emit(
DiagBuilder2::error("pattern has multiple default mappings")
.span(to.span)
.add_note("Previous mapping default mapping was here:")
.span(default.span),
);
failed = true;
continue;
}
None => {
default = Some(
cx.ast_for_id(to.id)
.as_all()
.get_expr()
.expect("default must be an expr"),
);
}
},
}
}
// In case the list of members provided by the user is incomplete, use the
// defaults to fill in the other members.
for (index, field) in strukt.members.iter().enumerate() {
if values.contains_key(&index) {
continue;
}
// Try the type-based defaults first.
if let Some(default) = type_defaults.get(field.ty.resolve_full()) {
trace!(
"applying type default to member `{}`: {:?}",
field.name,
default
);
values.insert(index, (PatternField::Struct(field), default));
continue;
}
// Try to assign a default value.
let default = if let Some(default) = default {
default
} else {
cx.emit(
DiagBuilder2::error(format!("`{}` member missing in struct pattern", field.name))
.span(span)
.add_note("Struct patterns must assign a value to every member."),
);
failed = true;
continue;
};
// Replicate the default value.
let ast = cx
.arena()
.alloc(ast::Expr::new(default.span, default.data.clone()));
ast.link_attach(default.get_parent().unwrap(), default.order());
cx.register_ast(ast);
cx.map_ast_with_parent(AstNode::Expr(ast), expr.id);
trace!("Replicated default {:?} as {:?}", default, ast);
let hir = match cx.hir_of_expr(Ref(ast)) {
Ok(h) => h,
_ => {
failed = true;
continue;
}
};
values.insert(index, (PatternField::Struct(field), hir));
}
if failed {
Err(())
} else {
Ok((0..values.len()).map(|i| values[&i]).collect())
}
}
/// Determine the mapping of a positional `'{...}` pattern.
fn map_positional_pattern<'a>(
cx: &impl Context<'a>,
mapping: &[NodeId],
repeat: usize,
ty: &'a ty::UnpackedType<'a>,
span: Span,
) -> Result<Vec<(PatternField<'a>, &'a hir::Expr<'a>)>> {
// Lower each of the values to HIR, and abort on errors.
let values: Result<Vec<_>> = mapping.iter().map(|&id| hir_of_expr(cx, id)).collect();
let values = values?;
let len = values.len() * repeat;
let values: Vec<_> = values.into_iter().cycle().take(len).collect();
// Find a mapping for the values.
let (exp_len, result) = if ty.coalesces_to_llhd_scalar() {
let sbv = ty.simple_bit_vector(cx, span);
let bit = sbv.change_size(1);
(
sbv.size,
values
.into_iter()
.rev()
.map(|v| (PatternField::Bit(bit), v))
.collect(),
)
} else if let Some(dim) = ty.outermost_dim() {
let elem_ty = ty.pop_dim(cx).unwrap();
match dim.get_size() {
Some(size) => (
size,
values
.into_iter()
.map(|v| (PatternField::Array(elem_ty), v))
.collect(),
),
None => {
cx.emit(
DiagBuilder2::error(format!(
"value of type `{}` cannot be constructed with a pattern; dimension `{}` \
has no fixed size",
ty, dim,
))
.span(span),
);
return Err(());
}
}
} else if let Some(strukt) = ty.get_struct() {
(
strukt.members.len(),
values
.into_iter()
.enumerate()
.flat_map(|(i, v)| match strukt.members.get(i) {
Some(f) => Some((PatternField::Struct(f), v)),
None => None,
})
.collect(),
)
} else {
bug_span!(span, cx, "positional pattern with invalid type `{}`", ty)
};
// Ensure that the number of values matches the array/struct definition.
if exp_len != len {
cx.emit(
DiagBuilder2::error(format!(
"pattern has {} fields, but type `{}` requires {}",
len, ty, exp_len
))
.span(span),
);
return Err(());
}
Ok(result)
}