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

434 lines, 254 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 overriden 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 corressponding flaoting 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## Float
214
215### floatsEqual()
216
217Check if two floating point numbers are equal.
218
219 = floatsEqual(42.0, 42.0)
220 (Bool) true
221
222It's usually better to make an approximate comparison:
223
224 = abs(float1 - float2) < 0.001
225 (Bool) false
226
227## Obj
228
229### Object
230
231Construct an object with a prototype and properties:
232
233 var obj = Object(null, {x: 42}}
234
235An object with methods:
236
237 func mymethod(self) { return (self.x) }
238 var cls = Object(null, {mymethod: mymethod})
239 var obj = Object(cls, {x: 42}}
240
241### prototype()
242
243Get the prototype of an object. May be null:
244
245 ysh$ = prototype(obj)
246 (Null) null
247
248### propView()
249
250Get a Dict that aliases an object's properties.
251
252 ysh andy@hoover:~/git/oilshell/oil$ = propView(obj)
253 (Dict) {x: 42}
254
255This means that if the Dict is modified, then the object is too.
256
257If you want to copy it, use `dict(obj)`.
258
259## Word
260
261### glob()
262
263See `glob-pat` topic for syntax.
264
265### maybe()
266
267## Serialize
268
269### toJson()
270
271Convert an object in memory to JSON text:
272
273 $ = toJson({name: "alice"})
274 (Str) '{"name":"alice"}'
275
276Add indentation by passing the `space` param:
277
278 $ = toJson([42], space=2)
279 (Str) "[\n 42\n]"
280
281Similar to `json write (x)`, except the default value of `space` is 0.
282
283See [err-json-encode][] for errors.
284
285[err-json-encode]: chap-errors.html#err-json-encode
286
287### fromJson()
288
289Convert JSON text to an object in memory:
290
291 = fromJson('{"name":"alice"}')
292 (Dict) {"name": "alice"}
293
294Similar to `json read <<< '{"name": "alice"}'`.
295
296See [err-json-decode][] for errors.
297
298[err-json-decode]: chap-errors.html#err-json-decode
299
300### toJson8()
301
302Like `toJson()`, but it also converts binary data (non-Unicode strings) to
303J8-style `b'foo \yff'` strings.
304
305In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
306character.
307
308See [err-json8-encode][] for errors.
309
310[err-json8-encode]: chap-errors.html#err-json8-encode
311
312### fromJson8()
313
314Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
315\yff'` strings.
316
317See [err-json8-decode][] for errors.
318
319[err-json8-decode]: chap-errors.html#err-json8-decode
320
321## Pattern
322
323### `_group()`
324
325Like `Match => group()`, but accesses the global match created by `~`:
326
327 if ('foo42' ~ / d+ /) {
328 echo $[_group(0)] # => 42
329 }
330
331### `_start()`
332
333Like `Match => start()`, but accesses the global match created by `~`:
334
335 if ('foo42' ~ / d+ /) {
336 echo $[_start(0)] # => 3
337 }
338
339### `_end()`
340
341Like `Match => end()`, but accesses the global match created by `~`:
342
343 if ('foo42' ~ / d+ /) {
344 echo $[_end(0)] # => 5
345 }
346
347## Introspection
348
349### `shvarGet()`
350
351Given a variable name, return its value. It uses the "dynamic scope" rule,
352which looks up the stack for a variable.
353
354It's meant to be used with `shvar`:
355
356 proc proc1 {
357 shvar PATH=/tmp { # temporarily set PATH in this stack frame
358 my-proc
359 }
360
361 proc2
362 }
363
364 proc proc2 {
365 proc3
366 }
367
368 proc proc3 {
369 var path = shvarGet('PATH') # Look up the stack (dynamic scoping)
370 echo $path # => /tmp
371 }
372
373 proc1
374
375Note that `shvar` is usually for string variables, and is analogous to `shopt`
376for "booleans".
377
378If the variable isn't defined, `shvarGet()` returns `null`. So there's no way
379to distinguish an undefined variable from one that's `null`.
380
381### `getVar()`
382
383Given a variable name, return its value.
384
385 $ var x = 42
386 $ echo $[getVar('x')]
387 42
388
389The variable may be local or global. (Compare with `shvarGet()`.) the "dynamic
390scope" rule.)
391
392If the variable isn't defined, `getVar()` returns `null`. So there's no way to
393distinguish an undefined variable from one that's `null`.
394
395### `evalExpr()`
396
397Given a an expression quotation, evaluate it and return its value:
398
399 $ var expr = ^[1 + 2]
400
401 $ = evalExpr(expr)
402 3
403
404## Hay Config
405
406### parseHay()
407
408### evalHay()
409
410
411## Hashing
412
413### sha1dc()
414
415Git's algorithm.
416
417### sha256()
418
419
420<!--
421
422### Better Syntax
423
424These functions give better syntax to existing shell constructs.
425
426- `shQuote()` for `printf %q` and `${x@Q}`
427- `trimLeft()` for `${x#prefix}` and `${x##prefix}`
428- `trimRight()` for `${x%suffix}` and `${x%%suffix}`
429- `trimLeftGlob()` and `trimRightGlob()` for slow, legacy glob
430- `upper()` for `${x^^}`
431- `lower()` for `${x,,}`
432- `strftime()`: hidden in `printf`
433
434-->