ombre: Add `doc` intrinsic
3094fa745a6d66bc2461f9099e1c38a8fc7cfc9a
1 parent
2fba52bc
ombre/src/lisp/evaluator.rs
+33 -0
| 741 | 741 | local: HashMap::default(), |
|
| 742 | 742 | docs: HashMap::default(), |
|
| 743 | 743 | parent: None, |
|
| 744 | 744 | exports: HashSet::default(), |
|
| 745 | 745 | }; |
|
| 746 | + | env.intrinsic("doc", "Get the documentation for a symbol", intrinsic::doc); |
|
| 746 | 747 | env.intrinsic( |
|
| 747 | 748 | "env", |
|
| 748 | 749 | "Return the current environment as a dictionary", |
|
| 749 | 750 | intrinsic::env, |
|
| 750 | 751 | ); |
| 1275 | 1276 | actual: arity, |
|
| 1276 | 1277 | })?; |
|
| 1277 | 1278 | Err(Error::User(err)) |
|
| 1278 | 1279 | } |
|
| 1279 | 1280 | ||
| 1281 | + | /// Get the docstring for a symbol. |
|
| 1282 | + | pub fn doc(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1283 | + | let arity = args.len(); |
|
| 1284 | + | let Ok([expr]) = <[_; 1]>::try_from(args) else { |
|
| 1285 | + | return Err(Error::WrongArgumentCount { |
|
| 1286 | + | expected: 1, |
|
| 1287 | + | actual: arity, |
|
| 1288 | + | }); |
|
| 1289 | + | }; |
|
| 1290 | + | ||
| 1291 | + | let Expr::Symbol(name) = expr else { |
|
| 1292 | + | return Err(Error::ExpectedValue("symbol")); |
|
| 1293 | + | }; |
|
| 1294 | + | ||
| 1295 | + | Ok(env |
|
| 1296 | + | .lookup_doc(&name) |
|
| 1297 | + | .map(|s| Expr::Str(s.to_string())) |
|
| 1298 | + | .unwrap_or(Expr::nil())) |
|
| 1299 | + | } |
|
| 1300 | + | ||
| 1280 | 1301 | /// Return the program environment. |
|
| 1281 | 1302 | pub fn env(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1282 | 1303 | if !args.is_empty() { |
|
| 1283 | 1304 | return Err(Error::WrongArgumentCount { |
|
| 1284 | 1305 | expected: 0, |
| 2689 | 2710 | &["(+ (vec2 1 2) (vec2 3 4) (vec2 1 1))"], |
|
| 2690 | 2711 | Expr::Vector2D(Vector2D::new(5., 7.)), |
|
| 2691 | 2712 | ); |
|
| 2692 | 2713 | } |
|
| 2693 | 2714 | ||
| 2715 | + | #[test] |
|
| 2716 | + | fn test_doc() { |
|
| 2717 | + | expect( |
|
| 2718 | + | &[ |
|
| 2719 | + | "(def answer \"The answer to life, the universe and everything.\" 42)", |
|
| 2720 | + | "(doc 'answer)", |
|
| 2721 | + | ], |
|
| 2722 | + | Expr::Str("The answer to life, the universe and everything.".to_string()), |
|
| 2723 | + | ); |
|
| 2724 | + | expect(&["(doc 'undefined)"], Expr::nil()); |
|
| 2725 | + | } |
|
| 2726 | + | ||
| 2694 | 2727 | #[test] |
|
| 2695 | 2728 | fn test_vector_field_access() { |
|
| 2696 | 2729 | expect(&["(:x (vec2 1 2))"], Expr::Float(1.0)); |
|
| 2697 | 2730 | expect(&["(:y (vec2 1 2))"], Expr::Float(2.0)); |
|
| 2698 | 2731 |