forked from oxidecomputer/p4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statement.rs
610 lines (564 loc) · 20.9 KB
/
statement.rs
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// Copyright 2022 Oxide Computer Company
use crate::{
expression::ExpressionGenerator, is_header, is_header_member,
is_rust_reference, rust_type,
};
use p4::ast::{
Call, Control, DeclarationInfo, Direction, ExpressionKind, NameInfo,
Parser, Statement, StatementBlock, Transition, Type, AST,
};
use p4::hlir::Hlir;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::HashMap;
#[derive(Debug)]
pub(crate) enum StatementContext<'a> {
Control(&'a Control),
#[allow(dead_code)]
Parser(&'a Parser),
}
pub(crate) struct StatementGenerator<'a> {
hlir: &'a Hlir,
ast: &'a AST,
context: StatementContext<'a>,
}
impl<'a> StatementGenerator<'a> {
pub fn new(
ast: &'a AST,
hlir: &'a Hlir,
context: StatementContext<'a>,
) -> Self {
Self { ast, hlir, context }
}
pub(crate) fn generate_block(
&self,
sb: &StatementBlock,
names: &mut HashMap<String, NameInfo>,
) -> TokenStream {
let mut ts = TokenStream::new();
for stmt in &sb.statements {
ts.extend(self.generate_statement(stmt, names));
}
ts
}
pub(crate) fn generate_statement(
&self,
stmt: &Statement,
names: &mut HashMap<String, NameInfo>,
) -> TokenStream {
match stmt {
Statement::Empty => TokenStream::new(),
Statement::Assignment(lval, xpr) => {
let eg = ExpressionGenerator::new(self.hlir);
let lhs = eg.generate_lvalue(lval);
let rhs = eg.generate_expression(xpr.as_ref());
let rhs_ty = self
.hlir
.expression_types
.get(xpr.as_ref())
.unwrap_or_else(|| {
panic!("codegen type not found for {:#?}", xpr)
});
let name_info =
self.hlir.lvalue_decls.get(lval).unwrap_or_else(|| {
panic!("codegen name not resolved for {:#?}", lval)
});
if is_header_member(lval, self.hlir) {
return quote! { #lhs = #rhs.clone(); };
}
let rhs = if rhs_ty != &name_info.ty {
let converter = self.converter(rhs_ty, &name_info.ty);
quote!( #converter(#rhs) )
} else {
rhs
};
let rhs = if let Type::Bit(_) = rhs_ty {
// TODO eww, to better to figure out precisely when to_owned
// and clone are needed
quote! { #rhs.to_owned().clone() }
} else if let Type::UserDefined(_) = rhs_ty {
quote! { #rhs.clone() }
} else {
rhs
};
if is_rust_reference(lval, names) {
quote! { *#lhs = #rhs; }
} else {
quote! { #lhs = #rhs; }
}
}
Statement::Call(c) => match &self.context {
StatementContext::Control(control) => {
let mut ts = TokenStream::new();
self.generate_control_body_call(control, c, &mut ts);
ts
}
StatementContext::Parser(parser) => {
let mut ts = TokenStream::new();
self.generate_parser_body_call(parser, c, &mut ts);
ts
}
},
Statement::If(ifb) => {
let eg = ExpressionGenerator::new(self.hlir);
let predicate = eg.generate_expression(ifb.predicate.as_ref());
let block = self.generate_block(&ifb.block, names);
let mut ts = quote! {
if #predicate { #block }
};
for ei in &ifb.else_ifs {
let predicate =
eg.generate_expression(ei.predicate.as_ref());
let block = self.generate_block(&ei.block, names);
ts.extend(quote! {else if #predicate { #block }})
}
if let Some(eb) = &ifb.else_block {
let block = self.generate_block(eb, names);
ts.extend(quote! {else { #block }})
}
ts
}
Statement::Variable(v) => {
let name = format_ident!("{}", v.name);
let ty = rust_type(&v.ty);
let initializer = match &v.initializer {
Some(xpr) => {
let eg = ExpressionGenerator::new(self.hlir);
let ini = eg.generate_expression(xpr.as_ref());
let ini_ty =
self.hlir.expression_types.get(xpr).unwrap_or_else(
|| panic!("type for expression {:#?}", xpr),
);
if ini_ty != &v.ty {
let converter = self.converter(ini_ty, &v.ty);
quote! { #converter(#ini) }
} else {
ini
}
}
None => quote! { #ty::default() },
};
names.insert(
v.name.clone(),
NameInfo {
ty: v.ty.clone(),
decl: DeclarationInfo::Local,
},
);
//TODO determine for real
let needs_mut = true;
if needs_mut {
quote! {
let mut #name: #ty = #initializer;
}
} else {
quote! {
let #name: #ty = #initializer;
}
}
}
Statement::Constant(c) => {
let name = format_ident!("{}", c.name);
let ty = rust_type(&c.ty);
let eg = ExpressionGenerator::new(self.hlir);
let initializer =
eg.generate_expression(c.initializer.as_ref());
quote! {
let #name: #ty = #initializer;
}
}
Statement::Transition(transition) => {
let parser = match self.context {
StatementContext::Parser(p) => p,
_ => {
panic!(
"transition statement outside parser: {:#?}",
transition,
)
}
};
match transition {
Transition::Reference(next_state) => {
match next_state.name.as_str() {
"accept" => quote! { return true; },
"reject" => quote! { return false; },
state_ref => {
let state_name = format_ident!(
"{}_{}",
parser.name,
state_ref
);
let mut args = Vec::new();
for arg in &parser.parameters {
let name = format_ident!("{}", arg.name);
args.push(quote! { #name });
}
quote! {
softnpu_provider::parser_transition!(||(#state_ref));
return #state_name( #(#args),* );
}
}
}
}
Transition::Select(_) => {
todo!();
}
}
}
Statement::Return(xpr) => {
let eg = ExpressionGenerator::new(self.hlir);
if let Some(xpr) = xpr {
let xp = eg.generate_expression(xpr.as_ref());
quote! { return #xp; }
} else {
quote! { return }
}
}
}
}
fn generate_parser_body_call(
&self,
parser: &Parser,
c: &Call,
tokens: &mut TokenStream,
) {
let lval: Vec<TokenStream> = c
.lval
.name
.split('.')
.map(|x| format_ident!("{}", x))
.map(|x| quote! { #x })
.collect();
let mut args = Vec::new();
for a in &c.args {
match &a.kind {
ExpressionKind::Lvalue(lvarg) => {
let parts: Vec<&str> = lvarg.name.split('.').collect();
let root = parts[0];
let mut mut_arg = false;
for parg in &parser.parameters {
if parg.name == root {
match parg.direction {
Direction::Out | Direction::InOut => {
mut_arg = true;
}
_ => {}
}
}
}
let lvref: Vec<TokenStream> = parts
.iter()
.map(|x| format_ident!("{}", x))
.map(|x| quote! { #x })
.collect();
if mut_arg {
args.push(quote! { &mut #(#lvref).* });
} else {
args.push(quote! { #(#lvref).* });
}
}
x => todo!("extern arg {:?}", x),
}
}
tokens.extend(quote! {
#(#lval).* ( #(#args),* );
});
}
fn generate_control_body_call(
&self,
control: &Control,
c: &Call,
tokens: &mut TokenStream,
) {
//
// get the lval reference to the thing being called
//
if c.lval.name.split('.').count() < 2 {
panic!(
"codegen: bare calls not supported, \
only <ref>.apply() calls are: {:#?}",
c
);
}
match c.lval.leaf() {
"apply" => {
self.generate_control_apply_body_call(control, c, tokens);
}
"setValid" => {
self.generate_header_set_validity(c, tokens, true);
}
"setInvalid" => {
self.generate_header_set_validity(c, tokens, false);
}
"isValid" => {
self.generate_header_get_validity(c, tokens);
}
_ => {
// assume we are at an extern call
// TODO check the extern call against defined externs in checker
// before we get here
self.generate_control_extern_call(control, c, tokens);
}
}
}
fn generate_control_extern_call(
&self,
_control: &Control,
c: &Call,
tokens: &mut TokenStream,
) {
let eg = ExpressionGenerator::new(self.hlir);
let mut args = Vec::new();
for a in &c.args {
let arg_xpr = eg.generate_expression(a.as_ref());
args.push(arg_xpr);
}
let lvref: Vec<TokenStream> = c
.lval
.name
.split('.')
.map(|x| format_ident!("{}", x))
.map(|x| quote! { #x })
.collect();
tokens.extend(quote! {
#(#lvref).*(#(#args),*);
})
}
fn generate_control_apply_body_call(
&self,
control: &Control,
c: &Call,
tokens: &mut TokenStream,
) {
let name_info = self
.hlir
.lvalue_decls
.get(&c.lval.pop_right())
.unwrap_or_else(|| {
panic!("codegen: lval root for {:#?} not found in hlir", c.lval)
});
let control_instance = match &name_info.ty {
Type::UserDefined(name) => {
self.ast.get_control(name).unwrap_or_else(|| {
panic!("codegen: control {} not found in AST", name,)
})
}
Type::Table => control,
t => panic!("call references non-user-defined type {:#?}", t),
};
let root = c.lval.root();
// This is a call to another control instance
if control_instance.name != control.name {
let eg = ExpressionGenerator::new(self.hlir);
let mut locals = Vec::new();
let mut args = Vec::new();
for (i, a) in c.args.iter().enumerate() {
let arg_xpr = eg.generate_expression(a.as_ref());
let et = self.hlir.expression_types.get(a.as_ref()).unwrap();
let local_name = format_ident!("arg{}", i);
if let ExpressionKind::BitLit(_, _) = a.as_ref().kind {
locals.push(quote! {
let mut #local_name = #arg_xpr;
})
}
match control_instance.parameters[i].direction {
Direction::Out | Direction::InOut => {
match &a.as_ref().kind {
ExpressionKind::Lvalue(lval) => {
let name_info = self
.hlir
.lvalue_decls
.get(lval)
.unwrap_or_else(|| {
panic!(
"codegen: lvalue resolve fail {:#?}",
lval
)
});
match name_info.decl {
// if this is a control parameter, it should
// already have the correct reference
// annotations
DeclarationInfo::Parameter(_) => {
args.push(arg_xpr);
}
_ => {
args.push(quote! {&mut #arg_xpr});
}
}
}
ExpressionKind::BitLit(_, _) => {
args.push(quote! { &mut #local_name })
}
_ => {
args.push(quote! {&mut #arg_xpr});
}
}
}
_ => match &a.as_ref().kind {
ExpressionKind::BitLit(_, _) => {
args.push(quote! { &#local_name })
}
// if the argument is an lvalue and a rust type that
// gets passed by reference, take a ref
ExpressionKind::Lvalue(_) => match et {
Type::Bit(_) | Type::Varbit(_) | Type::Int(_) => {
args.push(quote! { &#arg_xpr });
}
_ => {
args.push(arg_xpr);
}
},
_ => {
args.push(arg_xpr);
}
},
}
}
let tables = control_instance.tables(self.ast);
for (cs, table) in tables {
let qtn =
crate::qualified_table_function_name(None, &cs, table);
let name = format_ident!("{}_{}", c.lval.root(), qtn);
args.push(quote! { #name });
}
let cname = &control_instance.name;
let call = format_ident!("{}_apply", control_instance.name);
tokens.extend(quote! {
softnpu_provider::control_apply!(||(#cname));
#(#locals);*
#call(#(#args),*);
});
return;
}
// this is a local table
let table = match control_instance.get_table(root) {
Some(table) => table,
None => {
panic!(
"codegen: table {} not found in control {} decl: {:#?}",
root, control.name, name_info,
);
}
};
//
// match an action based on the key material
//
let table_name = format_ident!("{}", c.lval.root());
let table_name_str =
format!("{}_table_{}", control_instance.name, table.name,);
let mut action_args = Vec::new();
for p in &control.parameters {
let name = format_ident!("{}", p.name);
action_args.push(quote! { #name });
}
for var in &control.variables {
let name = format_ident!("{}", var.name);
if let Type::UserDefined(typename) = &var.ty {
if self.ast.get_extern(typename).is_some() {
action_args.push(quote! { &#name });
}
}
}
let mut selector_components = Vec::new();
for (lval, _match_kind) in &table.key {
let lvref: Vec<TokenStream> = lval
.name
.split('.')
.map(|x| format_ident!("{}", x))
.map(|x| quote! { #x })
.collect();
// determine if this lvalue references a header or a struct,
// if it's a header there's a bit of extra unsrapping we
// need to do to match the selector against the value.
let names = control.names();
if lval.degree() > 1
&& is_header(&lval.pop_right(), self.ast, &names)
{
//TODO: to_biguint is bad here, copying on data path
selector_components.push(quote! {
p4rs::bitvec_to_biguint(
&#(#lvref).*
).value
});
} else {
selector_components.push(quote! {
p4rs::bitvec_to_biguint(&#(#lvref).*).value
});
}
}
let default_action =
format_ident!("{}_action_{}", control.name, table.default_action);
tokens.extend(quote! {
let matches = #table_name.match_selector(
&[#(#selector_components),*]
);
if matches.len() > 0 {
softnpu_provider::control_table_hit!(||#table_name_str);
(matches[0].action)(#(#action_args),*)
}
});
if table.default_action != "NoAction" {
tokens.extend(quote! {
else {
softnpu_provider::control_table_miss!(||#table_name_str);
#default_action(#(#action_args),*);
}
});
} else {
tokens.extend(quote! {
else {
softnpu_provider::control_table_miss!(||#table_name_str);
}
});
}
}
fn generate_header_set_validity(
&self,
c: &Call,
tokens: &mut TokenStream,
valid: bool,
) {
let lhs: Vec<TokenStream> = c
.lval
.pop_right()
.name
.split('.')
.map(|x| format_ident!("{}", x))
.map(|x| quote! { #x })
.collect();
if valid {
tokens.extend(quote! {
#(#lhs).*.set_valid();
});
} else {
tokens.extend(quote! {
#(#lhs).*.set_invalid();
});
}
}
fn generate_header_get_validity(&self, c: &Call, tokens: &mut TokenStream) {
let lhs: Vec<TokenStream> = c
.lval
.pop_right()
.name
.split('.')
.map(|x| format_ident!("{}", x))
.map(|x| quote! { #x })
.collect();
tokens.extend(quote! {
#(#lhs).*.is_valid()
});
}
fn converter(&self, from: &Type, to: &Type) -> TokenStream {
match (from, to) {
(Type::Int(_), Type::Bit(_)) => {
quote! { p4rs::int_to_bitvec }
}
(Type::Bit(x), Type::Bit(16)) if *x <= 16 => {
quote! { p4rs::bitvec_to_bitvec16 }
}
_ => todo!("type converter for {} to {}", from, to),
}
}
}