llhd 0.16.0

A Low Level Hardware Description that acts as a foundation for building hardware design tools.
Documentation
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
// Copyright (c) 2017-2021 Fabian Schuiki

//! Lexer and parser for Liberty files.

use llhd::{int_ty, ir::prelude::*, signal_ty};
use std::collections::HashMap;

/// A lexer for Liberty files.
pub struct Lexer<I> {
    input: I,
    peek: [Option<u8>; 2],
    done: bool,
    offset: usize,
    line: usize,
    column: usize,
}

/// The token emitted by the lexer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Token {
    Ident(String),
    Literal(String),
    LParen,
    RParen,
    LBrace,
    RBrace,
    Comma,
    Colon,
    Semicolon,
}

impl<I: Iterator<Item = std::io::Result<u8>>> Lexer<I> {
    /// Create a new lexer.
    pub fn new(input: I) -> Self {
        let mut lexer = Self {
            input,
            peek: [None, None],
            done: false,
            offset: 0,
            line: 0,
            column: 0,
        };
        lexer.bump();
        lexer.bump();
        lexer.offset = 0;
        lexer
    }

    /// Advance the lexer to the next character.
    fn bump(&mut self) {
        self.offset += 1;
        if self.peek[0] == Some('\n' as u8) {
            self.line += 1;
            self.column = 0;
        }
        self.peek[0] = self.peek[1];
        if !self.done {
            self.peek[1] = self.input.next().map(|b| b.unwrap());
            if self.peek[1].is_none() {
                self.done = true;
            }
        }
    }
}

fn should_skip(c: char) -> bool {
    c.is_whitespace() || c == '\\'
}

fn is_ident(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '.' || c == '-' || c == '+'
}

impl<I: Iterator<Item = std::io::Result<u8>>> Iterator for Lexer<I> {
    type Item = Token;
    fn next(&mut self) -> Option<Token> {
        loop {
            let p0 = self.peek[0].map(|c| c as char);
            let p1 = self.peek[1].map(|c| c as char);
            match (p0, p1) {
                // Skip multi-line comments.
                (Some('/'), Some('*')) => {
                    self.bump();
                    self.bump();
                    while self.peek[0].is_some()
                        && (self.peek[0] != Some('*' as u8) || self.peek[1] != Some('/' as u8))
                    {
                        self.bump();
                    }
                    self.bump();
                    self.bump();
                    continue;
                }
                // Skip single-line comments.
                (Some('/'), Some('/')) => {
                    self.bump();
                    self.bump();
                    while self.peek[0].is_some() && self.peek[0] != Some('\n' as u8) {
                        self.bump();
                    }
                    continue;
                }
                // Skip whitespace and escapes.
                (Some(c), _) if should_skip(c) => {
                    self.bump();
                    continue;
                }
                // Parse symbols.
                (Some('('), _) => {
                    self.bump();
                    return Some(Token::LParen);
                }
                (Some(')'), _) => {
                    self.bump();
                    return Some(Token::RParen);
                }
                (Some('{'), _) => {
                    self.bump();
                    return Some(Token::LBrace);
                }
                (Some('}'), _) => {
                    self.bump();
                    return Some(Token::RBrace);
                }
                (Some(','), _) => {
                    self.bump();
                    return Some(Token::Comma);
                }
                (Some(':'), _) => {
                    self.bump();
                    return Some(Token::Colon);
                }
                (Some(';'), _) => {
                    self.bump();
                    return Some(Token::Semicolon);
                }
                // Identifiers and numbers.
                (Some(c), _) if is_ident(c) => {
                    let mut v = vec![self.peek[0].unwrap()];
                    self.bump();
                    while let Some(c) = self.peek[0] {
                        if !is_ident(c as char) {
                            break;
                        }
                        v.push(c);
                        self.bump();
                    }
                    let v = match String::from_utf8(v) {
                        Ok(v) => v,
                        Err(e) => panic!(
                            "syntax error: line {} column {} (offset {}): invalid UTF-8 string; {}",
                            self.line + 1,
                            self.column + 1,
                            self.offset,
                            e
                        ),
                    };
                    return Some(Token::Ident(v));
                }
                // Literals.
                (Some('"'), _) => {
                    self.bump();
                    let mut v = vec![];
                    while let Some(c) = self.peek[0] {
                        if self.peek[0] == Some('"' as u8) {
                            break;
                        }
                        if self.peek[0] == Some('\\' as u8) {
                            self.bump();
                        }
                        v.push(c);
                        self.bump();
                    }
                    self.bump();
                    let v = match String::from_utf8(v) {
                        Ok(v) => v,
                        Err(e) => panic!(
                            "syntax error: line {} column {} (offset {}): invalid UTF-8 string; {}",
                            self.line + 1,
                            self.column + 1,
                            self.offset,
                            e
                        ),
                    };
                    return Some(Token::Literal(v));
                }
                // End of file.
                (None, _) => return None,
                (Some(c), _) => panic!(
                    "syntax error: line {} column {} (offset {}): unexpected \"{}\"",
                    self.line + 1,
                    self.column + 1,
                    self.offset,
                    c
                ),
            }
        }
    }
}

