Skip to main content

reda_v/parse/
mod.rs

1mod base;
2mod expr;
3pub mod error;
4pub use error::ParseError;
5use std::path::Path;
6
7use base::*;
8use expr::*;
9use nom::multi::many0;
10use nom::sequence::preceded;
11use nom::{branch::alt, bytes::complete::tag, character::complete::char, multi::separated_list0, sequence::delimited};
12use nom::combinator::{map, opt};
13use crate::model::{Always, Assign, Connection, EdgeKind, Instance, Module, Net, NetKind, Parameter, Port, PortDirection, Range, SensitivityEvent, SensitivityList, Stmt, Verilog};
14
15pub fn load_file<P: AsRef<Path>>(path: P) -> Result<Verilog, ParseError> {
16    let source = std::fs::read_to_string(path)?;
17    let (_, v) = verilog(&source).map_err(|e| ParseError::Parse(e.to_string()))?;
18    Ok(v)
19}
20
21pub fn load_str(source: &str) -> Result<Verilog, ParseError> {
22    let (_, v) = verilog(&source).map_err(|e| ParseError::Parse(e.to_string()))?;
23    Ok(v)
24}
25
26pub fn verilog(input: &str) -> NomResult<Verilog> {
27    let (input, modules) = many0(hws(module))(input)?;
28    Ok((input, Verilog { modules }))
29}
30
31pub fn module(input: &str) -> NomResult<Module> {
32    let (input, _) = hws(tag("module"))(input)?;
33    let (input, name) = hws(identifier)(input).to_failure()?;
34    let (input, port_names) = delimited(
35        hws(char('(')),
36        separated_list0(hws(char(',')), identifier),
37        hws(char(')'))
38    )(input).to_failure()?;
39    let (input, _) = hws(char(';'))(input).to_failure()?;
40
41    // parse items until endmodule
42    let (input, items) = many0(alt((
43        map(port, ModuleItem::Port),
44        map(parameter, ModuleItem::Parameter),
45        map(net, ModuleItem::Net),
46        map(assign, ModuleItem::Assign),
47        map(always, ModuleItem::Always),
48        map(instance, ModuleItem::Instance),
49    )))(input)?;
50
51    let (input, _) = hws(tag("endmodule"))(input).to_failure()?;
52
53    let mut ports = vec![];
54    let mut parameters = vec![];
55    let mut nets = vec![];
56    let mut assigns = vec![];
57    let mut alwayses = vec![];
58    let mut instances = vec![];
59
60    for item in items {
61        match item {
62            ModuleItem::Port(p) => ports.push(p),
63            ModuleItem::Parameter(p) => parameters.push(p),
64            ModuleItem::Net(n) => nets.push(n),
65            ModuleItem::Assign(a) => assigns.push(a),
66            ModuleItem::Always(a) => alwayses.push(a),
67            ModuleItem::Instance(i) => instances.push(i),
68        }
69    }
70
71    Ok((input, Module {
72        name: name.to_string(),
73        port_names: port_names.into_iter().map(|p| p.to_string()).collect(),
74        ports,
75        nets,
76        parameters,
77        assign: assigns,
78        always: alwayses,
79        instances,
80    }))
81}
82
83enum ModuleItem {
84    Port(Port),
85    Parameter(Parameter),
86    Net(Net),
87    Assign(Assign),
88    Always(Always),
89    Instance(Instance),
90}
91
92pub fn port(input: &str) -> NomResult<Port> {
93    let (input, dir) = hws(hws(alt((
94        map(tag("input"), |_| PortDirection::Input),
95        map(tag("output"), |_| PortDirection::Output),
96        map(tag("inout"), |_| PortDirection::Inout),
97    ))))(input)?;
98
99    let (input, width) = opt(range)(input).to_failure()?;
100    let (input, name) = hws(identifier)(input).to_failure()?;
101    let (input, _) = hws(char(';'))(input).to_failure()?;
102
103    Ok((input, Port {
104        name: name.to_string(),
105        direction: dir,
106        width,
107    }))
108}
109
110pub fn range(input: &str) -> NomResult<Range> {
111    let (input, _) = hws(char('['))(input)?;
112    let (input, msb) = unsigned_int(input).to_failure()?;
113    let (input, _) = hws(char(':'))(input).to_failure()?;
114    let (input, lsb) = unsigned_int(input).to_failure()?;
115    let (input, _) = hws(char(']'))(input).to_failure()?;
116    Ok((input, Range { msb: msb as i32, lsb: lsb as i32 }))
117}
118
119pub fn parameter(input: &str) -> NomResult<Parameter> {
120    let (input, _) = hws(tag("parameter"))(input)?;
121    let (input, name) = hws(identifier)(input)?;
122    let (input, _) = hws(char('='))(input)?;
123    let (input, expr) = hws(const_expr)(input)?;
124    Ok((input, Parameter {
125        name: name.to_string(),
126        value: expr,
127    }))
128}
129
130pub fn net(input: &str) -> NomResult<Net> {
131    let (input, kind) = hws(alt((
132        map(tag("wire"), |_| NetKind::Wire),
133        map(tag("reg"), |_| NetKind::Reg),
134    )))(input)?;
135    let (input, width) = opt(range)(input).to_failure()?;
136    let (input, name) = hws(identifier)(input).to_failure()?;
137    let (input, _) = hws(char(';'))(input).to_failure()?;
138    Ok((input, Net {
139        kind,
140        name: name.to_string(),
141        width,
142    }))
143}
144
145pub fn assign(input: &str) -> NomResult<Assign> {
146    let (input, _) = hws(tag("assign"))(input)?;
147    let (input, lhs) = var_expr(input).to_failure()?; 
148    let (input, _) = hws(char('='))(input).to_failure()?;
149    let (input, rhs) = expr(input).to_failure()?;
150    let (input, _) = hws(char(';'))(input).to_failure()?;
151    Ok((input, Assign { lhs, rhs }))
152}
153
154pub fn always(input: &str) -> NomResult<Always> {
155    let (input, _) = hws(tag("always"))(input)?;
156    let (input, _) = hws(char('@'))(input).to_failure()?;
157
158    let (input, _) = hws(char('('))(input).to_failure()?;
159
160    // * or event?
161    let (input, width) = opt(hws(char('*')))(input).to_failure()?;
162    let (input, list) = match width {
163        Some(_) => (input, SensitivityList::Star),
164        None => {
165            let (input, events) = hws(separated_list0(hws(char(',')), sensitivity_event))(input)?;
166            (input, SensitivityList::List(events))
167        }
168    };
169    let (input, _) = hws(char(')'))(input).to_failure()?;
170    let (input, stmts) = hws(stmts)(input).to_failure()?;
171
172    Ok((input, Always {
173        sensitivity: list,
174        stmts, 
175    }))
176}
177
178pub fn sensitivity_event(input: &str) -> NomResult<SensitivityEvent> {
179    let (input, edge) = hws(opt(alt((
180        map(tag("posedge"), |_| EdgeKind::Posedge),
181        map(tag("negedge"), |_| EdgeKind::Negedge),
182    ))))(input)?;
183
184    let (input, signal) = hws(identifier)(input).to_failure()?;
185    Ok((input, SensitivityEvent {
186        edge,
187        signal: signal.to_string(),
188    }))
189}
190
191pub fn instance(input: &str) -> NomResult<Instance> {
192    let (input, module_name) = hws(identifier)(input)?;
193    let (input, instance_name) = hws(identifier)(input)?;
194
195    let (input, connections) = delimited(
196        hws(char('(')),
197        separated_list0(
198            hws(char(',')),
199            connection, // 解析单个 .port(expr)
200        ),
201        hws(char(')')),
202    )(input).to_failure()?;
203
204    let (input, _) = hws(char(';'))(input).to_failure()?;
205
206    Ok((
207        input,
208        Instance {
209            module_name: module_name.to_string(),
210            instance_name: instance_name.to_string(),
211            connections,
212        },
213    ))
214}
215
216/// 解析单个端口连接:.port(expr)
217pub fn connection(input: &str) -> NomResult<Connection> {
218    let (input, _) = hws(char('.'))(input)?;
219    let (input, port) = hws(identifier)(input)?;
220    let (input, expr) = delimited(hws(char('(')), expr, hws(char(')')))(input)?;
221    Ok((input, Connection {
222        port: port.to_string(),
223        expr,
224    }))
225}
226
227pub fn stmts(input: &str) -> NomResult<Vec<Stmt>> {
228    /*
229        stmts := "begin" stmt* "end"
230              | stmt
231    */
232    let parse_block = delimited(
233        hws(tag("begin")),
234        many0(hws(stmt)),
235        hws(tag("end")),
236    );
237    alt((
238        parse_block,
239        map(hws(stmt), |s| vec![s]),
240    ))(input)
241}
242
243pub fn stmt(input: &str) -> NomResult<Stmt> {
244    // TODO: case
245    alt((   
246        blocking_assign_stmt,
247        nonblocking_assign_stmt,
248        if_stmt,
249    ))(input)
250}
251
252pub fn blocking_assign_stmt(input: &str) -> NomResult<Stmt> {
253    let (input, lhs) = hws(var_expr)(input)?;
254    let (input, _) = hws(tag("="))(input)?;
255    let (input, rhs) = hws(expr)(input)?;
256    let (input, _) = hws(char(';'))(input)?;
257    Ok((input, Stmt::BlockingAssign { lhs, rhs }))
258}
259    
260pub fn nonblocking_assign_stmt(input: &str) -> NomResult<Stmt> {
261    let (input, lhs) = hws(var_expr)(input)?;
262    let (input, _) = hws(tag("<="))(input)?;
263    let (input, rhs) = hws(expr)(input)?;
264    let (input, _) = hws(char(';'))(input)?;
265    Ok((input, Stmt::NonBlockingAssign { lhs, rhs }))
266}
267
268pub fn if_stmt(input: &str) -> NomResult<Stmt> {
269    let (input, _) = hws(tag("if"))(input)?;
270    let (input, cond) = delimited(hws(char('(')), expr, hws(char(')')))(input)?;
271    let (input, then_body) = stmts(input)?;
272    // optional else
273    let (input, else_body) = opt(preceded(hws(tag("else")), stmts))(input)?;
274    Ok((input, Stmt::If { cond, then_body, else_body }))
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280    use crate::model::{EdgeKind, Expr, NetKind, PortDirection, ValueBase, VarExpr};
281
282    #[test]
283    fn test_empty_module() {
284        let input = r#"
285module mymod (a, b, c);
286endmodule
287"#;
288        let (_, m) = module(input).unwrap();
289        assert_eq!(m.name, "mymod");
290        assert_eq!(m.port_names.len(), 3);
291    }
292
293    #[test]
294    fn test_port_parsing() {
295        let inputs = vec![
296            ("input clk;", "clk", PortDirection::Input),
297            ("output [7:0] data;", "data", PortDirection::Output),
298            ("inout rst;", "rst", PortDirection::Inout),
299        ];
300
301        for (src, name, dir) in inputs {
302            let (_, p) = port(src).unwrap();
303            assert_eq!(p.name, name);
304            assert_eq!(p.direction, dir);
305        }
306    }
307
308    #[test]
309    fn test_range_parsing() {
310        let input = "[15:0]";
311        let (_, r) = range(input).unwrap();
312        assert_eq!(r.msb, 15);
313        assert_eq!(r.lsb, 0);
314    }
315
316    #[test]
317    fn test_net_parsing() {
318        let cases = vec![
319            ("wire clk;", "clk", NetKind::Wire),
320            ("reg [3:0] data;", "data", NetKind::Reg),
321        ];
322
323        for (src, name, kind) in cases {
324            let (_, n) = net(src).unwrap();
325            assert_eq!(n.name, name);
326            assert_eq!(n.kind, kind);
327        }
328    }
329
330    #[test]
331    fn test_assign_parsing() {
332        let input = "assign c = a;";
333        let (_, a) = assign(input).unwrap();
334        match a.lhs {
335            VarExpr::Ident(ref s) => assert_eq!(s, "c"),
336            _ => panic!("LHS not identifier"),
337        }
338        match a.rhs {
339            Expr::Ident(ref s) => assert_eq!(s, "a"),
340            _ => panic!("RHS not identifier"),
341        }
342    }
343
344    #[test]
345    fn test_sensitivity_event_parsing() {
346        let inputs = vec![
347            ("posedge clk", Some(EdgeKind::Posedge), "clk"),
348            ("negedge rst", Some(EdgeKind::Negedge), "rst"),
349            ("data", None, "data"),
350        ];
351
352        for (src, edge, signal) in inputs {
353            let (_, e) = sensitivity_event(src).unwrap();
354            assert_eq!(e.edge, edge);
355            assert_eq!(e.signal, signal);
356        }
357    }
358
359    #[test]
360    fn test_instance_parsing() {
361        let input = r#"
362my_module u1 (
363    .a(signal1),
364    .b(signal2),
365    .c(signal3)
366);
367"#;
368        let (_, inst) = instance(input).unwrap();
369        assert_eq!(inst.module_name, "my_module");
370        assert_eq!(inst.instance_name, "u1");
371        assert_eq!(inst.connections.len(), 3);
372        assert_eq!(inst.connections[0].port, "a");
373        match inst.connections[0].expr {
374            Expr::Ident(ref s) => assert_eq!(s, "signal1"),
375            _ => panic!("Expr not identifier"),
376        }
377    }
378
379    #[test]
380    fn test_stmts_single() {
381        let input = "a = 1;";
382        let (_, ss) = stmts(input).unwrap();
383        assert_eq!(ss.len(), 1);
384    }
385    
386    #[test]
387    fn test_stmts_block() {
388        let input = r#"
389        begin
390            a = 1;
391            b <= 2;
392        end
393        "#;
394        let (_, ss) = stmts(input).unwrap();
395        assert_eq!(ss.len(), 2);
396    }
397
398    #[test]
399    fn test_always_star() {
400        let input = r#"
401        always @(*) begin
402            a = b ;
403            c <= d;
404        end
405        "#;
406        let (_, alw) = always(input).unwrap();
407        match alw.sensitivity {
408            SensitivityList::Star => {}
409            _ => panic!("expected star sensitivity"),
410        }
411        assert_eq!(alw.stmts.len(), 2);
412    }
413
414    #[test]
415    fn test_always_posedge() {
416        let input = r#"
417        always @(posedge clk) q <= d;
418        "#;
419        let (_, alw) = always(input).unwrap();
420        match &alw.sensitivity {
421            SensitivityList::List(events) => {
422                assert_eq!(events.len(), 1);
423                assert_eq!(events[0].signal, "clk");
424                assert_eq!(events[0].edge, Some(EdgeKind::Posedge));
425            }
426            _ => panic!("expected list sensitivity"),
427        }
428        assert_eq!(alw.stmts.len(), 1);
429    }
430
431    #[test]
432    fn test_always_negedge_or_posedge() {
433        let input = r#"
434        always @(negedge rst, posedge clk) begin
435            if (rst) q <= 0;
436            else q <= d;
437        end
438        "#;
439        let (_, alw) = always(input).unwrap();
440        match &alw.sensitivity {
441            SensitivityList::List(events) => {
442                assert_eq!(events.len(), 2);
443                assert_eq!(events[0].signal, "rst");
444                assert_eq!(events[0].edge, Some(EdgeKind::Negedge));
445                assert_eq!(events[1].signal, "clk");
446                assert_eq!(events[1].edge, Some(EdgeKind::Posedge));
447            }
448            _ => panic!("expected list sensitivity"),
449        }
450        assert_eq!(alw.stmts.len(), 1); // if 语句
451    }
452
453    #[test]
454    fn test_always_simple_stmt() {
455        let input = r#"
456        always @(posedge clk) a <= b;
457        "#;
458        let (_, alw) = always(input).unwrap();
459        assert_eq!(alw.stmts.len(), 1);
460    }
461
462    #[test]
463    fn test_always_if_else() {
464        let input = r#"
465        always @(*) begin
466            if (a) b = 1;
467            else b = 0;
468        end
469        "#;
470        let (_, alw) = always(input).unwrap();
471        assert_eq!(alw.stmts.len(), 1); // if stmt
472    }
473
474    #[test]
475    fn test_bin_value_bits() {
476        assert_eq!(
477            bin_value_bits("1010").unwrap().1,
478            "1010".to_string()
479        );
480        assert_eq!(
481            bin_value_bits("10xz_01z1").unwrap().1,
482            "10xz_01z1".to_string()
483        );
484    }
485
486    #[test]
487    fn test_dec_value_bits() {
488        assert_eq!(
489            dec_value_bits("255").unwrap().1,
490            "255".to_string()
491        );
492        assert_eq!(
493            dec_value_bits("12_345").unwrap().1,
494            "12_345".to_string()
495        );
496    }
497
498    #[test]
499    fn test_oct_value_bits() {
500        assert_eq!(
501            oct_value_bits("765").unwrap().1,
502            "765".to_string()
503        );
504        assert_eq!(
505            oct_value_bits("7xz_1").unwrap().1,
506            "7xz_1".to_string()
507        );
508    }
509
510    #[test]
511    fn test_hex_value_bits() {
512        assert_eq!(
513            hex_value_bits("FF").unwrap().1,
514            "FF".to_string()
515        );
516        assert_eq!(
517            hex_value_bits("A3c_zX").unwrap().1,
518            "A3c_zX".to_string()
519        );
520    }
521
522    #[test]
523    fn test_value_parser() {
524        // 4'b1010
525        let (_, v) = value("4'b1010").unwrap();
526        assert_eq!(v.len, 4);
527        assert_eq!(v.base, ValueBase::Bin);
528        assert_eq!(v.bits, "1010");
529
530        // 16'd255
531        let (_, v) = value("16'd255").unwrap();
532        assert_eq!(v.len, 16);
533        assert_eq!(v.base, ValueBase::Dec);
534        assert_eq!(v.bits, "255");
535
536        // 8'hFF
537        let (_, v) = value("8'hFF").unwrap();
538        assert_eq!(v.len, 8);
539        assert_eq!(v.base, ValueBase::Hex);
540        assert_eq!(v.bits, "FF");
541
542        // 8'b10xz_01z1
543        let (_, v) = value("8'b10xz_01z1").unwrap();
544        assert_eq!(v.len, 8);
545        assert_eq!(v.base, ValueBase::Bin);
546        assert_eq!(v.bits, "10xz_01z1");
547    }
548
549
550    #[test]
551    fn test_parameter_simple_value() {
552        let (_, p) = parameter("parameter WIDTH = 8").unwrap();
553        assert_eq!(p.name, "WIDTH");
554    }
555
556    #[test]
557    fn test_parameter_with_hex() {
558        let (_, p) = parameter("parameter ADDR = 16'hFF").unwrap();
559        assert_eq!(p.name, "ADDR");
560    }
561
562    #[test]
563    fn test_parameter_with_expr() {
564        let (_, p) = parameter("parameter SIZE = 4*1024").unwrap();
565        assert_eq!(p.name, "SIZE");
566    }
567}