OILS / doc / ref / chap-expr-lang.md View on Github | oils.pub

949 lines, 583 significant
1---
2title: YSH Expression Language (Oils Reference)
3all_docs_url: ..
4body_css_class: width40
5default_highlighter: oils-sh
6preserve_anchor_case: yes
7---
8
9<div class="doc-ref-header">
10
11[Oils Reference](index.html) &mdash;
12Chapter **YSH Expression Language**
13
14</div>
15
16This chapter describes the YSH expression language, which includes [Egg
17Expressions]($xref:eggex).
18
19<div id="dense-toc">
20</div>
21
22## Assignment
23
24### assign
25
26The `=` operator is used with assignment keywords:
27
28 var x = 42
29 setvar x = 43
30
31 const y = 'k'
32
33 setglobal z = 'g'
34
35### aug-assign
36
37The augmented assignment operators are:
38
39 += -= *= /= **= //= %=
40 &= |= ^= <<= >>=
41
42They are used with `setvar` and `setglobal`. For example:
43
44 setvar x += 2
45
46is the same as:
47
48 setvar x = x + 2
49
50Likewise, these are the same:
51
52 setglobal a[i] -= 1
53
54 setglobal a[i] = a[i] - 1
55
56## Literals
57
58### atom-literal
59
60YSH uses JavaScript-like spellings for these three "atoms":
61
62 null # type Null
63 true false # type Bool
64
65Note: to signify "no value", you may sometimes use an empty string `''`,
66instead of `null`.
67
68- Related: [Null][] type, [Bool][] type
69
70[Null]: chap-type-method.html#Null
71[Bool]: chap-type-method.html#Bool
72
73### int-literal
74
75There are several ways to write integers. Examples:
76
77 var decimal = 42
78 var big = 42_000
79
80 var hex = 0x0010_ffff
81
82 var octal = 0o755
83
84 var binary = 0b0001_0000
85
86- Related: [Int][] type
87
88[Int]: chap-type-method.html#Int
89
90### float-literal
91
92Floating point numbers looke like C, Python, or JavaScript:
93
94 var myfloat = 3.14
95
96 var f2 = -1.5e-100
97
98- Related: [Float][] type
99
100[Float]: chap-type-method.html#Float
101
102### char-literal
103
104The expression language has 3 kinds of backslash escapes, denoting bytes or
105UTF-8:
106
107 var backslash = \\
108 var quotes = \' ++ \" # same as u'\'' ++ '"'
109
110 var mu = \u{3bc} # same as u'\u{3bc}'
111
112 var nul = \y00 # same as b'\y00'
113
114Notice that this is the same syntax that's available within quoted J8 strings.
115That is, the expression `\\` denotes the same thing as `u'\\'`.
116
117- Related: [Str][] type
118
119[Str]: chap-type-method.html#Str
120
121### ysh-string
122
123YSH has single and double-quoted strings borrowed from Bourne shell, and
124C-style strings borrowed from J8 Notation.
125
126Double quoted strings respect `$` interpolation:
127
128 var dq = "hello $world and $(hostname)"
129
130You can add a `$` before the left quote to be explicit: `$"x is $x"` rather
131than `"x is $x"`.
132
133Single quoted strings may be raw:
134
135 var s = r'line\n' # raw string means \n is literal, NOT a newline
136
137Or *J8 strings* with backslash escapes:
138
139 var s = u'line\n \u{3bc}' # unicode string means \n is a newline
140 var s = b'line\n \u{3bc} \yff' # same thing, but also allows bytes
141
142Both `u''` and `b''` strings evaluate to the single `Str` type. The difference
143is that `b''` strings allow the `\yff` byte escape.
144
145#### Notes
146
147There's no way to express a single quote in raw strings. Use one of the other
148forms instead:
149
150 var sq = "single quote: ' "
151 var sq = u'single quote: \' '
152
153Sometimes you can omit the `r`, e.g. where there are no backslashes and thus no
154ambiguity:
155
156 echo 'foo'
157 echo r'foo' # same thing
158
159The `u''` and `b''` strings are called *J8 strings* because the syntax in YSH
160**code** matches JSON-like **data**.
161
162 var strU = u'mu = \u{3bc}' # J8 string with escapes
163 var strB = b'bytes \yff' # J8 string that can express byte strings
164
165More examples:
166
167 var myRaw = r'[a-z]\n' # raw strings can be used for regexes (not
168 # eggexes)
169
170### triple-quoted
171
172Triple-quoted string literals have leading whitespace stripped on each line.
173They come in the same variants:
174
175 var dq = """
176 hello $world and $(hostname)
177 no leading whitespace
178 """
179
180 var myRaw = r'''
181 raw string
182 no leading whitespace
183 '''
184
185 var strU = u'''
186 string that happens to be unicode \u{3bc}
187 no leading whitespace
188 '''
189
190 var strB = b'''
191 string that happens to be bytes \u{3bc} \yff
192 no leading whitespace
193 '''
194
195Again, you can omit the `r` prefix if there's no backslash, because it's not
196ambiguous:
197
198 var myRaw = '''
199 raw string
200 no leading whitespace
201 '''
202
203[Expr]: chap-type-method.html#Expr
204
205### list-literal
206
207Lists have a Python-like syntax:
208
209 var mylist = ['one', 'two', [42, 43]]
210
211And a shell-like syntax:
212
213 var list2 = :| one two |
214
215The shell-like syntax accepts the same syntax as a simple command:
216
217 ls $mystr @ARGV *.py {foo,bar}@example.com
218
219 # Rather than executing ls, evaluate words into a List
220 var cmd = :| ls $mystr @ARGV *.py {foo,bar}@example.com |
221
222- Related: [List][] type
223
224[List]: chap-type-method.html#List
225
226### dict-literal
227
228Dicts look like JavaScript.
229
230 var d = {
231 key1: 'value', # key can be unquoted if it looks like a var name
232 'key2': 42, # or quote it
233
234 ['key2' ++ suffix]: 43, # bracketed expression
235 }
236
237Omitting a value means that the corresponding key takes the value of a var of
238the same name:
239
240 ysh$ var x = 42
241 ysh$ var y = 43
242
243 ysh$ var d = {x, y} # values omitted
244 ysh$ = d
245 (Dict) {x: 42, y: 43}
246
247- Related: [Dict][] type
248
249[Dict]: chap-type-method.html#Dict
250
251### range
252
253A Range is a sequence of numbers that can be iterated over. The `..<` operator
254constructs half-open ranges.
255
256 for i in (0 ..< 3) {
257 echo $i
258 }
259 => 0
260 => 1
261 => 2
262
263The `..=` operator constructs closed ranges:
264
265 for i in (0 ..= 3) {
266 echo $i
267 }
268 => 0
269 => 1
270 => 2
271 => 3
272
273- Related: [Range][] type
274
275[Range]: chap-type-method.html#Range
276
277### block-expr
278
279In YSH expressions, we use `^()` to create a [Command][] object:
280
281 var myblock = ^(echo $PWD; ls *.txt)
282
283It's more common for [Command][] objects to be created with block arguments,
284which are not expressions:
285
286 cd /tmp {
287 echo $PWD
288 ls *.txt
289 }
290
291[Command]: chap-type-method.html#Command
292
293### expr-literal
294
295An expression literal is an object that holds an unevaluated expression:
296
297 var myexpr = ^[1 + 2*3]
298
299- Related: [Expr][] type
300
301[Expr]: chap-type-method.html#Expr
302
303### str-template
304
305String templates use the same syntax as double-quoted strings:
306
307 var mytemplate = ^"name = $name, age = $age"
308
309Related topics:
310
311- The type of a template is [Expr][].
312- [Str.replace](chap-type-method.html#replace)
313- [ysh-string](#ysh-string)
314
315### expr-sub
316
317Turn an expression into a string.
318
319 $ var x = $[3 * 2]
320 $ = x
321 (Str) '6'
322
323This is the same as [Word Language > expr-sub](chap-word-lang.html#expr-sub).
324
325### expr-splice
326
327Turns each element of a List into a string.
328
329 $ var mylist = [42, 43]
330 $ var x = @[mylist]
331 $ = x
332 (List) ['42', '43']
333
334This is the same as [Word Language > expr-splice](chap-word-lang.html#expr-splice).
335
336## Operators
337
338### op-precedence
339
340YSH operator precedence is identical to Python's operator precedence.
341
342New operators:
343
344- `++` has the same precedence as `+`
345- `->` and `=>` have the same precedence as `.`
346
347<!-- TODO: show grammar -->
348
349
350<h3 id="concat">concat <code>++</code></h3>
351
352The concatenation operator works on `Str` objects:
353
354 ysh$ var s = 'hello'
355 ysh$ var t = s ++ ' world'
356
357 ysh$ = t
358 (Str) "hello world"
359
360and `List` objects:
361
362 ysh$ var L = ['one', 'two']
363 ysh$ var M = L ++ ['three', '4']
364
365 ysh$ = M
366 (List) ["one", "two", "three", "4"]
367
368String interpolation can be nicer than `++`:
369
370 var t2 = "${s} world" # same as t
371
372Likewise, splicing lists can be nicer:
373
374 var M2 = :| @L three 4 | # same as M
375
376### ysh-equals
377
378YSH has strict equality:
379
380 a === b # Python-like, without type conversion
381 a !== b # negated
382
383And type converting equality:
384
385 '3' ~== 3 # True, type conversion
386
387The `~==` operator expects a string as the left operand.
388
389---
390
391Note that:
392
393- `3 === 3.0` is false because integers and floats are different types, and
394 there is no type conversion.
395- `3 ~== 3.0` is an error, because the left operand isn't a string.
396
397You may want to use explicit `int()` and `float()` to convert numbers, and then
398compare them.
399
400---
401
402Compare objects for identity with `is`:
403
404 ysh$ var d = {}
405 ysh$ var e = d
406
407 ysh$ = d is d
408 (Bool) true
409
410 ysh$ = d is {other: 'dict'}
411 (Bool) false
412
413To negate `is`, use `is not` (like Python:
414
415 ysh$ d is not {other: 'dict'}
416 (Bool) true
417
418### ysh-in
419
420The `in` operator tests if a key is in a dictionary:
421
422 var d = {k: 42}
423 if ('k' in d) {
424 echo yes
425 } # => yes
426
427Unlike Python, `in` doesn't work on `Str` and `List` instances. This because
428those operations take linear time rather than constant time (O(n) rather than
429O(1)).
430
431TODO: Use `includes() / contains()` methods instead.
432
433### ysh-compare
434
435The comparison operators apply to integers or floats:
436
437 4 < 4 # => false
438 4 <= 4 # => true
439
440 5.0 > 5.0 # => false
441 5.0 >= 5.0 # => true
442
443Example in context:
444
445 if (x < 0) {
446 echo 'x is negative'
447 }
448
449### ysh-logical
450
451The logical operators take boolean operands, and are spelled like Python:
452
453 not
454 and or
455
456Note that they are distinct from `! && ||`, which are part of the [command
457language](chap-cmd-lang.html).
458
459### ysh-arith
460
461YSH supports most of the arithmetic operators from Python. Notably, `/` and `%`
462differ from Python as [they round toward zero, not negative
463infinity](https://www.oilshell.org/blog/2024/03/release-0.21.0.html#integers-dont-do-whatever-python-or-c-does).
464
465Use `+ - *` for `Int` or `Float` addition, subtraction and multiplication. If
466any of the operands are `Float`s, then the output will also be a `Float`.
467
468Use `/` and `//` for `Float` division and `Int` division, respectively. `/`
469will _always_ result in a `Float`, meanwhile `//` will _always_ result in an
470`Int`.
471
472 = 1 / 2 # => (Float) 0.5
473 = 1 // 2 # => (Int) 0
474
475Use `%` to compute the _remainder_ of integer division. The left operand must
476be an `Int` and the right a _positive_ `Int`.
477
478 = 1 % 2 # -> (Int) 1
479 = -4 % 2 # -> (Int) 0
480
481Use `**` for exponentiation. The left operand must be an `Int` and the right a
482_positive_ `Int`.
483
484All arithmetic operators may coerce either of their operands from strings to a
485number, provided those strings are formatted as numbers.
486
487 = 10 + '1' # => (Int) 11
488
489Operators like `+ - * /` will coerce strings to _either_ an `Int` or `Float`.
490However, operators like `// ** %` and bit shifts will coerce strings _only_ to
491an `Int`.
492
493 = '1.14' + '2' # => (Float) 3.14
494 = '1.14' % '2' # Type Error: Left operand is a Str
495
496### ysh-unary
497
498YSH has unary `+` and `-` operators:
499
500 var x = '3.14'
501 = +x # => (Float) 3.14
502 = -x # => (Float) -3.14
503
504Like binary `+` and `-`, these operators coerce `Str` values with decimal
505digits to either an `Int` or `Float`.
506
507### ysh-bitwise
508
509Bitwise operators are like Python and C:
510
511 ~ # unary complement
512
513 & | ^ # binary and, or, xor
514
515 >> << # bit shift
516
517### ysh-ternary
518
519The ternary operator is borrowed from Python:
520
521 display = 'yes' if len(s) else 'empty'
522
523### ysh-index
524
525`Str` objects can be indexed by byte:
526
527 ysh$ var s = 'cat'
528 ysh$ = mystr[1]
529 (Str) 'a'
530
531 ysh$ = mystr[-1] # index from the end
532 (Str) 't'
533
534`List` objects:
535
536 ysh$ var mylist = [1, 2, 3]
537 ysh$ = mylist[2]
538 (Int) 3
539
540`Dict` objects are indexed by string key:
541
542 ysh$ var mydict = {'key': 42}
543 ysh$ = mydict['key']
544 (Int) 42
545
546### ysh-attr
547
548The `.` operator looks up values on either `Dict` or `Obj` instances.
549
550On dicts, it looks for the value associated with a key. That is, the
551expression `mydict.key` is short for `mydict['key']` (like JavaScript, but
552unlike Python.)
553
554---
555
556On objects, the expression `obj.x` looks for attributes, with a special rule
557for bound methods. The rules are:
558
5591. Search the properties of `obj` for a field named `x`.
560 - If it exists, return the value literally. (It can be of any type: `Func`, `Int`,
561 `Str`, ...)
5622. Search up the prototype chain for a field named `x`.
563 - If it exists, and is **not** a `Func`, return the value literally.
564 - If it **is** a `Func`, return **bound method**, which is an (object,
565 function) pair.
566
567Later, when the bound method is called, the object is passed as the first
568argument to the function (`self`), making it a method call. This is how a
569method has access to the object's properties.
570
571Example of first rule:
572
573 func Free(i) {
574 return (i + 1)
575 }
576 var module = Object(null, {Free})
577 echo $[module.Free(42)] # => 43
578
579Example of second rule:
580
581 func method(self, i) {
582 return (self.n + i)
583 }
584 var methods = Object(null, {method})
585 var obj = Object(methods, {n: 10})
586 echo $[obj.method(42)] # => 52
587
588### ysh-slice
589
590Slicing gives you a subsequence of a `Str` or `List`, as in Python.
591
592Negative indices are relative to the end.
593
594String example:
595
596 $ var s = 'spam eggs'
597 $ pp (s[1:-1])
598 (Str) "pam egg"
599
600 $ echo "x $[s[2:]]"
601 x am eggs
602
603List example:
604
605 $ var foods = ['ale', 'bean', 'corn']
606 $ pp (foods[-2:])
607 (List) ["bean","corn"]
608
609 $ write -- @[foods[:2]]
610 ale
611 bean
612
613### ysh-func-call
614
615A function call expression looks like Python:
616
617 ysh$ = f('s', 't', named=42)
618
619A semicolon `;` can be used after positional args and before named args, but
620isn't always required:
621
622 ysh$ = f('s', 't'; named=42)
623
624In these cases, the `;` is necessary:
625
626 ysh$ = f(...args; ...kwargs)
627
628 ysh$ = f(42, 43; ...kwargs)
629
630### thin-arrow
631
632The thin arrow is for mutating methods:
633
634 var mylist = ['bar']
635 call mylist->pop()
636
637 var mydict = {name: 'foo'}
638 call mydict->erase('name')
639
640On `Obj` instances, `obj->mymethod` looks up the prototype chain for a function
641named `M/mymethod`. The `M/` prefix signals mutation.
642
643Example:
644
645 func inc(self, n) {
646 setvar self.i += n
647 }
648 var Counter_methods = Object(null, {'M/inc': inc})
649 var c = Object(Counter_methods, {i: 0})
650
651 call c->inc(5)
652 echo $[c.i] # => 5
653
654It does **not** look in the properties of an object.
655
656### fat-arrow
657
658The fat arrow is for function chaining:
659
660 var x = myFunc() => list() => join()
661
662(Note: it also does method lookup like `s => startswith('y')`, but the `.`
663operator is usually preferred.)
664
665### match-ops
666
667YSH has four pattern matching operators: `~ !~ ~~ !~~`.
668
669Does string match an **eggex**?
670
671 var filename = 'x42.py'
672 if (filename ~ / d+ /) {
673 echo 'yes'
674 } # => yes
675
676This performs a **search**. To change that, add `%start` or `%end` anchors to
677the pattern:
678
679 if (filename ~ / %start d+ %end /) {
680 echo 'yes'
681 } # nothing printed
682
683---
684
685Does a string match a POSIX regular expression (ERE syntax)?
686
687 if (filename ~ '[[:digit:]]+') {
688 echo 'number'
689 }
690
691This is also a search, which can be anchored with `^` and `$`.
692
693---
694
695Negate the result with the `!~` operator:
696
697 if (filename !~ /space/ ) {
698 echo 'no space'
699 }
700
701 if (filename !~ '[[:space:]]' ) {
702 echo 'no space'
703 }
704
705---
706
707Does a string match a **glob**?
708
709 if (filename ~~ '*.py') {
710 echo 'Python'
711 } # => Python
712
713 if (filename !~~ '*.py') { # negation
714 echo 'not Python'
715 } # nothing printed
716
717Take care not to confuse glob patterns and regular expressions.
718
719For example, globs don't have `%start %end` or `^ $`. They are always
720"anchored".
721
722- Related doc: [YSH Regex API](../ysh-regex-api.html)
723
724## Eggex
725
726### re-literal
727
728An eggex literal looks like this:
729
730 / expression ; flags ; translation preference /
731
732The flags and translation preference are both optional.
733
734Examples:
735
736 var pat = / d+ / # => [[:digit:]]+
737
738You can specify flags passed to libc `regcomp()`:
739
740 var pat = / d+ ; reg_icase reg_newline /
741
742You can specify a translation preference after a second semi-colon:
743
744 var pat = / d+ ; ; ERE /
745
746Right now the translation preference does nothing. It could be used to
747translate eggex to PCRE or Python syntax.
748
749- Related doc: [Egg Expressions](../eggex.html)
750
751### re-primitive
752
753There are two kinds of eggex primitives.
754
755"Zero-width assertions" match a position rather than a character:
756
757 %start # translates to ^
758 %end # translates to $
759
760Literal characters appear within **single** quotes:
761
762 'oh *really*' # translates to regex-escaped string
763
764Double-quoted strings are **not** eggex primitives. Instead, you can use
765splicing of strings:
766
767 var dq = "hi $name"
768 var eggex = / @dq /
769
770
771### class-literal
772
773An eggex *character class literal* specifies a **set** of code points. It's
774enclosed in brackets:
775
776 var vowels = / [a e i o u] / # A set of 5 vowels
777
778A class literal can have individual code points:
779
780 [ a e i o u '?' '*' '+' ]
781
782It can also have ranges of code points, denoted with a hyphen:
783
784 [ a-f A-F 0-9 ]
785
786To reduce the number of quotes, you can write a set of characters as a string:
787
788 [ 'xyz' ] # any of 3 chars, NOT a sequence of 3 chars
789
790You can also use backslash escapes:
791
792 [ \\ \' \" \0 ]
793 [ \y7F \u{3bc} ] # a byte and a code point
794
795 [ \y01 - \y7F ] # range of bytes
796 [ \u{1} - \u{7F} ] # range of code points
797
798The `@` operator lets you refer to string variables:
799
800 var str_var = 'xyz'
801 [ @str_var ]
802
803Negation always uses `!`
804
805 ![ a-f A-F 'xyz' @str_var ]
806
807### re-chars
808
809Oils usually invokes `libc` in UTF-8 mode. In this mode, the regex engine
810can't match bytes like `0xFF`; it can only match code points.
811
812 var x = / [ \y7F \u{3bc} ] / # a byte and a code point
813
814Oils translates Eggex to POSIX extended regex (ERE) syntax. Here are some
815restrictions when translating bytes and code points to ERE:
816
817- The `NUL` byte `\y00` isn't allowed.
818 - Its synonym, code point zero `\u{0}`, also isn't allowed.
819- Bytes `\y80` to `\yFF` aren't allowed, because they're outside the ASCII
820 range.
821
822Reminders:
823
824- In the ASCII range, bytes and code points are the same
825 - That is, `\y01` to `\y7F` are synonyms for `\u{1}` to `\u{7F}`.
826- Outside of the ASCII range, they are different, so Eggex disallows them.
827 - For example, `\u{FF}` is a code point, and `\yFF` is a byte, but they are
828 not the same.
829
830### named-class
831
832Perl-like shortcuts for sets of characters:
833
834 [ dot ] # => .
835 [ digit ] # => [[:digit:]]
836 [ space ] # => [[:space:]]
837 [ word ] # => [[:alpha:]][[:digit:]]_
838
839Abbreviations:
840
841 [ d s w ] # Same as [ digit space word ]
842
843Valid POSIX classes:
844
845 alnum cntrl lower space
846 alpha digit print upper
847 blank graph punct xdigit
848
849Negated:
850
851 !digit !space !word
852 !d !s !w
853 !alnum # etc.
854
855### re-repeat
856
857Eggex repetition looks like POSIX syntax:
858
859 / 'a'? / # zero or one
860 / 'a'* / # zero or more
861 / 'a'+ / # one or more
862
863Counted repetitions:
864
865 / 'a'{3} / # exactly 3 repetitions
866 / 'a'{2,4} / # between 2 to 4 repetitions
867
868### re-compound
869
870Sequence expressions with a space:
871
872 / word digit digit / # Matches 3 characters in sequence
873 # Examples: a42, b51
874
875(Compare `/ [ word digit ] /`, which is a set matching 1 character.)
876
877Alternation with `|`:
878
879 / word | digit / # Matches 'a' OR '9', for example
880
881Grouping with parentheses:
882
883 / (word digit) | \\ / # Matches a9 or \
884
885### re-capture
886
887To retrieve a substring of a string that matches an Eggex, use a "capture
888group" like `<capture ...>`.
889
890Here's an eggex with a **positional** capture:
891
892 var pat = / 'hi ' <capture d+> / # access with _group(1)
893 # or Match.group(1)
894
895Captures can be **named**:
896
897 <capture d+ as month> # access with _group('month')
898 # or Match.group('month')
899
900Captures can also have a type **conversion func**:
901
902 <capture d+ : int> # _group(1) returns Int
903
904 <capture d+ as month: int> # _group('month') returns Int
905
906Related docs and help topics:
907
908- [YSH Regex API](../ysh-regex-api.html)
909- [`_group()`](chap-builtin-func.html#_group)
910- [`Match.group()`](chap-type-method.html#group)
911
912### re-splice
913
914To build an eggex out of smaller expressions, you can **splice** eggexes
915together:
916
917 var D = / [0-9][0-9] /
918 var time = / @D ':' @D / # [0-9][0-9]:[0-9][0-9]
919
920If the variable begins with a capital letter, you can omit `@`:
921
922 var ip = / D ':' D /
923
924You can also splice a string:
925
926 var greeting = 'hi'
927 var pat = / @greeting ' world' / # hi world
928
929Splicing is **not** string concatenation; it works on eggex subtrees.
930
931### re-flags
932
933Valid ERE flags, which are passed to libc's `regcomp()`:
934
935- `reg_icase` aka `i` - ignore case
936- `reg_newline` - 4 matching changes related to newlines
937
938See `man regcomp`.
939
940### re-multiline
941
942Multi-line eggexes aren't yet implemented. Splicing makes it less necessary:
943
944 var Name = / <capture [a-z]+ as name> /
945 var Num = / <capture d+ as num> /
946 var Space = / <capture s+ as space> /
947
948 # For variables named like CapWords, splicing @Name doesn't require @
949 var lexer = / Name | Num | Space /