berry icon indicating copy to clipboard operation
berry copied to clipboard

Standalone && and || trigger infinite loop

Open Lydxn opened this issue 2 years ago • 3 comments

Either of these two lines will trigger an infinite loop, where you would expect them to do nothing:

0 && 1
1 || 0

This behavior seems to magically resolve when the expression is assigned to a variable, e.g.

_ = 0 && 1

Lydxn avatar Oct 09 '23 23:10 Lydxn

I cannot reproduce:

> 0 && 1
false
> 1 || 0
true
> def f() 0 && 1 end
syntax_error: stdin:1: strict: expression without side effect detected
> def f() return 0 && 1 end
> f()
false

s-hadinger avatar Oct 10 '23 02:10 s-hadinger

These lines need to be parsed together. Try 0 && 1 1 || 0 in REPL.

skiars avatar Oct 10 '23 03:10 skiars

Ah yes indeed. What's interesting is when running in strict mode, it gets the following error (which is expected):

> 0 && 1 1 || 0
syntax_error: stdin:1: strict: expression without side effect detected

Now looking at the produced code:

> def f() 0 && 1 1 || 0 end
> import debug
> debug.codedump(f)
source 'stdin', function 'f':
; line 1
  0000  LDCONST	R0	K0
  0001  JMPF	R0	#0001
  0002  LDCONST	R0	K1
  0003  JMPT	R0	#0003
  0004  RET	0

There is definitely a problem at line 3.

s-hadinger avatar Oct 10 '23 11:10 s-hadinger

I'm closing since it's definitely a pathological example that never showed up in any code. Btw using strict mode raises an error to prevent such problem from arising.

s-hadinger avatar Nov 03 '25 20:11 s-hadinger