TomFrost / Jexl

Javascript Expression Language: Powerful context-based expression parser and evaluator
MIT License
561 stars 92 forks source link

null vs undefined handling #65

Open winstonewert opened 4 years ago

winstonewert commented 4 years ago

I'm looking at using Jexl for templates, and I want to distingush between two cases:

  1. The expression referred to an attribute that was not there
  2. The expression attempted to access an attribute on a null value

1) indicates that the expression was incorrectly given, and I'd like to report an error identifying the issue. 2) indicates that the piece of data is legitmately missing and not an issue with the template

The problem is that I get back undefined in either case, so I can't tell them apart.

What I'd like is: 1) returns undefined but 2) returns null. All that is neccessary for that to happen is to change the Identifier handler to return null when the from evaluates to null instead of returning undefined.

But, I get that perhaps not everyone wants the same semantics as me. But perhaps, given the customizability you already have in your language, you'd be amenable to a PR adding the option to customize the logic on this point?

Otherwise, it looks like I could get the functionality I want by a convoluted process of compiling the expression, rewriting the AST on the returned expression object, then evaluating that. But... that's really ugly. Or I could fork the whole project and modify that one piece, but I'd rather not if I don't have to.

TomFrost commented 4 years ago

Hi Winston! I apologize for responding so late on this. I've been chewing on it ever since you posted it, and I keep arriving at this making the most sense as a constructor option that allows the programmer to enable JS-native functionality on throwing when a property of undefined is accessed.

I'm not in love the idea of using null vs undefined, because ultimately either of those things could be legitimate values inside the context. If Jexl threw an exception, that would make the difference quite clear -- at the expense of the programmer needing to catch the error if they enable this mode.

What do you think?

winstonewert commented 4 years ago

Hi! Yes, getting an exception would be good, especially if that exception can contain more information. If my expression was "foo.bar[12].gates.yellow", it'd be nice if the exception could indicate where exactly the undefined was.

Bob-Coding commented 3 years ago

Hi Tom, I'm having the same issue when comparing "null == undefined" or "null != undefined", both return back as undefined and will be true when comparing equality, when making a custom operator with using typeof undefined or typeof null both return a string "undefined", but typeof null should actually return a string "object" here instead of "undefined". This should resolve the issue.