Skip to content

Commit

Permalink
Leave spaces around operators that would be ambiguous without them
Browse files Browse the repository at this point in the history
Fixes #514
  • Loading branch information
bitwiseman committed Sep 26, 2014
1 parent 92ebeaf commit 809cf0f
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 22 deletions.
30 changes: 17 additions & 13 deletions js/lib/beautify.js
Original file line number Diff line number Diff line change
Expand Up @@ -390,11 +390,11 @@

function allow_wrap_or_preserved_newline(force_linewrap) {
force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;

if (output.just_added_newline()) {
return
}

if ((opt.preserve_newlines && current_token.wanted_newline) || force_linewrap) {
print_newline(false, true);
} else if (opt.wrap_line_length) {
Expand Down Expand Up @@ -1053,7 +1053,7 @@

var space_before = true;
var space_after = true;

if (in_array(current_token.text, ['--', '++', '!', '~']) || (in_array(current_token.text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || in_array(flags.last_text, Tokenizer.line_starters) || flags.last_text === ','))) {
// unary operators (and binary +/- pretending to be unary) special cases

Expand All @@ -1068,6 +1068,10 @@

if (last_type === 'TK_RESERVED' || last_type === 'TK_END_EXPR') {
space_before = true;
} else if (last_type === 'TK_OPERATOR') {
space_before =
(in_array(current_token.text, ['--', '-']) && in_array(flags.last_text, ['--', '-'])) ||
(in_array(current_token.text, ['++', '+']) && in_array(flags.last_text, ['++', '+']));
}

if ((flags.mode === MODE.BlockStatement || flags.mode === MODE.Statement) && (flags.last_text === '{' || flags.last_text === ';')) {
Expand Down Expand Up @@ -1213,7 +1217,7 @@

this.remove_indent = function(indent_string, preindent_string) {
var splice_index = 0;

// skip empty lines
if (line_items.length === 0) {
return;
Expand Down Expand Up @@ -1263,7 +1267,7 @@
lines.push(this.current_line);
return true;
}

return false;
}

Expand Down Expand Up @@ -1298,7 +1302,7 @@
this.add_space_before_token();
this.current_line.push(printable_token);
}

this.add_space_before_token = function() {
if (this.space_before_token && this.current_line.get_item_count()) {
var last_output = this.current_line.last();
Expand Down Expand Up @@ -1483,7 +1487,7 @@
var allow_decimal = true;
var allow_e = true;
var local_digit = digit;

if (c === '0' && parser_pos < input_length && /[Xx]/.test(input.charAt(parser_pos))) {
// switch to hex number, no decimal or e, just hex digits
allow_decimal = false;
Expand Down Expand Up @@ -1511,20 +1515,20 @@
if (allow_e && parser_pos < input_length && /[Ee]/.test(input.charAt(parser_pos))) {
c += input.charAt(parser_pos);
parser_pos += 1;

if (parser_pos < input_length && /[+-]/.test(input.charAt(parser_pos))) {
c += input.charAt(parser_pos);
parser_pos += 1;
}

allow_e = false;
allow_decimal = false;
}
}

return [c, 'TK_WORD'];
}

if (acorn.isIdentifierStart(input.charCodeAt(parser_pos-1))) {
if (parser_pos < input_length) {
while (acorn.isIdentifierChar(input.charCodeAt(parser_pos))) {
Expand All @@ -1544,7 +1548,7 @@
}
return [c, 'TK_RESERVED'];
}

return [c, 'TK_WORD'];
}

Expand Down Expand Up @@ -1634,7 +1638,7 @@
//
var in_char_class = false;
while (parser_pos < input_length &&
((esc || in_char_class || input.charAt(parser_pos) !== sep) &&
((esc || in_char_class || input.charAt(parser_pos) !== sep) &&
!acorn.newline.test(input.charAt(parser_pos)))) {
resulting_string += input.charAt(parser_pos);
if (!esc) {
Expand Down Expand Up @@ -1686,7 +1690,7 @@
// Template strings can travers lines without escape characters.
// Other strings cannot
while (parser_pos < input_length &&
(esc || (input.charAt(parser_pos) !== sep &&
(esc || (input.charAt(parser_pos) !== sep &&
(sep === '`' || !acorn.newline.test(input.charAt(parser_pos)))))) {
resulting_string += input.charAt(parser_pos);
if (esc) {
Expand Down
5 changes: 5 additions & 0 deletions js/test/beautify-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1697,6 +1697,11 @@ function run_beautifier_tests(test_obj, Urlencoded, js_beautify, html_beautify,
' name = b";');
// END tests for issue 505

// START tests for issue 514
// some operators require spaces to distinguish them
bt('var c = "_ACTION_TO_NATIVEAPI_" + ++g++ + +new Date;');
bt('var c = "_ACTION_TO_NATIVEAPI_" - --g-- - -new Date;');
// END tests for issue 514

bt('var a=1,b={bang:2},c=3;',
'var a = 1,\n b = {\n bang: 2\n },\n c = 3;');
Expand Down
22 changes: 13 additions & 9 deletions python/jsbeautifier/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,15 +326,15 @@ def blank_state(self, js_source_text = None):
self.preindent_string = ''
self.last_type = 'TK_START_BLOCK' # last token type
self.last_last_text = '' # pre-last token text

preindent_index = 0;
if not js_source_text == None and len(js_source_text) > 0:
while preindent_index < len(js_source_text) and \
js_source_text[preindent_index] in [' ', '\t'] :
self.preindent_string += js_source_text[preindent_index]
preindent_index += 1
js_source_text = js_source_text[preindent_index:]

self.output = Output(self.indent_string, self.preindent_string)

self.set_mode(MODE.BlockStatement)
Expand All @@ -349,7 +349,7 @@ def beautify(self, s, opts = None ):
raise(Exception('opts.brace_style must be "expand", "collapse" or "end-expand".'))

s = self.blank_state(s)

input = self.unpack(s, self.opts.eval_code)

self.handlers = {
Expand Down Expand Up @@ -999,6 +999,10 @@ def handle_operator(self, current_token):

if self.last_type == 'TK_RESERVED' or self.last_type == 'TK_END_EXPR':
space_before = True
elif self.last_type == 'TK_OPERATOR':
space_before = \
(current_token.text in ['--', '-'] and self.flags.last_text in ['--', '-']) or \
(current_token.text in ['++', '+'] and self.flags.last_text in ['++', '+'])

if self.flags.mode == MODE.BlockStatement and self.flags.last_text in ['{', ';']:
# { foo: --i }
Expand Down Expand Up @@ -1201,7 +1205,7 @@ def add_indent_string(self, level):
for i in range(level):
self.current_line.push(self.indent_string)
return True

return False

def add_token(self, printable_token):
Expand Down Expand Up @@ -1240,7 +1244,7 @@ def trim(self, eat_newlines = False):
self.current_line = self.lines[-1]
self.current_line.trim(self.indent_string, self.preindent_string)


def just_added_newline(self):
return self.current_line.get_item_count() == 0

Expand Down Expand Up @@ -1353,7 +1357,7 @@ def __tokenize_next(self):
allow_decimal = True
allow_e = True
local_digit = self.digit

if c == '0' and self.parser_pos < len(self.input) and re.match('[Xx]', self.input[self.parser_pos]):
# switch to hex number, no decimal or e, just hex digits
allow_decimal = False
Expand All @@ -1379,11 +1383,11 @@ def __tokenize_next(self):
if allow_e and self.parser_pos < len(self.input) and re.match('[Ee]', self.input[self.parser_pos]):
c += self.input[self.parser_pos]
self.parser_pos += 1

if self.parser_pos < len(self.input) and re.match('[+-]', self.input[self.parser_pos]):
c += self.input[self.parser_pos]
self.parser_pos += 1

allow_e = False
allow_decimal = False

Expand Down Expand Up @@ -1523,7 +1527,7 @@ def __tokenize_next(self):
else:
# handle string
while self.parser_pos < len(self.input) and \
(esc or (self.input[self.parser_pos] != sep and
(esc or (self.input[self.parser_pos] != sep and
(sep == '`' or not self.acorn.newline.match(self.input[self.parser_pos])))):
resulting_string += self.input[self.parser_pos]
if esc1 and esc1 >= esc2:
Expand Down
6 changes: 6 additions & 0 deletions python/jsbeautifier/tests/testjsbeautifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -1567,6 +1567,12 @@ def test_beautifier(self):
' name = b";');
# END tests for issue 505

# START tests for issue 514
# some operators require spaces to distinguish them
bt('var c = "_ACTION_TO_NATIVEAPI_" + ++g++ + +new Date;');
bt('var c = "_ACTION_TO_NATIVEAPI_" - --g-- - -new Date;');
# END tests for issue 514

bt('var a=1,b={bang:2},c=3;',
'var a = 1,\n b = {\n bang: 2\n },\n c = 3;');
bt('var a={bing:1},b=2,c=3;',
Expand Down

0 comments on commit 809cf0f

Please sign in to comment.