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

528 lines, 314 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
163Compares 2 strings using lexicographic order on bytes.
164Returns 0 if s1 and s2 are equal, -1 if s1 is less than s2, and 1 if s1 is greater than s2.
165
166### shSplit()
167
168Split a string into a List of strings, using the shell algorithm that respects
169`$IFS`.
170
171Prefer `split()` to `shSplit()`.
172
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)]
184 abc
185
186 $ echo $[join(x, ' ')] # optional separator
187 a b c
188
189As a reminder, you can call it with the [fat-arrow][] operator `=>` for function chaining:
190
191 var items = [1, 2, 3]
192
193 json write (items => join()) # => "123"
194 json write (items => join(' ')) # => "1 2 3"
195 json write (items => join(', ')) # => "1, 2, 3"
196
197[fat-arrow]: chap-expr-lang.html#fat-arrow
198
199## Dict
200
201### keys()
202
203Returns all existing keys from a dict as a list of strings.
204
205 var en2fr = {
206 hello: "bonjour",
207 friend: "ami",
208 cat: "chat"
209 }
210 = keys(en2fr)
211 # => (List 0x4689) ["hello","friend","cat"]
212
213### values()
214
215Similar to `keys()`, but returns the values of the dictionary.
216
217 var person = {
218 name: "Foo",
219 age: 25,
220 hobbies: :|walking reading|
221 }
222 = values(en2fr)
223 # => (List 0x4689) ["Foo",25,["walking","reading"]]
224
225### get()
226
227Return value for given key, falling back to the default value if the key
228doesn't exist.
229
230 var book = {
231 title: "Hitchhiker's Guide",
232 published: 1979,
233 }
234
235 var published = get(book, 'published', null)
236 = published
237 # => (Int) 1979
238
239 var author = get(book, 'author', "???")
240 = author
241 # => (Str) "???"
242
243If not specified, the default value is `null`:
244
245 var author = get(book, 'author')
246 = author
247 # => (Null) null
248
249## Float
250
251### floatsEqual()
252
253Check if two floating point numbers are equal.
254
255 = floatsEqual(42.0, 42.0)
256 (Bool) true
257
258It's usually better to make an approximate comparison:
259
260 = abs(float1 - float2) < 0.001
261 (Bool) false
262
263## Obj
264
265### first()
266
267Get the Dict that contains an object's properties.
268
269 ysh$ = first(obj)
270 (Dict) {x: 42}
271
272The Dict and Obj share the same storage. So if the Dict is modified, the
273object is too.
274
275If you want a copy, use `dict(obj)`.
276
277### rest()
278
279Get the "prototype" of an Obj, which is another Obj, or null:
280
281 ysh$ = rest(obj)
282 (Null) null
283
284## Word
285
286### glob()
287
288See `glob-pat` topic for syntax.
289
290### maybe()
291
292## Serialize
293
294### toJson()
295
296Convert an object in memory to JSON text:
297
298 $ = toJson({name: "alice"})
299 (Str) '{"name":"alice"}'
300
301Add indentation by passing the `space` param:
302
303 $ = toJson([42], space=2)
304 (Str) "[\n 42\n]"
305
306Turn non-serializable types into `null`, instead of raising an error:
307
308 $ = toJson(/d+/, type_errors=false)
309 (Str) 'null'
310
311The `toJson()` function is to `json write (x)`, except the default value of
312`space` is 0.
313
314See [err-json-encode][] for errors.
315
316[err-json-encode]: chap-errors.html#err-json-encode
317
318### fromJson()
319
320Convert JSON text to an object in memory:
321
322 = fromJson('{"name":"alice"}')
323 (Dict) {"name": "alice"}
324
325Similar to `json read <<< '{"name": "alice"}'`.
326
327See [err-json-decode][] for errors.
328
329[err-json-decode]: chap-errors.html#err-json-decode
330
331### toJson8()
332
333Like `toJson()`, but it also converts binary data (non-Unicode strings) to
334J8-style `b'foo \yff'` strings.
335
336In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
337character.
338
339See [err-json8-encode][] for errors.
340
341[err-json8-encode]: chap-errors.html#err-json8-encode
342
343### fromJson8()
344
345Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
346\yff'` strings.
347
348See [err-json8-decode][] for errors.
349
350[err-json8-decode]: chap-errors.html#err-json8-decode
351
352## Pattern
353
354### `_group()`
355
356Like `Match.group()`, but accesses the global match created by `~`:
357
358 if ('foo42' ~ / d+ /) {
359 echo $[_group(0)] # => 42
360 }
361
362### `_start()`
363
364Like `Match.start()`, but accesses the global match created by `~`:
365
366 if ('foo42' ~ / d+ /) {
367 echo $[_start(0)] # => 3
368 }
369
370### `_end()`
371
372Like `Match.end()`, but accesses the global match created by `~`:
373
374 if ('foo42' ~ / d+ /) {
375 echo $[_end(0)] # => 5
376 }
377
378## Reflection
379
380### func/eval()
381
382This function is like [`io->eval()`][io/eval], but it disallows I/O.
383
384Example:
385
386 var cmd = ^(const x = 42)
387 var d = eval(cmd, to_dict=true) # {x: 42}
388
389[io/eval]: chap-type-method.html#io/eval
390
391### func/evalExpr()
392
393This function is like [`io->evalExpr()`][io/evalExpr], but it disallows I/O.
394
395Example:
396
397 var x = 42
398 var expr = ^[x + 1]
399 var val = evalExpr(expr) # 43
400
401[io/evalExpr]: chap-type-method.html#io/evalExpr
402
403## Introspect
404
405### `shvarGet()`
406
407Given a variable name, return its value. It uses the "dynamic scope" rule,
408which looks up the stack for a variable.
409
410It's meant to be used with `shvar`:
411
412 proc proc1 {
413 shvar PATH=/tmp { # temporarily set PATH in this stack frame
414 my-proc
415 }
416
417 proc2
418 }
419
420 proc proc2 {
421 proc3
422 }
423
424 proc proc3 {
425 var path = shvarGet('PATH') # Look up the stack (dynamic scoping)
426 echo $path # => /tmp
427 }
428
429 proc1
430
431Note that `shvar` is usually for string variables, and is analogous to `shopt`
432for "booleans".
433
434If the variable isn't defined, `shvarGet()` returns `null`. So there's no way
435to distinguish an undefined variable from one that's `null`.
436
437### `getVar()`
438
439Given a variable name, return its value.
440
441 $ var x = 42
442 $ echo $[getVar('x')]
443 42
444
445The variable may be local or global. (Compare with `shvarGet()`.) the "dynamic
446scope" rule.)
447
448If the variable isn't defined, `getVar()` returns `null`. So there's no way to
449distinguish an undefined variable from one that's `null`.
450
451### `setVar()`
452
453Bind a name to a value, in the local scope. Returns nothing.
454
455 call setVar('myname', 42)
456
457This is like
458
459 setvar myname = 42
460
461except the name can is a string, which can be constructed at runtime.
462
463---
464
465You can also bind globals:
466
467 call setVar('myname', 42, global=true)
468
469which is like
470
471 setglobal myname = 42
472
473### `getShFunction`
474
475Given the name of a shell function, return the corresponding [Proc][] value, or
476`null` if it's not found.
477
478[Proc]: chap-type-method.html#Proc
479
480### `parseCommand()`
481
482Given a code string, parse it as a command (with the current parse options).
483
484Returns a `value.Command` instance, or raises an error.
485
486### `parseExpr()`
487
488TODO:
489
490Given a code string, parse it as an expression.
491
492Returns a `value.Expr` instance, or raises an error.
493
494### `bindFrame()`
495
496TODO
497
498## Hay Config
499
500### parseHay()
501
502### evalHay()
503
504
505## Hashing
506
507### sha1dc()
508
509Git's algorithm.
510
511### sha256()
512
513
514<!--
515
516### Better Syntax
517
518These functions give better syntax to existing shell constructs.
519
520- `shQuote()` for `printf %q` and `${x@Q}`
521- `trimLeft()` for `${x#prefix}` and `${x##prefix}`
522- `trimRight()` for `${x%suffix}` and `${x%%suffix}`
523- `trimLeftGlob()` and `trimRightGlob()` for slow, legacy glob
524- `upper()` for `${x^^}`
525- `lower()` for `${x,,}`
526- `strftime()`: hidden in `printf`
527
528-->