jqlang / jq

Command-line JSON processor
https://jqlang.github.io/jq/
Other
30.4k stars 1.57k forks source link

Opportunity: operator precedence table #2425

Open mikez opened 2 years ago

mikez commented 2 years ago

Does anyone here think operator precedence tables are helpful? I do. :) (Examples: Python and JavaScript.)

Is there already such a table for jq? If not, would it make sense to include it in the Wiki or elsewhere?

Example table (feel free to copy and change)

Here's a first draft based on Rosetta Code, parser.y, some simplifying assumptions, and guesses. Somebody who knows the codebase better than me, would be a good candidate to correct and extend this. :)

Order: from highest precedence (most binding) to lowest precedence (least binding).

Operator Description
x? Error Suppression
-x Negative
*, /, % Multiplication, Division, Modulo
+, - Addition, Subtraction
==, !=, <, >,<=, >= Comparisons
and Boolean AND
or Boolean OR
=, |=, +=, -=, *=, /=, %= Update-assignment
// Alternative
, Comma
| Pipe
label $variable Labels
try … catch … Try expression
if … then … end Conditional expression
foreach … as … (…) Loop expression
reduce … as … (…) Reduce expression
… as $variable Variable definition expression
def … ; … Function expression
wader commented 2 years ago

Good idea i think. Had a look at the wiki and found this https://github.com/stedolan/jq/wiki/jq-Language-Description#operators-priority, maybe it can be extended?

mikez commented 2 years ago

@wader Good find!

It seems @fadado added this in 2019 with the comment "Added operators priority table. Please, check the table validity, specially the new added operator ?//" and seemingly it hasn't been revised since. So maybe there was some uncertainty there too? :) Or maybe the concept of operator precedence is less applicable in the world of jq?

Some proposals:

  1. Find someone to verify the correctness of this.
  2. Change the section title to Operator Precedence for consistency with other languages and ease it being found.
  3. Add clickable links akin to the JavaScript table.
x-yuri commented 1 year ago

Is it asc or desc? I'd argue that usually it's desc. Anyway the direction should be specified.

emanuele6 commented 1 year ago

Order: from highest precedence (most binding) to lowest precedence (least binding).

x-yuri commented 1 year ago

Oh, indeed. I probably had the wiki in mind. Order is not specified there. And it's apparently from lowest to highest. Which I think is rather unusual. At least from my experience...

nicowilliams commented 1 year ago

Thank you for this.

Yes, the wiki is currently the best place for this work, and you can go ahead and edit it. Eventually we'd like to come up with a more formal specification of the language and put it up as a separate repository in the jqlang org.