Permalink
Browse files

add an ascii_only option to gen_code

This will make sure string literals have non-ascii characters
escaped as \u sequences, so that the resulting file can be
served up any old way without causing encoding problems.

Slightly changes the parameter conventions for gen_code (in
a backwards-compatible way). If you want to pass options
without pretty-printing, the second argument to gen_code
should have a beautify: false property. So to get ascii_only
mode, you pass {ascii_only: true, beautify: false}.
  • Loading branch information...
1 parent cc9e94d commit de80c97acc51e64eb984710a6bfd44878a3807a9 @marijnh marijnh committed Feb 28, 2011
Showing with 12 additions and 4 deletions.
  1. +12 −4 lib/process.js
View
@@ -1036,7 +1036,7 @@ var DOT_CALL_NO_PARENS = jsp.array_to_hash([
"regexp"
]);
-function make_string(str) {
+function make_string(str, ascii_only) {
var dq = 0, sq = 0;
str = str.replace(/[\\\b\f\n\r\t\x22\x27]/g, function(s){
switch (s) {
@@ -1051,15 +1051,23 @@ function make_string(str) {
}
return s;
});
+ if (ascii_only) {
+ str = str.replace(/[\u0080-\uffff]/g, function(ch) {
+ var code = ch.charCodeAt(0).toString(16);
+ while (code.length < 4) code = "0" + code;
+ return "\\u" + code;
+ });
+ }
if (dq > sq) {
return "'" + str.replace(/\x27/g, "\\'") + "'";
} else {
return '"' + str.replace(/\x22/g, '\\"') + '"';
}
};
-function gen_code(ast, beautify) {
- if (beautify) beautify = defaults(beautify, {
+function gen_code(ast, config) {
+ var ascii_only = config && config.ascii_only;
+ var beautify = config && config.beautify !== false && defaults(config, {
indent_start : 0,
indent_level : 4,
quote_keys : false,
@@ -1168,7 +1176,7 @@ function gen_code(ast, beautify) {
};
var generators = {
- "string": make_string,
+ "string": function(str) {return make_string(str, ascii_only);},
"num": make_num,
"name": make_name,
"toplevel": function(statements) {

0 comments on commit de80c97

Please sign in to comment.