13 ms·
Typed-Html: Type Checked JSX for Rust
- bhengaij 8y agoObligatory mention- scalatags. Something different but still wicked cool
- gkoberger 8y agoOne thing that's really cool about Rust is you don't need a compiler (like JSX) for this. It's using a procedural macro, so the Rust parser only sees the result of the macro. Basically, with Rust, you can import syntax like this much like you'd import a library in other languages.
- yen223 8y agoIt's such a shame people think languages shouldn't have macros because they're complex. They reduce complexity by shifting custom bespoke syntax out of the language core, and into packages that can be used (or not used) as needed.
- joshuamorton 8y agoProcedural macros aren't macros in the c sense though. They generally are done by acting on an ast (more similar to lisp macros). Macros aren't complex, c preprocessor macros are complex. Although generally, magic that introduces names that aren't defined anywhere is bad, whether it's c macros or a python metaclass, but the metaclass at least has some direct connection to the magic name.
- jstimpfle 8y ago> c preprocessor macros are complex At its core the C preprocessor language is a simple token substitution scheme (meaning it strictly operates on the word level). I couldn't write one without looking at the spec because it has some ugly edges. But fundamentally it's a simple technology. It's flexible but that also means it must be used carefully.
- eridius 8y agoThe core idea of the C preprocessor is relatively simple. But it has very complex effects on the surrounding language.
- anticensor 8y agoC preprocessor is one of the worst design decisions in C. They could have made the directive system into brace-and-semicolon grammar and not introduce a second syntax.
- v_lisivka 8y agoYou can use an other implementation of preprocessor for C/C++, with more features, e.g. DMS[0], which works with AST, or even PHP or Perl, but you will need to parse code twice, so compilation will be about 2x slower. [0]: http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html
- anticensor 8y agoIn C(++), the preprocessing is only way to portably declare directives. All others are vendor-specific. They are working on a common directive and module system now, but it will take at least two more years to be standardised fully.
- v_lisivka 8y ago
- kodablah 8y agoIt's not just complexity, it's compilation time/effort. I personally see no problem with it and am also happy my build.rs script can automatically do logic like code generation at build time. However, I completely understand a Go approach that would never consider such an automatic "go generate".
- staticassertion 8y ago> However, I completely understand a Go approach that would never consider such an automatic "go generate". These end up existing anyways though. At least a few places are using Go with their own preprocessor - isn't Kubernetes doing this?
- yen223 8y agoMy point is exactly that you can opt out of using macros if you so wish, if compilation time were an issue.
- kodablah 8y agoYou have less choice as your transitive dependency tree becomes larger while leveraging the popular libraries in the ecosystem.
- pjmlp 8y agoBecause most of the time they represent a huge debugging effort. For example, how do you step a macro expansion in Rust at any given point in a source level debugger? Yep, you don't. Even on Lisp, if we want something more developer friendly than (macroexpand) the only option are the commercial Common Lisp environments. Having said this, I also do like having macro support around, provided it gets used judiciously.
- iopq 8y ago> For example, how do you step a macro expansion in Rust at any given point in a source level debugger? > Yep, you don't. I don't see any technical reason why that can't be done
- pjmlp 8y agoI provided the example that you have such features in commercial Common Lisp environments. The point it that such kind of tooling is generally not available in FOSS offerings. Yes it can be done, but it isn't currently available.
- bluejekyll 8y agoThis isn’t what you want, but I do want to make sure that people know that there are tools available for at least viewing the expansion: https://github.com/dtolnay/cargo-expand/blob/master/README.md https://github.com/dtolnay/cargo-expand/blob/master/README.m...
- pjmlp 8y agoThanks, it looks interesting. Any plans to make it work on stable?
- steveklabnik 8y agoIt doens't have a ton of pressure to, given that it's a tool. You write "cargo +nightly" instead of "cargo" and it's fine. We'd of course like to have it on stable, like everything, there's just more pressing stuff to stabilize.
- leetbulb 8y agoThis is really cool. How viable would it be (resource consumption, etc) to use it for embedded firmware? Are there any special security considerations such as XSS?
- deleted 8y ago[deleted]
- gregwebs 8y agoNice! It is quite wonderful to know that if your code compiles there are no run-time issues in your templates. Of course, you can achieve this with TypeScript also, but it is easy to introduce errors while making API calls. Haskell has had something similar for many years now [1]. Ultimately the development cycle can become a big issue for this kind of thing (how long does it take to go from editing your type-checked template to being able to see that in the browser). In the Haskell version we did have a development version that allowed certain types of changes to show up quickly. [1] https://www.yesodweb.com/book/shakespearean-templates#shakespearean-templates_hamlet_html https://www.yesodweb.com/book/shakespearean-templates#shakes...
- TheAceOfHearts 8y agoThis is superb, I've been playing around with Rust and had been wanting to dig into doing some web stuff with it. What tools do people use for writing web services with Rust? A component example would be very useful. Being able to abstract away chunks of your views into discrete parts is a pretty important feature. One big thing that's not mentioned in the docs is whether or not it handles escaping values for you, as well as an equivalent of React's dangerouslySetInnerHTML [0] when you wish to embed HTML. [0] https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml https://reactjs.org/docs/dom-elements.html#dangerouslysetinn...
- mark_l_watson 8y agoI am in the same situation: I have lightly played with Rust (because a DLT platform I am interested in is written in Rust) and I want to branch out a bit and try Rust for a fairly simple web app.
- calebh 8y agoDoes anyone have a good way of representing HTML in the form of types? I'm primarily thinking about how it's tricky to pair valid attributes with the correct elements. For example, it should be okay to use the "alt" attribute with the img tag, but not with the p tag. It seems like there should be a type-safe way to do this.
- shaabanban 8y agoIf you use JSX with typescript you effectively get type-checked html attributes.
- btown 8y agoIf you're referring to Rust's ability to infer types from macro tokens, not sure how far you'll get. But Typescript itself can absolutely track permitted attributes for different HTML tags, and it compiles JSX using these types: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L1723 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/mast...
- evmar 8y agoTypeScript's type system can do it: http://www.typescriptlang.org/play/#src=%0D%0A%0D%0Atype%20Att%3CT%20extends%20keyof%20HTMLElementTagNameMap%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BK%20in%20keyof%20HTMLElementTagNameMap%5BT%5D%5D%3F%3A%20HTMLElementTagNameMap%5BT%5D%5BK%5D%3B%0D%0A%7D%0D%0A%0D%0Afunction%20tag%3CT%20extends%20keyof%20HTMLElementTagNameMap%3E(name%3A%20T%2C%20attrs%3A%20Att%3CT%3E)%20%7B%0D%0A%20%20%20%20%2F%2F%20code%20here.%0D%0A%7D%0D%0A%0D%0Atag('a'%2C%20%7B%20href%3A%20'asdfas'%20%7D)%3B%0D%0Atag('a'%2C%20%7B%20href%3A%203%20%7D)%3B%20%2F%2F%20fields%20are%20typed%0D%0Atag('div'%2C%20%7B%20href%3A%20'adfadf'%20%7D)%3B%20%20%2F%2F%20non-anchors%20have%20no%20href%0D%0A http://www.typescriptlang.org/play/#src=%0D%0A%0D%0Atype%20A...
- dtolnay 8y agoThis library represents HTML in types. The <p> tag turns into a typed_html::elements::p [1], inside of which the attributes are held by a typed_html::elements::Attrs_p [2]. [1] https://docs.rs/typed-html/0.1.0/typed_html/elements/struct.p.html https://docs.rs/typed-html/0.1.0/typed_html/elements/struct.... [2] https://docs.rs/typed-html/0.1.0/typed_html/elements/struct.Attrs_p.html https://docs.rs/typed-html/0.1.0/typed_html/elements/struct.... let doc: DOMTree<String> = html!{ <body> <img alt="xxx" /> <p alt="xxx"></p> </body> }; If you try to give <p> an alt attribute, the program fails to compile. error[E0609]: no field `alt` on type `typed_html::elements::Attrs_p` --> src/main.rs:12:16 | 12 | <p alt="xxx"></p> | ^^^ unknown field | = note: available fields are: `accesskey`, `autocapitalize`, `class`, `contenteditable`, `contextmenu` ... and 9 others
- abhinai 8y agoI really think all modern languages should have something like this!
- sidcool 8y agoRust (and the community) is getting these amazing tools out. As a Rustacean it's quite comforting . :)
- rattray 8y agoWould be awesome to see an example of this with a full vdom implementation... the docs just say: Render to a virtual DOM... pass it on to your favourite virtual DOM system Curious what'd it be like to wire this up with virtual-dom or maybe even React itself. Also curious how this compares to https://github.com/DenisKolodin/yew https://github.com/DenisKolodin/yew (which I'm not familiar with).
- bluejekyll 8y agoI used yew’s html! macro for a small experiment about 5 months ago. It’s awesome. The difference between that and this, is mainly this is more typesafe. This will check the types and expected attributes of tags, whereas yew pretty much treats all tags the same way.
- bluejekyll 8y agoThis is super exciting and awesome. I worked with the html! macro from yew, https://github.com/DenisKolodin/yew https://github.com/DenisKolodin/yew, and it had some quirks. Assuming yew hasn’t improved that macro since I used it (5 months back), this looks significantly better in almost every way. It would be very cool to see this become the main library for html generation in Rust (and WASM?). I’ve been following the posts about this library’s development, fun to see it discussed here. But I have to ask, will the choice of the MPL as the license have any effect on its potential adoption? Yew is Apache/MIT, matching Rust and much of the ecosystem, for context.
- drostie 8y agoIt's possible but unlikely. MPL, for folks who aren't aware, is a successor to the CDDL seen in Solaris etc. and is a per-file copyleft, thus having a nicer legal structure while getting the same rough benefits of GPL or at least LGPL. The idea is “any modifications to this file must also be open-sourced under MPL, but you can package this file with proprietary other files that are not MPL and integrate them into a larger proprietary thing as long as your modifications to this file alone are open-sourced.” The goal is to protect weakly from Microsoft-esque “embrace, extend, extinguish” as GPL does but enable commercial integration the way BSD does. In practice nobody seems to be all that pissed at Mozilla because of their license; the MPLv2 added GPL compatibility so the GPLers are mostly able to use MPL software and it gives a nod towards the stronger copyleft they like; commercial applications which just use the software as a library don't mind.
- tannhaeuser 8y agoHow is this checking the content type of HTML elements? The content type of eg. the table element in HTML 5.1 is given by the following production (from [1]): <!-- The table element Content: In this order: optionally a caption element, followed by zero or more colgroup elements, followed optionally by a thead element, followed by either zero or more tbody elements or one or more tr elements, followed optionally by a tfoot element, optionally intermixed with one or more script-supporting elements. --> <!ELEMENT table - - (caption?,colgroup*, thead, (tbody*|tr+),tfoot?) +(%scripting;)> Regular content types are pretty fundamental to markup languages. [1] http://sgmljs.net/docs/w3c-html51-dtd.html http://sgmljs.net/docs/w3c-html51-dtd.html
- zootm 8y agoI think this is mostly answered in the README. This is probably the most relevant section: > The structure validation is simplistic by necessity, as it defers to the type system: a few elements will have one or more required children, and any element which accepts children will have a restriction on the type of the children, usually a broad group as defined by the HTML spec. Many elements have restrictions on children of children, or require a particular ordering of optional elements, which isn't currently validated. It's not complete or thorough at present. Regarding your link: I'm impressed someone took the time to write a DTD for HTML5!
- tannhaeuser 8y agoThanks! The DTD is described in the talk/paper I gave at XML Prague 2017 linked from [1]. Meanwhile, I've got a revised version for HTML 5.2 with basic coverage of the validator.nu test suite, though not published on the site yet. [1]: http://sgmljs.net/blog/blog1701.html http://sgmljs.net/blog/blog1701.html
- oever 8y agoSince the macro is procedural, I suppose it's feasible to pass a DTD, XML Schema or Relax NG to typed-html so it would work with any XML. Ideally with checking of ID and IDREF or key/keyref.
- akubera 8y agof
- biggio 8y agoI always hated mixing up languages together. HTML in Rust? No!
- hbbio 8y agoIt's funny that the modern web stack (JSX syntax, type checking, async/await, etc.) is now heading towards something we built 10 years ago: http://opalang.org http://opalang.org I'm very glad that this is happening, the whole project got started when I was struggling to write PHP/JS in the early 2000s and the itch was getting worse and worse.
- pritambaral 8y agoHow close does Opa bring the database to the JS/HTML? From what little I read, it seems Opa is primarily tied to MongoDB, and CouchDB to a lesser level.
- hbbio 8y agoWe implemented a database abstraction layer called DbGen which generates the actual queries from a common ground. The key idea is to traverse a tree datastructure which will map to database entities, for instance: database my_db { int /basic/i float /basic/f string /basic/s stored /r intmap(stored) /imap } Kind of an ORM but without objects (Opa is purely functional) and without relations when using NoSQL. But DbGen has support for several types of database including PostgreSQL: See for instance this blog http://www.josetteorama.com/to-sql-from-nosql/ http://www.josetteorama.com/to-sql-from-nosql/
- tannhaeuser 8y agoI find it funny that JavaScript had (proposed) standardized first-party support for XML literals in the language (E4X), but nobody was using it because "XML sucks". Then shortly after it was scraped by Mozilla, React/JSX (requiring babel/node) became mainstream and praised for basically what E4X had done all the time. I guess to become mainstream these days, a lib needs to spin a drama around it such as "React vs Angular".
- okal 8y agoThis seems to happen quite a lot. I've heard similar criticism levelled at GraphQL (as a modern day SOAP). I wonder what the psychology behind this is. Perhaps they were ahead of their time, and top-down, not "community-driven"?
- rwmj 8y agoocsigen does this for OCaml: https://ocsigen.org/eliom/1.3.4/manual/html https://ocsigen.org/eliom/1.3.4/manual/html The syntax is fairly lightweight, just << followed by valid, type checked XHTML ended by >>. There are also antiquotations so you can use it as a templating language. For those of us generating XML from C I wrote a hairy set of C macros: https://github.com/libguestfs/libguestfs/blob/master/common/utils/libxml2-writer-macros.h https://github.com/libguestfs/libguestfs/blob/master/common/... so you can write code like this (which is not fully checked at compile time of course): https://github.com/libguestfs/libguestfs/blob/4aa712d551f9d4f5cda2b01d3fe5c672f531142b/lib/launch-libvirt.c#L1068 https://github.com/libguestfs/libguestfs/blob/4aa712d551f9d4...
- Drup 8y agoRegarding ocsigen, It's more appropriate to point to tyxml[1] and its syntax extension [2]! Note that tyxml goes quite further than Rust's typed-html: the nesting is significantly more flexible, type inference is still complete, and it will verify additional properties like "don't use <a> inside <a>". It can also be used conjointly with reactive and/or isomorphic programming. [1]: https://ocsigen.org/tyxml/ https://ocsigen.org/tyxml/ [2]: https://ocsigen.org/tyxml/4.3.0/manual/ppx https://ocsigen.org/tyxml/4.3.0/manual/ppx
- jonathanyc 8y agoAs an OCaml user, I do not see at first glance how any of your statements about where tyxml “goes quite further” are true, with the exception of completeness on the Rust end (but I am very dubious that there is completeness on the OCaml end—HTML is not as simple as you’d think). This makes me think that if you’d like to convince people who are not OCaml users to look at your library, you should provide examples of why these things are true and how they are useful. Otherwise, we just come off as smug FP weenies.
- Drup 8y agoAs the maintainer of a similar OCaml library[1], questions to the authors: - How compositional it is ? I have find that some of the HTML properties are very hard to verify in a compositional way, see https://github.com/ocsigen/tyxml/issues/175 https://github.com/ocsigen/tyxml/issues/175 - How do you handle the "subtyping" aspect that is intrinsic to HTML ? Or phrased in another way: what's your type encoding ? :) - I suppose you desugar to a set of combinators, but you don't really expose those. Why ? [1]: https://github.com/ocsigen/tyxml/ https://github.com/ocsigen/tyxml/
- twic 8y ago> I suppose you desugar to a set of combinators, but you don't really expose those. Why ? Why indeed. I personally find these "HTML in a programming language" tools pretty unappealing, because you have to give up all the normal tools of the programming language while using them [1]. Whereas you can usually write a really simple internal DSL to describe HTML that is as clear and concise as HTML, while being as convenient and powerful as the programming language. My quick and dirty efforts at this usually end up looking something like this: html( head( title("My First Page")), body( h1("Welcome"), p($("Made by "), a(href(), $("Tom"))), userIsOldSchool() ? p("Bring back HTML 3.2!") : div("Made with HTML 5."))) The typed-html crate has an object model like this underneath, but doesn't, AFAICS, expose it. [1] With the honourable exception of ScalaTags, which i still wouldn't touch with a bargepole
- Drup 8y agoYes, that's why in Tyxml, we have a set of combinators and an HTML-like syntax, and you can compose them arbitrarily with each other. This way, you can use the HTML syntax (and c/c internet snipets) but still enjoy all the cool functional idioms.
- Dowwie 8y agoAny word on when proc macro hygiene functionality will release to stable? This project and Maud both depend on nightly features such as this.
- steveklabnik 8y agoNo current timeline.
- dtolnay 8y agoThis library no longer requires proc_macro_hygiene. I added support for the stable compiler in https://github.com/bodil/typed-html/pull/1 https://github.com/bodil/typed-html/pull/1.
- steveklabnik 8y agoAhhh thank you a ton, this is awesome.
- pjungwir 8y agoI'm sad that SPAs have made us regress from haml back to plain html. Without closing tags, a whole class of bugs just goes away, and you can read your document structure at a glace. (Ease of reading is much more valuable than the saved typing in my opinion.) In my own React work I've found it nicer to use pug for templating, instead of jsx, and setting it up in webpack was just a couple lines. On team projects it's hard to get consensus for something like that though. I'd love to see a WASMable whitespace-sensitive html templating library for Rust. I bet it would even give the tokenizer a break so you don't have to quote the strings.
- err4nt 8y agoHTML syntax is a lot more flexible than a lot of people choose to write it. The following is a valid table in HTML: <table> <caption>Example Table <thead> <tr> <th>Col 1 <th>Col 2 <th>Col 3 <tbody> <tr> <td>One <td>Two <td>Three <tfoot> <tr> <td>Four <td>Five <td>Six </table> I'm currently drafting an article of HTML you never need to write, currently I'm covering: - some start tags are implied and never need to be written unless you're adding attributes - some end tags are implied and never need to be written - default attributes never need to be specified - element values often don't require quoting - no trailing slashes are required on void tags
- andraaspar 8y agoNo components??? It's no good then. Edit: Sure, having automatic HTML escape for values is good. I work with JSX every day, and I can't really imagine having it all in one huge chunk and no code reuse. Also, what about conditional hide/show and lists?
- RussianCow 8y agoThe very first example in the README shows how to render a list using `map`, duplicated here[0]. I don't know about conditional rendering; the README doesn't have any examples of that, and there doesn't appear to be any actual documentation. Edit: You could probably create a separate function with an `html!` return and call that from the first? If the return types line up, which they should, I don't see why you couldn't do that. [0]: https://github.com/bodil/typed-html#example-1 https://github.com/bodil/typed-html#example-1
- deleted 8y ago[deleted]
- equalunique 8y agoBodil Stokke has many other interesting projects. Check out her other repos too.