| 1 | ---
|
| 2 | title: YSH Expression Language (Oils Reference)
|
| 3 | all_docs_url: ..
|
| 4 | body_css_class: width40
|
| 5 | default_highlighter: oils-sh
|
| 6 | preserve_anchor_case: yes
|
| 7 | ---
|
| 8 |
|
| 9 | <div class="doc-ref-header">
|
| 10 |
|
| 11 | [Oils Reference](index.html) —
|
| 12 | Chapter **YSH Expression Language**
|
| 13 |
|
| 14 | </div>
|
| 15 |
|
| 16 | This chapter describes the YSH expression language, which includes [Egg
|
| 17 | Expressions]($xref:eggex).
|
| 18 |
|
| 19 | <div id="dense-toc">
|
| 20 | </div>
|
| 21 |
|
| 22 | ## Assignment
|
| 23 |
|
| 24 | ### assign
|
| 25 |
|
| 26 | The `=` 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 |
|
| 37 | The augmented assignment operators are:
|
| 38 |
|
| 39 | += -= *= /= **= //= %=
|
| 40 | &= |= ^= <<= >>=
|
| 41 |
|
| 42 | They are used with `setvar` and `setglobal`. For example:
|
| 43 |
|
| 44 | setvar x += 2
|
| 45 |
|
| 46 | is the same as:
|
| 47 |
|
| 48 | setvar x = x + 2
|
| 49 |
|
| 50 | Likewise, 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 |
|
| 60 | YSH uses JavaScript-like spellings for these three "atoms":
|
| 61 |
|
| 62 | null # type Null
|
| 63 | true false # type Bool
|
| 64 |
|
| 65 | Note: to signify "no value", you may sometimes use an empty string `''`,
|
| 66 | instead 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 |
|
| 75 | There 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 |
|
| 92 | Floating 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 |
|
| 104 | The expression language has 3 kinds of backslash escapes, denoting bytes or
|
| 105 | UTF-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 |
|
| 114 | Notice that this is the same syntax that's available within quoted J8 strings.
|
| 115 | That 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 |
|
| 123 | YSH has single and double-quoted strings borrowed from Bourne shell, and
|
| 124 | C-style strings borrowed from J8 Notation.
|
| 125 |
|
| 126 | Double quoted strings respect `$` interpolation:
|
| 127 |
|
| 128 | var dq = "hello $world and $(hostname)"
|
| 129 |
|
| 130 | You can add a `$` before the left quote to be explicit: `$"x is $x"` rather
|
| 131 | than `"x is $x"`.
|
| 132 |
|
| 133 | Single quoted strings may be raw:
|
| 134 |
|
| 135 | var s = r'line\n' # raw string means \n is literal, NOT a newline
|
| 136 |
|
| 137 | Or *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 |
|
| 142 | Both `u''` and `b''` strings evaluate to the single `Str` type. The difference
|
| 143 | is that `b''` strings allow the `\yff` byte escape.
|
| 144 |
|
| 145 | #### Notes
|
| 146 |
|
| 147 | There's no way to express a single quote in raw strings. Use one of the other
|
| 148 | forms instead:
|
| 149 |
|
| 150 | var sq = "single quote: ' "
|
| 151 | var sq = u'single quote: \' '
|
| 152 |
|
| 153 | Sometimes you can omit the `r`, e.g. where there are no backslashes and thus no
|
| 154 | ambiguity:
|
| 155 |
|
| 156 | echo 'foo'
|
| 157 | echo r'foo' # same thing
|
| 158 |
|
| 159 | The `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 |
|
| 165 | More examples:
|
| 166 |
|
| 167 | var myRaw = r'[a-z]\n' # raw strings can be used for regexes (not
|
| 168 | # eggexes)
|
| 169 |
|
| 170 | ### triple-quoted
|
| 171 |
|
| 172 | Triple-quoted string literals have leading whitespace stripped on each line.
|
| 173 | They 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 |
|
| 195 | Again, you can omit the `r` prefix if there's no backslash, because it's not
|
| 196 | ambiguous:
|
| 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 |
|
| 207 | Lists have a Python-like syntax:
|
| 208 |
|
| 209 | var mylist = ['one', 'two', [42, 43]]
|
| 210 |
|
| 211 | And a shell-like syntax:
|
| 212 |
|
| 213 | var list2 = :| one two |
|
| 214 |
|
| 215 | The 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 |
|
| 228 | Dicts 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 |
|
| 237 | Omitting a value means that the corresponding key takes the value of a var of
|
| 238 | the 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 |
|
| 253 | A Range is a sequence of numbers that can be iterated over. The `..<` operator
|
| 254 | constructs half-open ranges.
|
| 255 |
|
| 256 | for i in (0 ..< 3) {
|
| 257 | echo $i
|
| 258 | }
|
| 259 | => 0
|
| 260 | => 1
|
| 261 | => 2
|
| 262 |
|
| 263 | The `..=` 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 |
|
| 279 | In YSH expressions, we use `^()` to create a [Command][] object:
|
| 280 |
|
| 281 | var myblock = ^(echo $PWD; ls *.txt)
|
| 282 |
|
| 283 | It's more common for [Command][] objects to be created with block arguments,
|
| 284 | which 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 |
|
| 295 | An 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 |
|
| 305 | String templates use the same syntax as double-quoted strings:
|
| 306 |
|
| 307 | var mytemplate = ^"name = $name, age = $age"
|
| 308 |
|
| 309 | Related 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 |
|
| 317 | Turn an expression into a string.
|
| 318 |
|
| 319 | $ var x = $[3 * 2]
|
| 320 | $ = x
|
| 321 | (Str) '6'
|
| 322 |
|
| 323 | This is the same as [Word Language > expr-sub](chap-word-lang.html#expr-sub).
|
| 324 |
|
| 325 | ### expr-splice
|
| 326 |
|
| 327 | Turns 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 |
|
| 334 | This is the same as [Word Language > expr-splice](chap-word-lang.html#expr-splice).
|
| 335 |
|
| 336 | ## Operators
|
| 337 |
|
| 338 | ### op-precedence
|
| 339 |
|
| 340 | YSH operator precedence is identical to Python's operator precedence.
|
| 341 |
|
| 342 | New 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 |
|
| 352 | The 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 |
|
| 360 | and `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 |
|
| 368 | String interpolation can be nicer than `++`:
|
| 369 |
|
| 370 | var t2 = "${s} world" # same as t
|
| 371 |
|
| 372 | Likewise, splicing lists can be nicer:
|
| 373 |
|
| 374 | var M2 = :| @L three 4 | # same as M
|
| 375 |
|
| 376 | ### ysh-equals
|
| 377 |
|
| 378 | YSH has strict equality:
|
| 379 |
|
| 380 | a === b # Python-like, without type conversion
|
| 381 | a !== b # negated
|
| 382 |
|
| 383 | And type converting equality:
|
| 384 |
|
| 385 | '3' ~== 3 # True, type conversion
|
| 386 |
|
| 387 | The `~==` operator expects a string as the left operand.
|
| 388 |
|
| 389 | ---
|
| 390 |
|
| 391 | Note 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 |
|
| 397 | You may want to use explicit `int()` and `float()` to convert numbers, and then
|
| 398 | compare them.
|
| 399 |
|
| 400 | ---
|
| 401 |
|
| 402 | Compare 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 |
|
| 413 | To negate `is`, use `is not` (like Python:
|
| 414 |
|
| 415 | ysh$ d is not {other: 'dict'}
|
| 416 | (Bool) true
|
| 417 |
|
| 418 | ### ysh-in
|
| 419 |
|
| 420 | The `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 |
|
| 427 | Unlike Python, `in` doesn't work on `Str` and `List` instances. This because
|
| 428 | those operations take linear time rather than constant time (O(n) rather than
|
| 429 | O(1)).
|
| 430 |
|
| 431 | TODO: Use `includes() / contains()` methods instead.
|
| 432 |
|
| 433 | ### ysh-compare
|
| 434 |
|
| 435 | The 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 |
|
| 443 | Example in context:
|
| 444 |
|
| 445 | if (x < 0) {
|
| 446 | echo 'x is negative'
|
| 447 | }
|
| 448 |
|
| 449 | ### ysh-logical
|
| 450 |
|
| 451 | The logical operators take boolean operands, and are spelled like Python:
|
| 452 |
|
| 453 | not
|
| 454 | and or
|
| 455 |
|
| 456 | Note that they are distinct from `! && ||`, which are part of the [command
|
| 457 | language](chap-cmd-lang.html).
|
| 458 |
|
| 459 | ### ysh-arith
|
| 460 |
|
| 461 | YSH supports most of the arithmetic operators from Python. Notably, `/` and `%`
|
| 462 | differ from Python as [they round toward zero, not negative
|
| 463 | infinity](https://www.oilshell.org/blog/2024/03/release-0.21.0.html#integers-dont-do-whatever-python-or-c-does).
|
| 464 |
|
| 465 | Use `+ - *` for `Int` or `Float` addition, subtraction and multiplication. If
|
| 466 | any of the operands are `Float`s, then the output will also be a `Float`.
|
| 467 |
|
| 468 | Use `/` and `//` for `Float` division and `Int` division, respectively. `/`
|
| 469 | will _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 |
|
| 475 | Use `%` to compute the _remainder_ of integer division. The left operand must
|
| 476 | be an `Int` and the right a _positive_ `Int`.
|
| 477 |
|
| 478 | = 1 % 2 # -> (Int) 1
|
| 479 | = -4 % 2 # -> (Int) 0
|
| 480 |
|
| 481 | Use `**` for exponentiation. The left operand must be an `Int` and the right a
|
| 482 | _positive_ `Int`.
|
| 483 |
|
| 484 | All arithmetic operators may coerce either of their operands from strings to a
|
| 485 | number, provided those strings are formatted as numbers.
|
| 486 |
|
| 487 | = 10 + '1' # => (Int) 11
|
| 488 |
|
| 489 | Operators like `+ - * /` will coerce strings to _either_ an `Int` or `Float`.
|
| 490 | However, operators like `// ** %` and bit shifts will coerce strings _only_ to
|
| 491 | an `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 |
|
| 498 | YSH has unary `+` and `-` operators:
|
| 499 |
|
| 500 | var x = '3.14'
|
| 501 | = +x # => (Float) 3.14
|
| 502 | = -x # => (Float) -3.14
|
| 503 |
|
| 504 | Like binary `+` and `-`, these operators coerce `Str` values with decimal
|
| 505 | digits to either an `Int` or `Float`.
|
| 506 |
|
| 507 | ### ysh-bitwise
|
| 508 |
|
| 509 | Bitwise 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 |
|
| 519 | The 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 |
|
| 548 | The `.` operator looks up values on either `Dict` or `Obj` instances.
|
| 549 |
|
| 550 | On dicts, it looks for the value associated with a key. That is, the
|
| 551 | expression `mydict.key` is short for `mydict['key']` (like JavaScript, but
|
| 552 | unlike Python.)
|
| 553 |
|
| 554 | ---
|
| 555 |
|
| 556 | On objects, the expression `obj.x` looks for attributes, with a special rule
|
| 557 | for bound methods. The rules are:
|
| 558 |
|
| 559 | 1. 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`, ...)
|
| 562 | 2. 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 |
|
| 567 | Later, when the bound method is called, the object is passed as the first
|
| 568 | argument to the function (`self`), making it a method call. This is how a
|
| 569 | method has access to the object's properties.
|
| 570 |
|
| 571 | Example 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 |
|
| 579 | Example 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 |
|
| 590 | Slicing gives you a subsequence of a `Str` or `List`, as in Python.
|
| 591 |
|
| 592 | Negative indices are relative to the end.
|
| 593 |
|
| 594 | String 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 |
|
| 603 | List 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 |
|
| 615 | A function call expression looks like Python:
|
| 616 |
|
| 617 | ysh$ = f('s', 't', named=42)
|
| 618 |
|
| 619 | A semicolon `;` can be used after positional args and before named args, but
|
| 620 | isn't always required:
|
| 621 |
|
| 622 | ysh$ = f('s', 't'; named=42)
|
| 623 |
|
| 624 | In these cases, the `;` is necessary:
|
| 625 |
|
| 626 | ysh$ = f(...args; ...kwargs)
|
| 627 |
|
| 628 | ysh$ = f(42, 43; ...kwargs)
|
| 629 |
|
| 630 | ### thin-arrow
|
| 631 |
|
| 632 | The 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 |
|
| 640 | On `Obj` instances, `obj->mymethod` looks up the prototype chain for a function
|
| 641 | named `M/mymethod`. The `M/` prefix signals mutation.
|
| 642 |
|
| 643 | Example:
|
| 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 |
|
| 654 | It does **not** look in the properties of an object.
|
| 655 |
|
| 656 | ### fat-arrow
|
| 657 |
|
| 658 | The 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 `.`
|
| 663 | operator is usually preferred.)
|
| 664 |
|
| 665 | ### match-ops
|
| 666 |
|
| 667 | YSH has four pattern matching operators: `~ !~ ~~ !~~`.
|
| 668 |
|
| 669 | Does string match an **eggex**?
|
| 670 |
|
| 671 | var filename = 'x42.py'
|
| 672 | if (filename ~ / d+ /) {
|
| 673 | echo 'yes'
|
| 674 | } # => yes
|
| 675 |
|
| 676 | This performs a **search**. To change that, add `%start` or `%end` anchors to
|
| 677 | the pattern:
|
| 678 |
|
| 679 | if (filename ~ / %start d+ %end /) {
|
| 680 | echo 'yes'
|
| 681 | } # nothing printed
|
| 682 |
|
| 683 | ---
|
| 684 |
|
| 685 | Does a string match a POSIX regular expression (ERE syntax)?
|
| 686 |
|
| 687 | if (filename ~ '[[:digit:]]+') {
|
| 688 | echo 'number'
|
| 689 | }
|
| 690 |
|
| 691 | This is also a search, which can be anchored with `^` and `$`.
|
| 692 |
|
| 693 | ---
|
| 694 |
|
| 695 | Negate 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 |
|
| 707 | Does 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 |
|
| 717 | Take care not to confuse glob patterns and regular expressions.
|
| 718 |
|
| 719 | For 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 |
|
| 728 | An eggex literal looks like this:
|
| 729 |
|
| 730 | / expression ; flags ; translation preference /
|
| 731 |
|
| 732 | The flags and translation preference are both optional.
|
| 733 |
|
| 734 | Examples:
|
| 735 |
|
| 736 | var pat = / d+ / # => [[:digit:]]+
|
| 737 |
|
| 738 | You can specify flags passed to libc `regcomp()`:
|
| 739 |
|
| 740 | var pat = / d+ ; reg_icase reg_newline /
|
| 741 |
|
| 742 | You can specify a translation preference after a second semi-colon:
|
| 743 |
|
| 744 | var pat = / d+ ; ; ERE /
|
| 745 |
|
| 746 | Right now the translation preference does nothing. It could be used to
|
| 747 | translate eggex to PCRE or Python syntax.
|
| 748 |
|
| 749 | - Related doc: [Egg Expressions](../eggex.html)
|
| 750 |
|
| 751 | ### re-primitive
|
| 752 |
|
| 753 | There 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 |
|
| 760 | Literal characters appear within **single** quotes:
|
| 761 |
|
| 762 | 'oh *really*' # translates to regex-escaped string
|
| 763 |
|
| 764 | Double-quoted strings are **not** eggex primitives. Instead, you can use
|
| 765 | splicing of strings:
|
| 766 |
|
| 767 | var dq = "hi $name"
|
| 768 | var eggex = / @dq /
|
| 769 |
|
| 770 |
|
| 771 | ### class-literal
|
| 772 |
|
| 773 | An eggex *character class literal* specifies a **set** of code points. It's
|
| 774 | enclosed in brackets:
|
| 775 |
|
| 776 | var vowels = / [a e i o u] / # A set of 5 vowels
|
| 777 |
|
| 778 | A class literal can have individual code points:
|
| 779 |
|
| 780 | [ a e i o u '?' '*' '+' ]
|
| 781 |
|
| 782 | It can also have ranges of code points, denoted with a hyphen:
|
| 783 |
|
| 784 | [ a-f A-F 0-9 ]
|
| 785 |
|
| 786 | To 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 |
|
| 790 | You 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 |
|
| 798 | The `@` operator lets you refer to string variables:
|
| 799 |
|
| 800 | var str_var = 'xyz'
|
| 801 | [ @str_var ]
|
| 802 |
|
| 803 | Negation always uses `!`
|
| 804 |
|
| 805 | ![ a-f A-F 'xyz' @str_var ]
|
| 806 |
|
| 807 | ### re-chars
|
| 808 |
|
| 809 | Oils usually invokes `libc` in UTF-8 mode. In this mode, the regex engine
|
| 810 | can'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 |
|
| 814 | Oils translates Eggex to POSIX extended regex (ERE) syntax. Here are some
|
| 815 | restrictions 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 |
|
| 822 | Reminders:
|
| 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 |
|
| 832 | Perl-like shortcuts for sets of characters:
|
| 833 |
|
| 834 | [ dot ] # => .
|
| 835 | [ digit ] # => [[:digit:]]
|
| 836 | [ space ] # => [[:space:]]
|
| 837 | [ word ] # => [[:alpha:]][[:digit:]]_
|
| 838 |
|
| 839 | Abbreviations:
|
| 840 |
|
| 841 | [ d s w ] # Same as [ digit space word ]
|
| 842 |
|
| 843 | Valid POSIX classes:
|
| 844 |
|
| 845 | alnum cntrl lower space
|
| 846 | alpha digit print upper
|
| 847 | blank graph punct xdigit
|
| 848 |
|
| 849 | Negated:
|
| 850 |
|
| 851 | !digit !space !word
|
| 852 | !d !s !w
|
| 853 | !alnum # etc.
|
| 854 |
|
| 855 | ### re-repeat
|
| 856 |
|
| 857 | Eggex repetition looks like POSIX syntax:
|
| 858 |
|
| 859 | / 'a'? / # zero or one
|
| 860 | / 'a'* / # zero or more
|
| 861 | / 'a'+ / # one or more
|
| 862 |
|
| 863 | Counted repetitions:
|
| 864 |
|
| 865 | / 'a'{3} / # exactly 3 repetitions
|
| 866 | / 'a'{2,4} / # between 2 to 4 repetitions
|
| 867 |
|
| 868 | ### re-compound
|
| 869 |
|
| 870 | Sequence 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 |
|
| 877 | Alternation with `|`:
|
| 878 |
|
| 879 | / word | digit / # Matches 'a' OR '9', for example
|
| 880 |
|
| 881 | Grouping with parentheses:
|
| 882 |
|
| 883 | / (word digit) | \\ / # Matches a9 or \
|
| 884 |
|
| 885 | ### re-capture
|
| 886 |
|
| 887 | To retrieve a substring of a string that matches an Eggex, use a "capture
|
| 888 | group" like `<capture ...>`.
|
| 889 |
|
| 890 | Here's an eggex with a **positional** capture:
|
| 891 |
|
| 892 | var pat = / 'hi ' <capture d+> / # access with _group(1)
|
| 893 | # or Match.group(1)
|
| 894 |
|
| 895 | Captures can be **named**:
|
| 896 |
|
| 897 | <capture d+ as month> # access with _group('month')
|
| 898 | # or Match.group('month')
|
| 899 |
|
| 900 | Captures 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 |
|
| 906 | Related 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 |
|
| 914 | To build an eggex out of smaller expressions, you can **splice** eggexes
|
| 915 | together:
|
| 916 |
|
| 917 | var D = / [0-9][0-9] /
|
| 918 | var time = / @D ':' @D / # [0-9][0-9]:[0-9][0-9]
|
| 919 |
|
| 920 | If the variable begins with a capital letter, you can omit `@`:
|
| 921 |
|
| 922 | var ip = / D ':' D /
|
| 923 |
|
| 924 | You can also splice a string:
|
| 925 |
|
| 926 | var greeting = 'hi'
|
| 927 | var pat = / @greeting ' world' / # hi world
|
| 928 |
|
| 929 | Splicing is **not** string concatenation; it works on eggex subtrees.
|
| 930 |
|
| 931 | ### re-flags
|
| 932 |
|
| 933 | Valid 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 |
|
| 938 | See `man regcomp`.
|
| 939 |
|
| 940 | ### re-multiline
|
| 941 |
|
| 942 | Multi-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 /
|