@@ -1162,7 +1162,7 @@ impl CTLexer {
11621162/// pub const T_ID: u8 = 1;
11631163/// }
11641164/// ```
1165- pub fn ct_token_map < StorageT : Display > (
1165+ pub fn ct_token_map < StorageT : Display + ToTokens > (
11661166 mod_name : & str ,
11671167 token_map : impl Borrow < HashMap < String , StorageT > > ,
11681168 rename_map : Option < & HashMap < & str , & str > > ,
@@ -1172,34 +1172,37 @@ pub fn ct_token_map<StorageT: Display>(
11721172 // build of lrlex to be recompiled too.
11731173 let mut outs = String :: new ( ) ;
11741174 let timestamp = env ! ( "VERGEN_BUILD_TIMESTAMP" ) ;
1175- write ! (
1176- outs,
1177- "// lrlex build time: {}\n \n mod {} {{\n " ,
1178- quote!( #timestamp) ,
1179- mod_name
1180- )
1181- . ok ( ) ;
1182- outs. push_str (
1183- & token_map
1184- . borrow ( )
1185- . iter ( )
1186- . map ( |( k, v) | {
1187- let k = match rename_map {
1188- Some ( rmap) => * rmap. get ( k. as_str ( ) ) . unwrap_or ( & k. as_str ( ) ) ,
1189- _ => k,
1190- } ;
1191- format ! (
1192- " #[allow(dead_code)] pub const T_{}: {} = {};" ,
1193- k,
1194- type_name:: <StorageT >( ) ,
1195- v
1196- )
1197- } )
1198- . collect :: < Vec < _ > > ( )
1199- . join ( "\n " ) ,
1200- ) ;
1201- outs. push_str ( "\n }" ) ;
1202-
1175+ let mod_ident = format_ident ! ( "{}" , mod_name) ;
1176+ write ! ( outs, "// lrlex build time: {}\n \n " , quote!( #timestamp) , ) . ok ( ) ;
1177+ let tokens = & token_map
1178+ . borrow ( )
1179+ . iter ( )
1180+ . map ( |( k, id) | {
1181+ let name = match rename_map {
1182+ Some ( rmap) => * rmap. get ( k. as_str ( ) ) . unwrap_or ( & k. as_str ( ) ) ,
1183+ _ => k,
1184+ } ;
1185+ let tok_ident = format_ident ! ( "T_{}" , name. to_ascii_uppercase( ) ) ;
1186+ let storaget = str:: parse :: < TokenStream > ( type_name :: < StorageT > ( ) ) . unwrap ( ) ;
1187+ // Code gen for the constant token values.
1188+ quote ! {
1189+ pub const #tok_ident: #storaget = #id;
1190+ }
1191+ } )
1192+ . collect :: < Vec < _ > > ( ) ;
1193+ // Since the formatter doesn't preserve comments and we don't want to lose build time,
1194+ // just format the module contents.
1195+ let unformatted = quote ! {
1196+ mod #mod_ident {
1197+ #![ allow( dead_code) ]
1198+ #( #tokens) *
1199+ }
1200+ }
1201+ . to_string ( ) ;
1202+ let out_mod = syn:: parse_str ( & unformatted)
1203+ . map ( |syntax_tree| prettyplease:: unparse ( & syntax_tree) )
1204+ . unwrap_or ( unformatted) ;
1205+ outs. push_str ( & out_mod) ;
12031206 let mut outp = PathBuf :: from ( var ( "OUT_DIR" ) ?) ;
12041207 outp. push ( mod_name) ;
12051208 outp. set_extension ( "rs" ) ;
0 commit comments