OILS / doc / ref / chap-builtin-func.md View on Github | oilshell.org

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