In Object.toSource implementation if property is not valid Java identifier, print it as 'escaped_property' so the property will read as proper Java string.

This commit is contained in:
igor%mir2.org 2003-12-04 15:47:03 +00:00
Родитель a18a81d561
Коммит 449bf5eadc
2 изменённых файлов: 45 добавлений и 11 удалений

Просмотреть файл

@ -423,20 +423,26 @@ public class ScriptRuntime {
/* Work around Microsoft Java VM bugs. */
private final static boolean MSJVM_BUG_WORKAROUNDS = true;
public static String escapeString(String s)
{
return escapeString(s, '"');
}
/**
* For escaping strings printed by object and array literals; not quite
* the same as 'escape.'
*/
public static String escapeString(String s) {
public static String escapeString(String s, char escapeQuote)
{
if (!(escapeQuote == '"' || escapeQuote == '\'')) Kit.codeBug();
StringBuffer sb = null;
for(int i = 0, L = s.length(); i != L; ++i) {
int c = s.charAt(i);
if (' ' <= c && c <= '~' && c != '"' && c != '\\') {
if (' ' <= c && c <= '~' && c != escapeQuote && c != '\\') {
// an ordinary print character (like C isprint()) and not "
// or \ . Note single quote ' is not escaped
// or \ .
if (sb != null) {
sb.append((char)c);
}
@ -456,7 +462,6 @@ public class ScriptRuntime {
case '\r': escape = 'r'; break;
case '\t': escape = 't'; break;
case 0xb: escape = 'v'; break; // Java lacks \v.
case '"': escape = '"'; break;
case ' ': escape = ' '; break;
case '\\': escape = '\\'; break;
}
@ -464,6 +469,9 @@ public class ScriptRuntime {
// an \escaped sort of character
sb.append('\\');
sb.append((char)escape);
} else if (c == escapeQuote) {
sb.append('\\');
sb.append(escapeQuote);
} else {
int hexSize;
if (c < 256) {
@ -483,10 +491,23 @@ public class ScriptRuntime {
}
}
}
return (sb == null) ? s : sb.toString();
}
static boolean isValidIdentifierName(String s)
{
int L = s.length();
if (L == 0)
return false;
if (!Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i != L; ++i) {
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
}
return true;
}
/**
* Convert the value to a string.
*

Просмотреть файл

@ -706,12 +706,25 @@ public abstract class ScriptableObject implements Scriptable, Serializable,
if (i > 0)
result.append(", ");
Object id = ids[i];
result.append(id);
Object value;
if (id instanceof Integer) {
int intId = ((Integer)id).intValue();
value = this.get(intId, this);
result.append(intId);
} else {
String strId = (String)id;
value = this.get(strId, this);
if (ScriptRuntime.isValidIdentifierName(strId)) {
result.append(strId);
} else {
result.append('\'');
result.append(
ScriptRuntime.escapeString(strId, '\''));
result.append('\'');
}
}
result.append(':');
Object p = (id instanceof String)
? this.get((String) id, this)
: this.get(((Integer) id).intValue(), this);
result.append(ScriptRuntime.uneval(cx, scope, p));
result.append(ScriptRuntime.uneval(cx, scope, value));
}
}
} finally {