jq icon indicating copy to clipboard operation
jq copied to clipboard

Opportunity: operator precedence table

Open mikez opened this issue 3 years ago • 7 comments

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

mikez avatar Apr 10 '22 19:04 mikez

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?

wader avatar Apr 11 '22 10:04 wader

@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.

mikez avatar Apr 11 '22 14:04 mikez

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

x-yuri avatar Jul 13 '23 01:07 x-yuri

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

emanuele6 avatar Jul 13 '23 01:07 emanuele6

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...

x-yuri avatar Jul 13 '23 11:07 x-yuri

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.

nicowilliams avatar Jul 13 '23 15:07 nicowilliams