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
//! Specialization for JavaScript code generation. //! //! # Examples //! //! Basic example: //! //! ```rust //! #[feature(proc_macro_hygiene)] //! use genco::prelude::*; //! //! let toks: js::Tokens = quote! { //! function foo(v) { //! return v + ", World"; //! } //! //! foo("Hello"); //! }; //! //! assert_eq!( //! vec![ //! "function foo(v) {", //! " return v + \", World\";", //! "}", //! "", //! "foo(\"Hello\");", //! ], //! toks.to_file_vec().unwrap() //! ); //! ``` //! //! String quoting in JavaScript: //! //! ```rust //! #[feature(proc_macro_hygiene)] //! use genco::prelude::*; //! //! let toks: js::Tokens = quote!(#("hello \n world".quoted())); //! assert_eq!("\"hello \\n world\"", toks.to_string().unwrap()); //! ``` use crate::{Formatter, ItemStr, Lang, LangItem}; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{self, Write}; /// Tokens container specialization for Rust. pub type Tokens = crate::Tokens<JavaScript>; impl_type_basics!(JavaScript, TypeEnum<'a>, TypeTrait, TypeBox, TypeArgs, {Import, ImportDefault, Local}); /// Trait implemented by all types. pub trait TypeTrait: 'static + fmt::Debug + LangItem<JavaScript> { /// Coerce trait into an enum that can be used for type-specific operations. fn as_enum(&self) -> TypeEnum<'_>; } /// An imported item in JavaScript. /// /// Created using the [import()] function. #[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Import { /// Module of the imported name. module: ItemStr, /// Name imported. name: ItemStr, /// Alias of an imported item. /// /// If this is set, you'll get an import like: /// /// ```text /// import {<name> as <alias>} from <module> /// ``` alias: Option<ItemStr>, } impl Import { /// Alias of an imported item. /// /// If this is set, you'll get an import like: /// /// ```text /// import {<name> as <alias>} from <module> /// ``` /// /// # Examples /// /// ```rust /// #![feature(proc_macro_hygiene)] /// use genco::prelude::*; /// /// let a = js::import("collections", "vec"); /// let b = js::import("collections", "vec").alias("list"); /// /// let toks = quote! { /// #a /// #b /// }; /// /// assert_eq!( /// vec![ /// "import {vec, vec as list} from \"collections\";", /// "", /// "vec", /// "list", /// ], /// toks.to_file_vec().unwrap() /// ); /// ``` pub fn alias<N: Into<ItemStr>>(self, alias: N) -> Self { Self { alias: Some(alias.into()), ..self } } } impl TypeTrait for Import { fn as_enum(&self) -> TypeEnum<'_> { TypeEnum::Import(self) } } impl LangItem<JavaScript> for Import { fn format(&self, out: &mut Formatter, _: &mut (), _: usize) -> fmt::Result { if let Some(alias) = &self.alias { out.write_str(alias)?; } else { out.write_str(&self.name)?; } Ok(()) } fn as_import(&self) -> Option<&dyn TypeTrait> { Some(self) } } /// The default imported item. /// /// Created using the [import_default()] function. #[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct ImportDefault { /// Module of the imported name. module: ItemStr, /// Name imported. name: ItemStr, } impl TypeTrait for ImportDefault { fn as_enum(&self) -> TypeEnum<'_> { TypeEnum::ImportDefault(self) } } impl LangItem<JavaScript> for ImportDefault { fn format(&self, out: &mut Formatter, _: &mut (), _: usize) -> fmt::Result { out.write_str(&self.name) } fn as_import(&self) -> Option<&dyn TypeTrait> { Some(self) } } /// A local name. /// /// Created using the [local()] function. #[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Local { /// The local name. name: ItemStr, } impl TypeTrait for Local { fn as_enum(&self) -> TypeEnum<'_> { TypeEnum::Local(self) } } impl LangItem<JavaScript> for Local { fn format(&self, out: &mut Formatter, _: &mut (), _: usize) -> fmt::Result { out.write_str(&self.name) } fn as_import(&self) -> Option<&dyn TypeTrait> { None } } /// JavaScript language specialization. pub struct JavaScript(()); impl JavaScript { /// Translate imports into the necessary tokens. fn imports(tokens: &Tokens, output: &mut Tokens) { use crate as genco; use crate::prelude::*; let mut modules = BTreeMap::<&ItemStr, Module<'_>>::new(); for import in tokens.walk_imports() { match import.as_enum() { TypeEnum::Import(this) => { let module = modules.entry(&this.module).or_default(); module.set.insert(match &this.alias { None => ImportedElement::Plain(&this.name), Some(alias) => ImportedElement::Aliased(&this.name, alias), }); } TypeEnum::ImportDefault(this) => { let module = modules.entry(&this.module).or_default(); module.default_import = Some(&this.name); } _ => (), } } if modules.is_empty() { return; } for (name, module) in modules { let names = module.set.into_iter().map(|import| match import { ImportedElement::Plain(name) => quote!(#name), ImportedElement::Aliased(name, alias) => quote!(#name as #alias), }); output.push(); quote_in! { output => import #{ *tokens => { if let Some(default) = module.default_import { tokens.append(ItemStr::from(default)); tokens.append(","); tokens.spacing(); } }}{#names,*} from #(name.quoted()); }; } output.push_line(); #[derive(Default)] struct Module<'a> { default_import: Option<&'a ItemStr>, set: BTreeSet<ImportedElement<'a>>, } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] enum ImportedElement<'a> { Plain(&'a ItemStr), Aliased(&'a ItemStr, &'a ItemStr), } } } impl Lang for JavaScript { type Config = (); type Import = dyn TypeTrait; fn quote_string(out: &mut Formatter, input: &str) -> fmt::Result { out.write_char('"')?; for c in input.chars() { match c { '\t' => out.write_str("\\t")?, '\u{0007}' => out.write_str("\\b")?, '\n' => out.write_str("\\n")?, '\r' => out.write_str("\\r")?, '\u{0014}' => out.write_str("\\f")?, '\'' => out.write_str("\\'")?, '"' => out.write_str("\\\"")?, '\\' => out.write_str("\\\\")?, c => out.write_char(c)?, }; } out.write_char('"')?; Ok(()) } fn write_file( tokens: Tokens, out: &mut Formatter, config: &mut Self::Config, level: usize, ) -> fmt::Result { let mut toks = Tokens::new(); Self::imports(&tokens, &mut toks); toks.extend(tokens); toks.format(out, config, level) } } /// Import an element from a module /// /// # Examples /// /// ```rust /// #![feature(proc_macro_hygiene)] /// use genco::prelude::*; /// /// let a = js::import("collections", "vec"); /// let b = js::import("collections", "vec").alias("list"); /// /// let toks = quote! { /// #a /// #b /// }; /// /// assert_eq!( /// vec![ /// "import {vec, vec as list} from \"collections\";", /// "", /// "vec", /// "list", /// ], /// toks.to_file_vec().unwrap() /// ); /// ``` pub fn import<M, N>(module: M, name: N) -> Import where M: Into<ItemStr>, N: Into<ItemStr>, { Import { module: module.into(), name: name.into(), alias: None, } } /// Import the default element from the specified module. /// /// Note that the default element may only be aliased once, so multiple aliases /// will cause an error. /// /// # Examples /// /// ```rust /// #![feature(proc_macro_hygiene)] /// use genco::prelude::*; /// /// let a = js::import_default("collections", "defaultVec"); /// let b = js::import("collections", "vec"); /// let c = js::import("collections", "vec").alias("list"); /// /// let toks = quote! { /// #a /// #b /// #c /// }; /// /// assert_eq!( /// vec![ /// "import defaultVec, {vec, vec as list} from \"collections\";", /// "", /// "defaultVec", /// "vec", /// "list", /// ], /// toks.to_file_vec().unwrap() /// ); /// ``` pub fn import_default<M, N>(module: M, name: N) -> ImportDefault where M: Into<ItemStr>, N: Into<ItemStr>, { ImportDefault { module: module.into(), name: name.into(), } } /// Setup a local element. /// /// # Examples /// /// ```rust /// #![feature(proc_macro_hygiene)] /// use genco::prelude::*; /// /// let toks = quote!(#(js::local("MyType"))); /// assert_eq!(vec!["MyType"], toks.to_file_vec().unwrap()); /// ``` pub fn local<N>(name: N) -> Local where N: Into<ItemStr>, { Local { name: name.into() } }