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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::{
token_stream::IntoIter as TokenIter, Literal, TokenTree,
};
use quote::quote;
use std::{
env,
fs::{create_dir_all, read, File, OpenOptions},
io::{BufRead, Read, Seek, SeekFrom, Write},
path::Path,
process::{Command, Stdio},
};
use syn::Token;
fn is(t: &TokenTree, ch: char) -> bool {
match t {
TokenTree::Punct(p) => p.as_char() == ch,
_ => false,
}
}
fn named_arg(mut input: TokenIter, name: &'static str) -> Option<proc_macro2::TokenStream> {
input.next().and_then(|t| match t {
TokenTree::Ident(ref i) if i.to_string() == name => {
input.next();
Some(
input
.take_while(|tok| match tok {
TokenTree::Punct(_) => false,
_ => true,
})
.collect(),
)
}
_ => None,
})
}
fn root_crate_path() -> std::path::PathBuf {
let path = env::var("CARGO_MANIFEST_DIR")
.expect("CARGO_MANIFEST_DIR is not set. Please use cargo to compile your crate.");
let path = Path::new(&path);
if path
.parent()
.expect("No parent dir")
.join("Cargo.toml")
.exists()
{
path.parent().expect("No parent dir").to_path_buf()
} else {
path.to_path_buf()
}
}
struct Config {
domain: String,
make_po: bool,
make_mo: bool,
langs: Vec<String>,
}
impl Config {
fn path() -> std::path::PathBuf {
Path::new(&env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| {
root_crate_path()
.join("target")
.join("debug")
.to_str()
.expect("Couldn't compute mo output dir")
.into()
}))
.join("gettext_macros")
.join(env::var("CARGO_PKG_NAME").expect("Please build with cargo"))
}
fn read() -> Config {
let config = read(Config::path())
.expect("Coudln't read domain, make sure to call init_i18n! before");
let mut lines = config.lines();
let domain = lines
.next()
.expect("Invalid config file. Make sure to call init_i18n! before this macro")
.expect("IO error while reading config");
let make_po: bool = lines
.next()
.expect("Invalid config file. Make sure to call init_i18n! before this macro")
.expect("IO error while reading config")
.parse()
.expect("Couldn't parse make_po");
let make_mo: bool = lines
.next()
.expect("Invalid config file. Make sure to call init_i18n! before this macro")
.expect("IO error while reading config")
.parse()
.expect("Couldn't parse make_mo");
Config {
domain,
make_po,
make_mo,
langs: lines
.map(|l| l.expect("IO error while reading config"))
.collect(),
}
}
fn write(&self) {
create_dir_all(Config::path().parent().unwrap()).expect("Couldn't create output dir");
let mut out = File::create(Config::path()).expect("Metadata file couldn't be open");
writeln!(out, "{}", self.domain).expect("Couldn't write domain");
writeln!(out, "{}", self.make_po).expect("Couldn't write po settings");
writeln!(out, "{}", self.make_mo).expect("Couldn't write mo settings");
for l in self.langs.clone() {
writeln!(out, "{}", l).expect("Couldn't write lang");
}
}
}
trait Message {
fn writable(&self) -> bool;
fn content(&self) -> String;
fn context(&self) -> Option<String>;
fn plural(&self) -> Option<String>;
fn write(&self) {
if !self.writable() {
return;
}
let config = Config::read();
let mut pot = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(format!("po/{0}/{0}.pot", config.domain))
.expect("Couldn't open .pot file");
let mut contents = String::new();
pot.read_to_string(&mut contents)
.expect("IO error while reading .pot file");
pot.seek(SeekFrom::End(0))
.expect("IO error while seeking .pot file to end");
let already_exists = self.content().is_empty()
|| contents.contains(&format!(
r#"{}msgid "{}""#,
self.context()
.clone()
.map(|c| format!(
r#"msgctxt "{}"
"#,
c))
.unwrap_or_default(),
self.content()
));
if already_exists {
return;
}
let prefix = if let Some(c) = self.context() {
format!(
r#"msgctxt "{}"
"#, c)
} else {
String::new()
};
if let Some(ref pl) = self.plural() {
pot.write_all(
&format!(
r#"
{}msgid "{}"
msgid_plural "{}"
msgstr[0] ""
"#,
prefix, self.content(), pl,
)
.into_bytes(),
)
.expect("Couldn't write message to .pot (plural)");
} else {
pot.write_all(
&format!(
r#"
{}msgid "{}"
msgstr ""
"#,
prefix, self.content(),
)
.into_bytes(),
)
.expect("Couldn't write message to .pot");
}
}
}
struct I18nCall {
catalog: syn::Expr,
context: Option<syn::LitStr>,
msg: syn::Expr,
plural: Option<syn::Expr>,
format_args: Option<syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>>,
}
mod kw {
syn::custom_keyword!(context);
}
impl syn::parse::Parse for I18nCall {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let catalog = input.parse()?;
input.parse::<Token![,]>()?;
let context = if input.parse::<kw::context>().is_ok() {
input.parse::<Token![=]>()?;
let ctx = input.parse().ok();
input.parse::<Token![,]>()?;
ctx
} else {
None
};
let msg = input.parse()?;
let plural = if input.parse::<Token![,]>().is_ok() {
input.parse().ok()
} else {
None
};
let format_args = if input.parse::<Token![;]>().is_ok() {
syn::punctuated::Punctuated::parse_terminated(input).ok()
} else {
None
};
Ok(I18nCall {
catalog,
context,
msg,
plural,
format_args,
})
}
}
fn extract_str_lit(expr: &syn::Expr) -> Option<String> {
match *expr {
syn::Expr::Lit(syn::ExprLit { lit : syn::Lit::Str(ref s), attrs: _ }) => Some(s.value()),
_ => None,
}
}
impl Message for I18nCall {
fn writable(&self) -> bool {
extract_str_lit(&self.msg).is_some()
}
fn content(&self) -> String {
extract_str_lit(&self.msg).unwrap_or_default().replace("\"", "\\\"").replace('\n', "\\n")
}
fn context(&self) -> Option<String> {
self.context.as_ref().map(|c| c.value())
}
fn plural(&self) -> Option<String> {
self.plural.as_ref().and_then(extract_str_lit)
}
}
struct TCall {
context: Option<syn::LitStr>,
msg: syn::LitStr,
plural: Option<syn::LitStr>,
}
impl syn::parse::Parse for TCall {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let context = if input.parse::<kw::context>().is_ok() {
input.parse::<Token![=]>()?;
let ctx = input.parse().ok();
input.parse::<Token![,]>()?;
ctx
} else {
None
};
let msg = input.parse()?;
let plural = if input.parse::<Token![,]>().is_ok() {
input.parse().ok()
} else {
None
};
Ok(TCall {
context,
msg,
plural,
})
}
}
impl Message for TCall {
fn writable(&self) -> bool {
true
}
fn content(&self) -> String {
self.msg.value().replace("\"", "\\\"").replace('\n', "\\n")
}
fn context(&self) -> Option<String> {
self.context.as_ref().map(|c| c.value())
}
fn plural(&self) -> Option<String> {
self.plural.as_ref().map(|p| p.value())
}
}
#[proc_macro]
pub fn t(input: TokenStream) -> TokenStream {
let message = syn::parse_macro_input!(input as TCall);
message.write();
let msg = message.content();
if let Some(pl) = message.plural.clone() {
quote!(
(#msg, #pl)
).into()
} else {
quote!(#msg).into()
}
}
#[proc_macro]
pub fn i18n(input: TokenStream) -> TokenStream {
let message = syn::parse_macro_input!(input as I18nCall);
message.write();
let gettext_call = message.catalog.clone();
let content = message.msg;
let gettext_call = if let Some(pl) = message.plural {
let count = message
.format_args
.clone()
.and_then(|args| args.first().cloned());
if let Some(c) = message.context {
quote!(
#gettext_call.npgettext(#c, #content, #pl, #count as u64)
)
} else {
quote!(
#gettext_call.ngettext(#content, #pl, #count as u64)
)
}
} else {
if let Some(c) = message.context {
quote!(
#gettext_call.pgettext(#c, #content)
)
} else {
quote!(
#gettext_call.gettext(#content)
)
}
};
let fargs: syn::punctuated::Punctuated<proc_macro2::TokenStream, Token![,]> = message.format_args.unwrap_or_default().into_iter().map(|x| {
quote!(::std::boxed::Box::new(#x))
}).collect();
let res = quote!({
use gettext_utils::try_format;
try_format(#gettext_call, &[#fargs]).expect("Error while formatting message")
});
res.into()
}
#[proc_macro]
pub fn init_i18n(input: TokenStream) -> TokenStream {
let input = proc_macro2::TokenStream::from(input);
let mut input = input.into_iter();
let domain = match input.next() {
Some(TokenTree::Literal(lit)) => lit.to_string().replace("\"", ""),
Some(_) => panic!("Domain should be a str"),
None => panic!("Expected a translation domain (for instance \"myapp\")"),
};
let (po, mo) = if let Some(n) = input.next() {
if is(&n, ',') {
let po = named_arg(input.clone(), "po");
if let Some(po) = po.clone() {
for _ in 0..(po.into_iter().count() + 3) {
input.next();
}
}
let mo = named_arg(input.clone(), "mo");
if let Some(mo) = mo.clone() {
for _ in 0..(mo.into_iter().count() + 3) {
input.next();
}
}
(po, mo)
} else {
(None, None)
}
} else {
(None, None)
};
let mut langs = vec![];
match input.next() {
Some(TokenTree::Ident(i)) => {
langs.push(i.to_string());
loop {
let next = input.next();
if next.is_none() || !is(&next.expect("Unreachable: next should be Some"), ',') {
break;
}
match input.next() {
Some(TokenTree::Ident(i)) => {
langs.push(i.to_string());
}
_ => panic!("Expected a language identifier"),
}
}
}
None => {}
_ => panic!("Expected a language identifier"),
}
let conf = Config {
domain: domain.clone(),
make_po: po.map(|x| x.to_string() == "true").unwrap_or(true),
make_mo: mo.map(|x| x.to_string() == "true").unwrap_or(true),
langs,
};
conf.write();
create_dir_all(format!("po/{}", domain)).expect("Couldn't create po dir");
let mut pot = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(format!("po/{0}/{0}.pot", domain))
.expect("Couldn't open .pot file");
pot.write_all(
&format!(
r#"msgid ""
msgstr ""
"Project-Id-Version: {}\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-06-15 16:33-0700\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
"#,
domain
)
.into_bytes(),
)
.expect("Couldn't init .pot file");
quote!().into()
}
#[proc_macro]
pub fn i18n_domain(_: TokenStream) -> TokenStream {
let domain = Config::read().domain;
let tok = TokenTree::Literal(Literal::string(&domain));
quote!(#tok).into()
}
#[proc_macro]
pub fn compile_i18n(_: TokenStream) -> TokenStream {
let conf = Config::read();
let domain = &conf.domain;
let pot_path = root_crate_path()
.join("po")
.join(domain.clone())
.join(format!("{}.pot", domain));
for lang in conf.langs {
let po_path = root_crate_path()
.join("po")
.join(domain.clone())
.join(format!("{}.po", lang.clone()));
if conf.make_po {
if po_path.exists() && po_path.is_file() {
Command::new("msgmerge")
.arg("-U")
.arg(po_path.to_str().expect("msgmerge: PO path error"))
.arg(pot_path.to_str().expect("msgmerge: POT path error"))
.stdout(Stdio::null())
.status()
.map(|s| {
if !s.success() {
panic!("Couldn't update PO file")
}
})
.expect("Couldn't update PO file. Make sure msgmerge is installed.");
} else {
println!("Creating {}", lang.clone());
Command::new("msginit")
.arg(format!(
"--input={}",
pot_path.to_str().expect("msginit: POT path error")
))
.arg(format!(
"--output-file={}",
po_path.to_str().expect("msginit: PO path error")
))
.arg("-l")
.arg(lang.clone())
.arg("--no-translator")
.stdout(Stdio::null())
.status()
.map(|s| {
if !s.success() {
panic!("Couldn't init PO file (gettext returned an error)")
}
})
.expect("Couldn't init PO file. Make sure msginit is installed.");
}
}
if conf.make_mo {
if !po_path.exists() {
panic!(
"{} doesn't exist. Make sure you didn't disabled po generation.",
po_path.display()
);
}
let mo_dir = Path::new(&env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| {
root_crate_path()
.join("target")
.join("debug")
.to_str()
.expect("Couldn't compute mo output dir")
.into()
}))
.join("gettext_macros")
.join(lang);
create_dir_all(mo_dir.clone()).expect("Couldn't create MO directory");
let mo_path = mo_dir.join(format!("{}.mo", domain));
Command::new("msgfmt")
.arg(format!(
"--output-file={}",
mo_path.to_str().expect("msgfmt: MO path error")
))
.arg(po_path)
.stdout(Stdio::null())
.status()
.map(|s| {
if !s.success() {
panic!("Couldn't compile translations (gettext returned an error)")
}
})
.expect("Couldn't compile translations. Make sure msgfmt is installed");
}
}
quote!().into()
}
#[proc_macro]
pub fn include_i18n(_: TokenStream) -> TokenStream {
let conf = Config::read();
let locales = conf.langs.clone().into_iter().map(|l| {
let lang = TokenTree::Literal(Literal::string(&l));
let path = Config::path().parent().unwrap().join(l).join(format!("{}.mo", conf.domain));
if !path.exists() {
panic!("{} doesn't exist. Make sure to call compile_i18n! before include_i18n!, and check that you didn't disabled mo compilation.", path.display());
}
let path = TokenTree::Literal(Literal::string(path.to_str().expect("Couldn't write MO file path")));
quote!{
(#lang, ::gettext::Catalog::parse(
&include_bytes!(
#path
)[..]
).expect("Error while loading catalog")),
}
}).collect::<proc_macro2::TokenStream>();
quote!({
vec![
#locales
]
}).into()
}