/// A visitor for a Liberty file.
pub trait Visitor {
    /// Called for `name : value;` fields.
    fn visit_scalar(&mut self, _name: String, _value: String) {}
    /// Called for `name(values);` fields.
    fn visit_array(&mut self, _name: String, _values: Vec<String>) {}
    /// Called for `name(values) { ... }` fields.
    fn visit_group_begin(&mut self, _name: String, _values: Vec<String>) {}
    /// Called for end of groups.
    fn visit_group_end(&mut self) {}
}

/// Parse a entire Liberty file.
pub fn parse(p: &mut impl Iterator<Item = Token>, with: &mut impl Visitor) {
    loop {
        let name = match p.next() {
            Some(Token::Ident(ident)) => ident,
            Some(Token::RBrace) | None => return,
            _ => panic!("syntax error: expected field name"),
        };
        match p.next() {
            Some(Token::Colon) => {
                let value = match p.next() {
                    Some(Token::Ident(ident)) => ident,
                    Some(Token::Literal(literal)) => literal,
                    _ => panic!("syntax error: expected field value after \":\""),
                };
                match p.next() {
                    Some(Token::Semicolon) => (),
                    _ => panic!("syntax error: expected \";\" after field value"),
                }
                with.visit_scalar(name, value);
            }
            Some(Token::LParen) => {
                let mut values = vec![];
                loop {
                    match p.next() {
                        Some(Token::Ident(ident)) => values.push(ident),
                        Some(Token::Literal(literal)) => values.push(literal),
                        Some(Token::Comma) => (),
                        Some(Token::RParen) => break,
                        _ => panic!("syntax error: expected value or \")\""),
                    }
                }

                match p.next() {
                    Some(Token::Semicolon) => with.visit_array(name, values),
                    Some(Token::LBrace) => {
                        with.visit_group_begin(name, values);
                        parse(p, with);
                        with.visit_group_end();
                    }
                    _ => panic!("{}", r#"syntax error: expected ";" or "{""#),
                }
            }
            _ => panic!(r#"syntax error: expected ":" or "(""#),
        }
    }
}

/// The root visitor.
pub struct RootVisitor<'a> {
    module: &'a mut Module,
    stack: Vec<Context>,
    cell_name: Option<String>,
    cell_inputs: Vec<String>,
    cell_outputs: Vec<(String, String)>,
    pin_name: Option<String>,
    pin_function: Option<String>,
    pin_direction: Option<String>,
}

enum Context {
    None,
    Cell,
    Pin,
}

impl Visitor for RootVisitor<'_> {
    fn visit_scalar(&mut self, name: String, value: String) {
        match self.stack.last() {
            Some(Context::Pin) if name == "function" => self.pin_function = Some(value),
            Some(Context::Pin) if name == "direction" => self.pin_direction = Some(value),
            _ => (),
        }
    }

    fn visit_group_begin(&mut self, name: String, mut values: Vec<String>) {
        let context = match (name.as_str(), values.pop()) {
            ("cell", Some(value)) => {
                self.cell_name = Some(value);
                Context::Cell
            }
            ("pin", Some(value)) => {
                self.pin_name = Some(value);
                self.pin_function = None;
                self.pin_direction = None;
                Context::Pin
            }
            _ => Context::None,
        };
        self.stack.push(context);
    }

    fn visit_group_end(&mut self) {
        match self.stack.pop().expect("unbalanced LIB file") {
            Context::Cell => self.emit_cell(),
            Context::Pin => {
                let dir = self.pin_direction.take();
                let name = self.pin_name.take();
                let func = self.pin_function.take();
                match (dir.as_ref().map(AsRef::as_ref), name, func) {
                    (Some("input"), Some(name), _) => self.cell_inputs.push(name),
                    (Some("output"), Some(name), Some(func)) => {
                        self.cell_outputs.push((name, func))
                    }
                    _ => (),
                }
            }
            Context::None => (),
        }
    }
}

