Skip to content

Commit

Permalink
Document the backend (#2365)
Browse files Browse the repository at this point in the history
* Document the backend. All of it

* Fix formatting error

* Shim docs improvement

* Further improve shim
  • Loading branch information
CraftSpider authored Nov 25, 2020
1 parent e0ffa8f commit 83cc988
Show file tree
Hide file tree
Showing 5 changed files with 164 additions and 3 deletions.
116 changes: 116 additions & 0 deletions crates/backend/src/ast.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
//! A representation of the Abstract Syntax Tree of a Rust program,
//! with all the added metadata necessary to generate WASM bindings
//! for it.
use crate::Diagnostic;
use proc_macro2::{Ident, Span};
use std::hash::{Hash, Hasher};
Expand Down Expand Up @@ -71,20 +75,29 @@ pub enum MethodSelf {
RefShared,
}

/// Things imported from a JS module (in an `extern` block)
#[cfg_attr(feature = "extra-traits", derive(Debug))]
#[derive(Clone)]
pub struct Import {
/// The type of module being imported from
pub module: ImportModule,
/// The namespace to access the item through, if any
pub js_namespace: Option<Vec<String>>,
/// The type of item being imported
pub kind: ImportKind,
}

/// The possible types of module to import from
#[cfg_attr(feature = "extra-traits", derive(Debug))]
#[derive(Clone)]
pub enum ImportModule {
/// No module / import from global scope
None,
/// Import from the named module, with relative paths interpreted
Named(String, Span),
/// Import from the named module, without interpreting paths
RawNamed(String, Span),
/// Import from an inline JS snippet
Inline(usize, Span),
}

Expand All @@ -110,91 +123,147 @@ impl Hash for ImportModule {
}
}

/// The type of item being imported
#[cfg_attr(feature = "extra-traits", derive(Debug))]
#[derive(Clone)]
pub enum ImportKind {
/// Importing a function
Function(ImportFunction),
/// Importing a static value
Static(ImportStatic),
/// Importing a type/class
Type(ImportType),
/// Importing a JS enum
Enum(ImportEnum),
}

/// A function being imported from JS
#[cfg_attr(feature = "extra-traits", derive(Debug))]
#[derive(Clone)]
pub struct ImportFunction {
/// The full signature of the function
pub function: Function,
/// The name rust code will use
pub rust_name: Ident,
/// The type being returned
pub js_ret: Option<syn::Type>,
/// Whether to catch JS exceptions
pub catch: bool,
/// Whether the function is variadic on the JS side
pub variadic: bool,
/// Whether the function should use structural type checking
pub structural: bool,
/// Causes the Builder (See cli-support::js::binding::Builder) to error out if
/// it finds itself generating code for a function with this signature
pub assert_no_shim: bool,
/// The kind of function being imported
pub kind: ImportFunctionKind,
/// The shim name to use in the generated code. The 'shim' is a function that appears in
/// the generated JS as a wrapper around the actual function to import, performing any
/// necessary conversions (EG adding a try/catch to change a thrown error into a Result)
pub shim: Ident,
/// The doc comment on this import, if one is provided
pub doc_comment: Option<String>,
}

/// The type of a function being imported
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub enum ImportFunctionKind {
/// A class method
Method {
/// The name of the class for this method, in JS
class: String,
/// The type of the class for this method, in Rust
ty: syn::Type,
/// The kind of method this is
kind: MethodKind,
},
/// A standard function
Normal,
}

/// The type of a method
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub enum MethodKind {
/// A class constructor
Constructor,
/// Any other kind of method
Operation(Operation),
}

/// The operation performed by a class method
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct Operation {
/// Whether this method is static
pub is_static: bool,
/// The internal kind of this Operation
pub kind: OperationKind,
}

/// The kind of operation performed by a method
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub enum OperationKind {
/// A standard method, nothing special
Regular,
/// A method for getting the value of the provided Ident
Getter(Option<Ident>),
/// A method for setting the value of the provided Ident
Setter(Option<Ident>),
/// A dynamically intercepted getter
IndexingGetter,
/// A dynamically intercepted setter
IndexingSetter,
/// A dynamically intercepted deleter
IndexingDeleter,
}

