OILS / doc / ref / chap-builtin-func.md View on Github | oils.pub

544 lines, 320 significant
1---
2title: Builtin Functions (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 **Builtin Functions**
13
14</div>
15
16This chapter describes builtin functions (as opposed to [builtin
17commands](chap-builtin-cmd.html).)
18
19<span class="in-progress">(in progress)</span>
20
21<div id="dense-toc">
22</div>
23
24## Values
25
26### len()
27
28Returns the
29
30- number of entries in a `List`
31- number of pairs in a `Dict`
32- number of bytes in a `Str`
33 - TODO: `countRunes()` can return the number of UTF-8 encoded code points.
34
35### func/type()
36
37Given an arbitrary value, returns a string representing the value's runtime
38type.
39
40For example:
41
42 var d = {'foo': 'bar'}
43 var n = 42
44
45 = type(d) # => (Str) 'Dict'
46 = type(n) # => (Str) 'Int'
47
48Similar names: [type][]
49
50[type]: chap-index.html#type
51
52
53## Conversions
54
55### bool()
56
57Returns the truth value of its argument. Similar to `bool()` in python, it
58returns `false` for:
59
60- `false`, `0`, `0.0`, `''`, `{}`, `[]`, and `null`.
61
62Returns `true` for all other values.
63
64### int()
65
66Given a float, returns the largest integer that is less than its argument (i.e. `floor()`).
67
68 = int(1.99) # => (Int) 1
69
70Given a string, `Int()` will attempt to convert the string to a base-10
71integer.
72
73 = int('10') # => (Int) 10
74
75<!-- TODO
76The base can be overridden by calling with a second argument.
77 = int('10', base=2) # => (Int) 2
78-->
79
80```raw
81= int('not_an_integer') # fails with an expression error
82```
83
84### float()
85
86Given an integer, returns the corresponding floating point representation.
87
88 = float(1) # => (Float) 1.0
89
90Given a string, `Float()` will attempt to convert the string to float.
91
92 = float('1.23') # => (Float) 1.23
93
94```raw
95= float('bar') # fails with an expression error
96```
97
98### str()
99
100Converts a `Float` or `Int` to a string.
101
102### list()
103
104Given a list, returns a shallow copy of the original.
105
106 = list({'a': 1, 'b': 2}) # => (List) ['a', 'b']
107
108Given an iterable value (e.g. a range or dictionary), returns a list containing
109one element for each item in the original collection.
110
111 = list(1 ..= 5) # => (List) [1, 2, 3, 4, 5]
112
113### dict()
114
115Given a dictionary, returns a shallow copy of the original.
116
117### runes()
118
119TODO
120
121Given a string, decodes UTF-8 into a List of integer "runes" (aka code points).
122
123Each rune is in the range `U+0` to `U+110000`, and **excludes** the surrogate
124range.
125
126```raw
127runes(s, start=-1, end=-1)
128```
129
130TODO: How do we signal errors?
131
132(`runes()` can be used to implement implemented Python's `ord()`.)
133
134### encodeRunes()
135
136TODO
137
138Given a List of integer "runes" (aka code points), return a string.
139
140(`encodeRunes()` can be used to implement implemented Python's `chr()`.)
141
142### bytes()
143
144TODO
145
146Given a string, return a List of integer byte values.
147
148Each byte is in the range 0 to 255.
149
150### encodeBytes()
151
152TODO
153
154Given a List of integer byte values, return a string.
155
156## Str
157
158### strcmp()
159
160Compare 2 strings, using lexicographic order on bytes.
161
162Returns 0 if the strings are equal:
163
164 = strcmp('z', 'z') # => (Int) 0
165
166Or -1 if the first is less than the second:
167
168 = strcmp('a', 'aa') # => (Int) -1
169
170Or 1 if the first is greater than the second:
171
172 = strcmp('z', 'a') # => (Int) 1
173
174## List
175
176### join()
177
178Given a List, stringify its items, and join them by a separator. The default
179separator is the empty string.
180
181 var x = ['a', 'b', 'c']
182
183 echo $[join(x)] # => abc
184
185 # optional separator
186 echo $[join(x, ' ')] # => a b c
187
188As a reminder, you can call it with the [fat-arrow][] operator `=>` for function chaining:
189
190 var items = [1, 2, 3]
191
192 json write (items => join()) # => "123"
193 json write (items => join(' ')) # => "1 2 3"
194 json write (items => join(', ')) # => "1, 2, 3"
195
196[fat-arrow]: chap-expr-lang.html#fat-arrow
197
198## Dict
199
200### keys()
201
202Returns all existing keys from a dict as a list of strings.
203
204 var en2fr = {
205 hello: "bonjour",
206 friend: "ami",
207 cat: "chat"
208 }
209 = keys(en2fr)
210 # => (List 0x4689) ["hello","friend","cat"]
211
212### values()
213
214Similar to `keys()`, but returns the values of the dictionary.
215
216 var person = {
217 name: "Foo",
218 age: 25,
219 hobbies: :|walking reading|
220 }
221 = values(en2fr)
222 # => (List 0x4689) ["Foo",25,["walking","reading"]]
223
224### get()
225
226Return value for given key, falling back to the default value if the key
227doesn't exist.
228
229 var book = {
230 title: "Hitchhiker's Guide",
231 published: 1979,
232 }
233
234 var published = get(book, 'published', null)
235 = published
236 # => (Int) 1979
237
238 var author = get(book, 'author', "???")
239 = author
240 # => (Str) "???"
241
242If not specified, the default value is `null`:
243
244 var author = get(book, 'author')
245 = author
246 # => (Null) null
247
248## Float
249
250### floatsEqual()
251
252Check if two floating point numbers are equal.
253
254 = floatsEqual(42.0, 42.0) # => (Bool) true
255
256It's usually better to make an approximate comparison:
257
258 use $LIB_YSH/math.ysh --pick abs
259 var f1 = 0.3
260 var f2 = 0.4
261 = abs(f1 - f2) < 0.001 # => (Bool) false
262
263## Obj
264
265Let's use this definition:
266
267 var fields = {x: 42}
268 var obj = Obj.new(fields, null)
269
270### first()
271
272Get the Dict that contains an object's properties.
273
274 = first(obj) # => (Dict) {x: 42}
275
276The Dict and Obj share the same storage. So if the Dict is modified, the
277object is too.
278
279If you want a copy, use `dict(obj)`.
280
281### rest()
282
283Get the "prototype" of an Obj, which is another Obj, or null:
284
285 = rest(obj) # => (Null) null
286
287## Word
288
289### maybe()
290
291Turn a string into a list, based on its emptiness.
292
293It's designed to be used to construct `argv` arrays, along with
294[expr-splice][].
295
296 var empty = ''
297 write -- ale @[maybe(empty)] corn # => ale corn
298
299 var s = 'bean'
300 write -- ale @[maybe(s)] corn # => ale bean corn
301
302[expr-splice]: chap-word-lang.html#expr-splice
303
304### shSplit()
305
306Split a string into a List of strings, using the shell algorithm that respects
307`$IFS`.
308
309Prefer [split()][split] to `shSplit()`.
310
311[split]: chap-type-method.html#split
312
313## Serialize
314
315### toJson()
316
317Convert an object in memory to JSON text:
318
319 = toJson({name: "alice"}) # => (Str) '{"name":"alice"}'
320
321Add indentation by passing the `space` param:
322
323 = toJson([42], space=2) # => (Str) "[\n 42\n]"
324
325Turn non-serializable types into `null`, instead of raising an error:
326
327 = toJson(/d+/, type_errors=false) # => (Str) 'null'
328
329The `toJson()` function is to `json write (x)`, except the default value of
330`space` is 0.
331
332See [err-json-encode][] for errors.
333
334[err-json-encode]: chap-errors.html#err-json-encode
335
336### fromJson()
337
338Convert JSON text to an object in memory:
339
340 = fromJson('{"name":"alice"}') # => (Dict) {"name": "alice"}
341
342Similar to `json read <<< '{"name": "alice"}'`.
343
344See [err-json-decode][] for errors.
345
346[err-json-decode]: chap-errors.html#err-json-decode
347
348### toJson8()
349
350Like `toJson()`, but it also converts binary data (non-Unicode strings) to
351J8-style `b'foo \yff'` strings.
352
353In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
354character.
355
356See [err-json8-encode][] for errors.
357
358[err-json8-encode]: chap-errors.html#err-json8-encode
359
360### fromJson8()
361
362Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
363\yff'` strings.
364
365See [err-json8-decode][] for errors.
366
367[err-json8-decode]: chap-errors.html#err-json8-decode
368
369## Pattern
370
371### `_group()`
372
373Like `Match.group()`, but accesses the global match created by `~`:
374
375 if ('foo42' ~ / d+ /) {
376 echo $[_group(0)] # => 42
377 }
378
379### `_start()`
380
381Like `Match.start()`, but accesses the global match created by `~`:
382
383 if ('foo42' ~ / d+ /) {
384 echo $[_start(0)] # => 3
385 }
386
387### `_end()`
388
389Like `Match.end()`, but accesses the global match created by `~`:
390
391 if ('foo42' ~ / d+ /) {
392 echo $[_end(0)] # => 5
393 }
394
395## Reflection
396
397### func/eval()
398
399This function is like [`io->eval()`][io/eval], but it disallows I/O.
400
401Example:
402
403 var cmd = ^(const x = 42; )
404 = eval(cmd, to_dict=true) # => (Dict) {x: 42}
405
406[io/eval]: chap-type-method.html#io/eval
407
408### func/evalExpr()
409
410This function is like [`io->evalExpr()`][io/evalExpr], but it disallows I/O.
411
412Example:
413
414 var x = 42
415 var expr = ^[x + 1]
416 var val = evalExpr(expr) # 43
417
418[io/evalExpr]: chap-type-method.html#io/evalExpr
419
420## Introspect
421
422### `shvarGet()`
423
424Given a variable name, return its value. It uses the "dynamic scope" rule,
425which looks up the stack for a variable.
426
427It's meant to be used with `shvar`:
428
429 proc proc1 {
430 shvar PATH=/tmp { # temporarily set PATH in this stack frame
431 echo
432 }
433
434 proc2
435 }
436
437 proc proc2 {
438 proc3
439 }
440
441 proc proc3 {
442 var path = shvarGet('PATH') # Look up the stack (dynamic scoping)
443 echo $path # => /tmp
444 }
445
446 proc1
447
448Note that `shvar` is usually for string variables, and is analogous to `shopt`
449for "booleans".
450
451If the variable isn't defined, `shvarGet()` returns `null`. So there's no way
452to distinguish an undefined variable from one that's `null`.
453
454### `getVar()`
455
456Given a variable name, return its value.
457
458 var x = 42
459 = getVar('x') # => (Int) 42
460
461The variable may be local or global. (Compare with `shvarGet()`.) the "dynamic
462scope" rule.)
463
464If the variable isn't defined, `getVar()` returns `null`. So there's no way to
465distinguish an undefined variable from one that's `null`.
466
467### `setVar()`
468
469Bind a name to a value, in the local scope. Returns nothing.
470
471 call setVar('myname', 42)
472
473This is like
474
475 setvar myname = 42
476
477except the name can is a string, which can be constructed at runtime.
478
479---
480
481You can also bind globals:
482
483 call setVar('myname', 42, global=true)
484
485which is like
486
487 setglobal myname = 42
488
489### `getShFunction`
490
491Given the name of a shell function, return the corresponding [Proc][] value, or
492`null` if it's not found.
493
494[Proc]: chap-type-method.html#Proc
495
496### `parseCommand()`
497
498Given a code string, parse it as a command (with the current parse options).
499
500Returns a `value.Command` instance, or raises an error.
501
502### `parseExpr()`
503
504TODO:
505
506Given a code string, parse it as an expression.
507
508Returns a `value.Expr` instance, or raises an error.
509
510### `bindFrame()`
511
512TODO
513
514## Hay Config
515
516### parseHay()
517
518### evalHay()
519
520
521## Hashing
522
523### sha1dc()
524
525Git's algorithm.
526
527### sha256()
528
529
530<!--
531
532### Better Syntax
533
534These functions give better syntax to existing shell constructs.
535
536- `shQuote()` for `printf %q` and `${x@Q}`
537- `trimLeft()` for `${x#prefix}` and `${x##prefix}`
538- `trimRight()` for `${x%suffix}` and `${x%%suffix}`
539- `trimLeftGlob()` and `trimRightGlob()` for slow, legacy glob
540- `upper()` for `${x^^}`
541- `lower()` for `${x,,}`
542- `strftime()`: hidden in `printf`
543
544-->