facebook / starlark-rust

A Rust implementation of the Starlark language
Apache License 2.0
699 stars 57 forks source link

how do user defined types interact with typechecking? #119

Closed johnynek closed 6 months ago

johnynek commented 6 months ago

Thanks for this great library and the documentation.

I have been working on some example configuration tooling based on this library and I would like to have typechecking working for my particular dialect of starlark.

Taking as an example your complex type here:

https://docs.rs/starlark/latest/starlark/#defining-rust-objects-that-are-used-from-starlark

I tried to implement something similar to Label in the standard bazel starlark:

#[derive(Debug, PartialEq, Eq, ProvidesStaticType, Allocative)]
struct Label { path: String, name: String }
starlark_simple_value!(Label);

impl Label {
  pub fn string_repr(&self) -> String {
    format!("{:}:{:}", self.path, self.name)
  }
}

#[starlark_value(type = "Label")]
impl<'v> StarlarkValue<'v> for Label {

I would have thought that type = Label would have allowed me to use Label in typechecking:

foo: Label = ...

but I get an error like: error: VariableLabelnot found

Is there something else I need to do make that type name available? If I remove the type ascription then everything I am doing works, so I'm wiring up my functions correctly.

Rather than debug my particular example, another possible solution to this issue would be to make your complex example work with typechecking so that your newly introduced type could be referenced in type annotations.

Thank you!

stepancheg commented 6 months ago

Is there something else I need to do make that type name available?

Use StarlarkValueAsType to define global with type symbol.

Overall, typechecking documentation is heavily outdated. For example, if you start using this symbol in function signatures, it will be runtime typechecking, but static typechecking is turned off by default.

johnynek commented 6 months ago

Thank you for the reply.

After your comment I found this code as a good example to learn from:

https://github.com/facebook/starlark-rust/blob/1054d4bd20601cbd6bdb91b742202b779964d1bb/starlark/src/tests/docs/rustdocs.rs#L72

Thanks again. I'm unblocked.