/// The type of a static being imported
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct ImportStatic {
/// The visibility of this static in Rust
pub vis: syn::Visibility,
/// The type of static being imported
pub ty: syn::Type,
/// The name of the shim function used to access this static
pub shim: Ident,
/// The name of this static on the Rust side
pub rust_name: Ident,
/// The name of this static on the JS side
pub js_name: String,
}

/// The metadata for a type being imported
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct ImportType {
/// The visibility of this type in Rust
pub vis: syn::Visibility,
/// The name of this type on the Rust side
pub rust_name: Ident,
/// The name of this type on the JS side
pub js_name: String,
/// The custom attributes to apply to this type
pub attrs: Vec<syn::Attribute>,
/// The TS definition to generate for this type
pub typescript_type: Option<String>,
/// The doc comment applied to this type, if one exists
pub doc_comment: Option<String>,
/// The name of the shim to check instanceof for this type
pub instanceof_shim: String,
/// The name of the remote function to use for the generated is_type_of
pub is_type_of: Option<syn::Expr>,
/// The list of classes this extends, if any
pub extends: Vec<syn::Path>,
/// A custom prefix to add and attempt to fall back to, if the type isn't found
pub vendor_prefixes: Vec<Ident>,
}

/// The metadata for an Enum being imported
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct ImportEnum {
Expand All @@ -210,76 +279,123 @@ pub struct ImportEnum {
pub rust_attrs: Vec<syn::Attribute>,
}

/// Information about a function being imported or exported
#[cfg_attr(feature = "extra-traits", derive(Debug))]
#[derive(Clone)]
pub struct Function {
/// The name of the function
pub name: String,
/// The span of the function's name in Rust code
pub name_span: Span,
/// Whether the function has a js_name attribute
pub renamed_via_js_name: bool,
/// The arguments to the function
pub arguments: Vec<syn::PatType>,
/// The return type of the function, if provided
pub ret: Option<syn::Type>,
/// Any custom attributes being applied to the function
pub rust_attrs: Vec<syn::Attribute>,
/// The visibility of this function in Rust
pub rust_vis: syn::Visibility,
/// Whether this is an `async` function
pub r#async: bool,
/// Whether to generate a typescript definition for this function
pub generate_typescript: bool,
}

/// Information about a Struct being exported
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct Struct {
/// The name of the struct in Rust code
pub rust_name: Ident,
/// The name of the struct in JS code
pub js_name: String,
/// All the fields of this struct to export
pub fields: Vec<StructField>,
/// The doc comments on this struct, if provided
pub comments: Vec<String>,
/// Whether this struct is inspectable (provides toJSON/toString properties to JS)
pub is_inspectable: bool,
/// Whether to generate a typescript definition for this struct
pub generate_typescript: bool,
}

/// The field of a struct
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct StructField {
/// The name of the field in Rust code
pub rust_name: syn::Member,
/// The name of the field in JS code
pub js_name: String,
/// The name of the struct this field is part of
pub struct_name: Ident,
/// Whether this value is read-only to JS
pub readonly: bool,
/// The type of this field
pub ty: syn::Type,
/// The name of the getter shim for this field
pub getter: Ident,
/// The name of the setter shim for this field
pub setter: Ident,
/// The doc comments on this field, if any
pub comments: Vec<String>,
/// Whether to generate a typescript definition for this field
pub generate_typescript: bool,
}

/// Information about an Enum being exported
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct Enum {
/// The name of this enum in Rust code
pub rust_name: Ident,
/// The name of this enum in JS code
pub js_name: String,
/// The variants provided by this enum
pub variants: Vec<Variant>,
/// The doc comments on this enum, if any
pub comments: Vec<String>,
/// The value to use for a `none` variant of the enum
pub hole: u32,
/// Whether to generate a typescript definition for this enum
pub generate_typescript: bool,
}

/// The variant of an enum
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct Variant {
/// The name of this variant
pub name: Ident,
/// The backing value of this variant
pub value: u32,
/// The doc comments on this variant, if any
pub comments: Vec<String>,
}

/// Unused, the type of an argument to / return from a function
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum TypeKind {
/// A by-reference arg, EG `&T`
ByRef,
/// A by-mutable-reference arg, EG `&mut T`
ByMutRef,
/// A by-value arg, EG `T`
ByValue,
}

/// Unused, the location of a type for a function argument (import/export, argument/ret)
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum TypeLocation {
/// An imported argument (JS side type)
ImportArgument,
/// An imported return
ImportRet,
/// An exported argument (Rust side type)
ExportArgument,
/// An exported return
ExportRet,
}

Expand Down
4 changes: 4 additions & 0 deletions crates/backend/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ use std::sync::Mutex;
use syn;
use wasm_bindgen_shared as shared;

/// A trait for converting AST structs into Tokens and adding them to a TokenStream,
/// or providing a diagnostic if conversion fails.
pub trait TryToTokens {
/// Attempt to convert a `Self` into tokens and add it to the `TokenStream`
fn try_to_tokens(&self, tokens: &mut TokenStream) -> Result<(), Diagnostic>;

/// Attempt to convert a `Self` into a new `TokenStream`
fn try_to_token_stream(&self) -> Result<TokenStream, Diagnostic> {
let mut tokens = TokenStream::new();
self.try_to_tokens(&mut tokens)?;
Expand Down
9 changes: 9 additions & 0 deletions crates/backend/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@ use proc_macro2::*;
use quote::{ToTokens, TokenStreamExt};
use syn::parse::Error;

/// Provide a Diagnostic with the given span and message
#[macro_export]
macro_rules! err_span {
($span:expr, $($msg:tt)*) => (
$crate::Diagnostic::spanned_error(&$span, format!($($msg)*))
)
}

/// Immediately fail and return an Err, with the arguments passed to err_span!
#[macro_export]
macro_rules! bail_span {
($($t:tt)*) => (
return Err(err_span!($($t)*).into())
)
}

/// A struct representing a diagnostic to emit to the end-user as an error.
#[derive(Debug)]
pub struct Diagnostic {
inner: Repr,
Expand All @@ -34,6 +37,7 @@ enum Repr {
}

impl Diagnostic {
/// Generate a `Diagnostic` from an informational message with no Span
pub fn error<T: Into<String>>(text: T) -> Diagnostic {
Diagnostic {
inner: Repr::Single {
Expand All @@ -43,6 +47,7 @@ impl Diagnostic {
}
}

/// Generate a `Diagnostic` from a Span and an informational message
pub fn span_error<T: Into<String>>(span: Span, text: T) -> Diagnostic {
Diagnostic {
inner: Repr::Single {
Expand All @@ -52,6 +57,7 @@ impl Diagnostic {
}
}

/// Generate a `Diagnostic` from the span of any tokenizable object and a message
pub fn spanned_error<T: Into<String>>(node: &dyn ToTokens, text: T) -> Diagnostic {
Diagnostic {
inner: Repr::Single {
Expand All @@ -61,6 +67,8 @@ impl Diagnostic {
}
}

/// Attempt to generate a `Diagnostic` from a vector of other `Diagnostic` instances.
/// If the `Vec` is empty, returns `Ok(())`, otherwise returns the new `Diagnostic`
pub fn from_vec(diagnostics: Vec<Diagnostic>) -> Result<(), Diagnostic> {
if diagnostics.len() == 0 {
Ok(())
Expand All @@ -71,6 +79,7 @@ impl Diagnostic {
}
}

/// Immediately trigger a panic from this `Diagnostic`
#[allow(unconditional_recursion)]
pub fn panic(&self) -> ! {
match &self.inner {
Expand Down
Loading

0 comments on commit 83cc988

Please sign in to comment.