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

527 lines, 313 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 = 1337
44
45 $ = type(d)
46 (Str) 'Dict'
47
48 $ = type(n)
49 (Str) 'Int'
50
51Similar names: [type][]
52
53[type]: chap-index.html#type
54
55
56## Conversions
57
58### bool()
59
60Returns the truth value of its argument. Similar to `bool()` in python, it
61returns `false` for:
62
63- `false`, `0`, `0.0`, `''`, `{}`, `[]`, and `null`.
64
65Returns `true` for all other values.
66
67### int()
68
69Given a float, returns the largest integer that is less than its argument (i.e. `floor()`).
70
71 $ = int(1.99)
72 (Int) 1
73
74Given a string, `Int()` will attempt to convert the string to a base-10
75integer. The base can be overridden by calling with a second argument.
76
77 $ = int('10')
78 (Int) 10
79
80 $ = int('10', 2)
81 (Int) 2
82
83 ysh$ = Int('foo')
84 # fails with an expression error
85
86### float()
87
88Given an integer, returns the corresponding floating point representation.
89
90 $ = float(1)
91 (Float) 1.0
92
93Given a string, `Float()` will attempt to convert the string to float.
94
95 $ = float('1.23')
96 (Float) 1.23
97
98 ysh$ = float('bar')
99 # fails with an expression error
100
101### str()
102
103Converts a `Float` or `Int` to a string.
104
105### list()
106
107Given a list, returns a shallow copy of the original.
108
109Given an iterable value (e.g. a range or dictionary), returns a list containing
110one element for each item in the original collection.
111
112 $ = list({'a': 1, 'b': 2})
113 (List) ['a', 'b']
114
115 $ = list(1:5)
116 (List) [1, 2, 3, 4, 5]
117
118### dict()
119
120Given a dictionary, returns a shallow copy of the original.
121
122### runes()
123
124TODO
125
126Given a string, decodes UTF-8 into a List of integer "runes" (aka code points).
127
128Each rune is in the range `U+0` to `U+110000`, and **excludes** the surrogate
129range.
130
131 runes(s, start=-1, end=-1)
132
133TODO: How do we signal errors?
134
135(`runes()` can be used to implement implemented Python's `ord()`.)
136
137### encodeRunes()
138
139TODO
140
141Given a List of integer "runes" (aka code points), return a string.
142
143(`encodeRunes()` can be used to implement implemented Python's `chr()`.)
144
145### bytes()
146
147TODO
148
149Given a string, return a List of integer byte values.
150
151Each byte is in the range 0 to 255.
152
153### encodeBytes()
154
155TODO
156
157Given a List of integer byte values, return a string.
158
159## Str
160
161### strcmp()
162
163TODO
164
165### shSplit()
166
167Split a string into a List of strings, using the shell algorithm that respects
168`$IFS`.
169
170Prefer `split()` to `shSplit()`.
171
172
173## List
174
175### join()
176
177Given a List, stringify its items, and join them by a separator. The default
178separator is the empty string.
179
180 var x = ['a', 'b', 'c']
181
182 $ echo $[join(x)]
183 abc
184
185 $ echo $[join(x, ' ')] # optional separator
186 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)
255 (Bool) true
256
257It's usually better to make an approximate comparison:
258
259 = abs(float1 - float2) < 0.001
260 (Bool) false
261
262## Obj
263
264### first()
265
266Get the Dict that contains an object's properties.
267
268 ysh$ = first(obj)
269 (Dict) {x: 42}
270
271The Dict and Obj share the same storage. So if the Dict is modified, the
272object is too.
273
274If you want a copy, use `dict(obj)`.
275
276### rest()
277
278Get the "prototype" of an Obj, which is another Obj, or null:
279
280 ysh$ = rest(obj)
281 (Null) null
282
283## Word
284
285### glob()
286
287See `glob-pat` topic for syntax.
288
289### maybe()
290
291## Serialize
292
293### toJson()
294
295Convert an object in memory to JSON text:
296
297 $ = toJson({name: "alice"})
298 (Str) '{"name":"alice"}'
299
300Add indentation by passing the `space` param:
301
302 $ = toJson([42], space=2)
303 (Str) "[\n 42\n]"
304
305Turn non-serializable types into `null`, instead of raising an error:
306
307 $ = toJson(/d+/, type_errors=false)
308 (Str) 'null'
309
310The `toJson()` function is to `json write (x)`, except the default value of
311`space` is 0.
312
313See [err-json-encode][] for errors.
314
315[err-json-encode]: chap-errors.html#err-json-encode
316
317### fromJson()
318
319Convert JSON text to an object in memory:
320
321 = fromJson('{"name":"alice"}')
322 (Dict) {"name": "alice"}
323
324Similar to `json read <<< '{"name": "alice"}'`.
325
326See [err-json-decode][] for errors.
327
328[err-json-decode]: chap-errors.html#err-json-decode
329
330### toJson8()
331
332Like `toJson()`, but it also converts binary data (non-Unicode strings) to
333J8-style `b'foo \yff'` strings.
334
335In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
336character.
337
338See [err-json8-encode][] for errors.
339
340[err-json8-encode]: chap-errors.html#err-json8-encode
341
342### fromJson8()
343
344Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
345\yff'` strings.
346
347See [err-json8-decode][] for errors.
348
349[err-json8-decode]: chap-errors.html#err-json8-decode
350
351## Pattern
352
353### `_group()`
354
355Like `Match.group()`, but accesses the global match created by `~`:
356
357 if ('foo42' ~ / d+ /) {
358 echo $[_group(0)] # => 42
359 }
360
361### `_start()`
362
363Like `Match.start()`, but accesses the global match created by `~`:
364
365 if ('foo42' ~ / d+ /) {
366 echo $[_start(0)] # => 3
367 }
368
369### `_end()`
370
371Like `Match.end()`, but accesses the global match created by `~`:
372
373 if ('foo42' ~ / d+ /) {
374 echo $[_end(0)] # => 5
375 }
376
377## Reflection
378
379### func/eval()
380
381This function is like [`io->eval()`][io/eval], but it disallows I/O.
382
383Example:
384
385 var cmd = ^(const x = 42)
386 var d = eval(cmd, to_dict=true) # {x: 42}
387
388[io/eval]: chap-type-method.html#io/eval
389
390### func/evalExpr()
391
392This function is like [`io->evalExpr()`][io/evalExpr], but it disallows I/O.
393
394Example:
395
396 var x = 42
397 var expr = ^[x + 1]
398 var val = evalExpr(expr) # 43
399
400[io/evalExpr]: chap-type-method.html#io/evalExpr
401
402## Introspect
403
404### `shvarGet()`
405
406Given a variable name, return its value. It uses the "dynamic scope" rule,
407which looks up the stack for a variable.
408
409It's meant to be used with `shvar`:
410
411 proc proc1 {
412 shvar PATH=/tmp { # temporarily set PATH in this stack frame
413 my-proc
414 }
415
416 proc2
417 }
418
419 proc proc2 {
420 proc3
421 }
422
423 proc proc3 {
424 var path = shvarGet('PATH') # Look up the stack (dynamic scoping)
425 echo $path # => /tmp
426 }
427
428 proc1
429
430Note that `shvar` is usually for string variables, and is analogous to `shopt`
431for "booleans".
432
433If the variable isn't defined, `shvarGet()` returns `null`. So there's no way
434to distinguish an undefined variable from one that's `null`.
435
436### `getVar()`
437
438Given a variable name, return its value.
439
440 $ var x = 42
441 $ echo $[getVar('x')]
442 42
443
444The variable may be local or global. (Compare with `shvarGet()`.) the "dynamic
445scope" rule.)
446
447If the variable isn't defined, `getVar()` returns `null`. So there's no way to
448distinguish an undefined variable from one that's `null`.
449
450### `setVar()`
451
452Bind a name to a value, in the local scope. Returns nothing.
453
454 call setVar('myname', 42)
455
456This is like
457
458 setvar myname = 42
459
460except the name can is a string, which can be constructed at runtime.
461
462---
463
464You can also bind globals:
465
466 call setVar('myname', 42, global=true)
467
468which is like
469
470 setglobal myname = 42
471
472### `getShFunction`
473
474Given the name of a shell function, return the corresponding [Proc][] value, or
475`null` if it's not found.
476
477[Proc]: chap-type-method.html#Proc
478
479### `parseCommand()`
480
481Given a code string, parse it as a command (with the current parse options).
482
483Returns a `value.Command` instance, or raises an error.
484
485### `parseExpr()`
486
487TODO:
488
489Given a code string, parse it as an expression.
490
491Returns a `value.Expr` instance, or raises an error.
492
493### `bindFrame()`
494
495TODO
496
497## Hay Config
498
499### parseHay()
500
501### evalHay()
502
503
504## Hashing
505
506### sha1dc()
507
508Git's algorithm.
509
510### sha256()
511
512
513<!--
514
515### Better Syntax
516
517These functions give better syntax to existing shell constructs.
518
519- `shQuote()` for `printf %q` and `${x@Q}`
520- `trimLeft()` for `${x#prefix}` and `${x##prefix}`
521- `trimRight()` for `${x%suffix}` and `${x%%suffix}`
522- `trimLeftGlob()` and `trimRightGlob()` for slow, legacy glob
523- `upper()` for `${x^^}`
524- `lower()` for `${x,,}`
525- `strftime()`: hidden in `printf`
526
527-->