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

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