impl<'a> RootVisitor<'a> {
    /// Create a new visitor.
    pub fn new(module: &'a mut Module) -> Self {
        Self {
            module,
            stack: Default::default(),
            cell_name: Default::default(),
            cell_inputs: Default::default(),
            cell_outputs: Default::default(),
            pin_name: Default::default(),
            pin_function: Default::default(),
            pin_direction: Default::default(),
        }
    }

    fn emit_cell(&mut self) {
        let cell_name = match self.cell_name.take() {
            Some(name) => UnitName::Global(name),
            None => return,
        };
        let mut sig = Signature::new();
        let mut input_map = HashMap::new();
        for name in self.cell_inputs.drain(..) {
            let arg = sig.add_input(signal_ty(int_ty(1)));
            input_map.insert(name, arg);
        }
        let mut output_map = HashMap::new();
        let mut funcs = vec![];
        for (name, func) in self.cell_outputs.drain(..) {
            let arg = sig.add_output(signal_ty(int_ty(1)));
            let func = match FunctionParser::new().parse(&func) {
                Ok(f) => f,
                Err(e) => {
                    eprintln!(
                        "{}: invalid function `{}` on pin `{}`; {}",
                        cell_name, func, name, e
                    );
                    return;
                }
            };
            funcs.push((arg, func));
            output_map.insert(name, arg);
        }
        let mut ent = UnitData::new(UnitKind::Entity, cell_name, sig);
        let mut builder = UnitBuilder::new_anonymous(&mut ent);
        for (name, &arg) in input_map.iter().chain(output_map.iter()) {
            let arg = builder.arg_value(arg);
            builder.set_name(arg, name.clone());
        }
        for (arg, func) in funcs {
            let arg = builder.arg_value(arg);
            let value = match self.emit_term(&mut builder, &input_map, func) {
                Ok(v) => v,
                Err(e) => {
                    let unit = builder.finish();
                    eprintln!(
                        "{}: invalid function on `{}`; {}",
                        unit.name(),
                        unit.get_name(arg)
                            .map(str::to_owned)
                            .unwrap_or_else(|| format!("{}", arg)),
                        e
                    );
                    return;
                }
            };
            builder.ins().con(arg, value);
        }
        self.module.add_unit(ent);
    }

    fn emit_term(
        &mut self,
        builder: &mut UnitBuilder,
        map: &HashMap<String, Arg>,
        func: FunctionTerm,
    ) -> Result<Value, String> {
        Ok(match func {
            FunctionTerm::Or(lhs, rhs) => {
                let x = self.emit_term(builder, map, *lhs)?;
                let y = self.emit_term(builder, map, *rhs)?;
                builder.ins().or(x, y)
            }
            FunctionTerm::And(lhs, rhs) => {
                let x = self.emit_term(builder, map, *lhs)?;
                let y = self.emit_term(builder, map, *rhs)?;
                builder.ins().and(x, y)
            }
            FunctionTerm::Not(term) => {
                let x = self.emit_term(builder, map, *term)?;
                builder.ins().not(x)
            }
            FunctionTerm::Atom(name) => {
                let arg = map.get(&name).cloned().ok_or_else(|| {
                    format!("term references argument `{}` which is not a pin", name)
                })?;
                builder.arg_value(arg)
            }
        })
    }
}

#[derive(Debug)]
pub enum FunctionTerm {
    Or(Box<FunctionTerm>, Box<FunctionTerm>),
    And(Box<FunctionTerm>, Box<FunctionTerm>),
    Not(Box<FunctionTerm>),
    Atom(String),
}

#[allow(unused_parens)]
mod grammar {
    include!("liberty_parser.rs");
}

use grammar::FunctionParser;