Debian Codegraph @

Nasal/string.nas

raw
1 var iscntrl = func(c) c >= 1 and c <= 31 or c == 127;
2 var isascii = func(c) c >= 0 and c <= 127;
3 var isupper = func(c) c >= `A` and c <= `Z`;
4 var islower = func(c) c >= `a` and c <= `z`;
5 var isdigit = func(c) c >= `0` and c <= `9`;
6 var isblank = func(c) c == ` ` or c == `\t`;
7 var ispunct = func(c) c >= `!` and c <= `/` or c >= `:` and c <= `@`
8 or c >= `[` and c <= `\`` or c >= `{` and c <= `~`;
9
10 var isxdigit = func(c) isdigit(c) or c >= `a` and c <= `f` or c >= `A` and c <= `F`;
11 var isspace = func(c) c == ` ` or c >= `\t` and c <= `\r`;
12 var isalpha = func(c) isupper(c) or islower(c);
13 var isalnum = func(c) isalpha(c) or isdigit(c);
14 var isgraph = func(c) isalnum(c) or ispunct(c);
15 var isprint = func(c) isgraph(c) or c == ` `;
16
17 var toupper = func(c) islower(c) ? c + `A` - `a` : c;
18 var tolower = func(c) isupper(c) ? c + `a` - `A` : c;
19
20 var isxspace = func(c) isspace(c) or c == `\n`;
21
22
23 ##
24 # trim spaces at the left (lr < 0), at the right (lr > 0), or both (lr = 0)
25 # An optional function argument defines which characters should be trimmed:
26 #
27 # string.trim(a); # trim spaces
28 # string.trim(a, 1, string.isdigit); # trim digits at the right
29 # string.trim(a, 0, func(c) c == `\\` or c == `/`); # trim slashes/backslashes
30 #
31 var trim = func(s, lr = 0, istrim = nil) {
32 if (istrim == nil)
33 istrim = isspace;
34 var l = 0;
35 if (lr <= 0)
36 for (; l < size(s); l += 1)
37 if (!istrim(s[l]))
38 break;
39 var r = size(s) - 1;
40 if (lr >= 0)
41 for (; r >= 0; r -= 1)
42 if (!istrim(s[r]))
43 break;
44 return r < l ? "" : substr(s, l, r - l + 1);
45 }
46
47 ##
48 # truncate at the first match
49 #
50 # string.truncateAt("file.xml", ".xml"); # "file.xml" -> "file"
51 # string.truncateAt("file.xml", ".txt"); # "file.xml" -> "file.xml"
52 #
53 var truncateAt = func(src, match){
54 var rv = nil;
55 call(func {
56 if (src != nil and match !=nil) {
57 var pos = find(match,src);
58 if (pos>=0)
59 src=substr(src,0,pos);
60 }
61 }, nil, var err = []);
62 return src;
63 }
64
65 ##
66 # return string converted to lower case letters
67 #
68 var lc = func(str) {
69 var s = "";
70 for (var i = 0; i < size(str); i += 1)
71 s ~= chr(tolower(str[i]));
72 return s;
73 }
74
75
76 ##
77 # return string converted to upper case letters
78 #
79 var uc = func(str) {
80 var s = "";
81 for (var i = 0; i < size(str); i += 1)
82 s ~= chr(toupper(str[i]));
83 return s;
84 }
85
86
87 ##
88 # case insensitive string compare and match functions
89 # (not very efficient -- converting the array to be sorted
90 # first is faster)
91 #
92 var icmp = func(a, b) cmp(lc(a), lc(b));
93 var imatch = func(a, b) match(lc(a), lc(b));
94
95
96 ##
97 # check if string <str> matches shell style pattern <patt>
98 #
99 # Rules:
100 # ? stands for any single character
101 # * stands for any number (including zero) of arbitrary characters
102 # \ escapes the next character and makes it stand for itself; that is:
103 # \? stands for a question mark (not the "any single character" placeholder)
104 # [] stands for a group of characters:
105 # [abc] stands for letters a, b or c
106 # [^abc] stands for any character but a, b, and c (^ as first character -> inversion)
107 # [1-4] stands for digits 1 to 4 (1, 2, 3, 4)
108 # [1-4-] stands for digits 1 to 4, and the minus
109 # [-1-4] same as above
110 # [1-3-6] stands for digits 1 to 3, minus, and 6
111 # [1-3-6-9] stands for digits 1 to 3, minus, and 6 to 9
112 # [][] stands for the closing and the opening bracket (']' must be first!)
113 # [^^] stands for all characters but the caret symbol
114 # [\/] stands for a backslash or a slash (the backslash isn't an
115 # escape character in a [] character group)
116 #
117 # Note that a minus can't be a range delimiter, as in [a--e],
118 # which would be interpreted as any of a, e, or minus.
119 #
120 # Example:
121 # string.match(name, "*[0-9].xml"); ... true if 'name' ends with digit followed by ".xml"
122 #
123 match = func(str, patt) {
124 var s = 0;
125 for (var p = 0; p < size(patt) and s < size(str); ) {
126 if (patt[p] == `\\`) {
127 if ((p += 1) >= size(patt))
128 return 0; # pattern ends with backslash
129
130 } elsif (patt[p] == `?`) {
131 s += 1;
132 p += 1;
133 continue;
134
135 } elsif (patt[p] == `*`) {
136 for (; p < size(patt); p += 1)
137 if (patt[p] != `*`)
138 break;
139 if (p >= size(patt))
140 return 1;
141
142 for (; s < size(str); s += 1)
143 if (caller(0)[1](substr(str, s), substr(patt, p)))
144 return 1;
145 continue;
146
147 } elsif (patt[p] == `[`) {
148 setsize(var x = [], 256);
149 var invert = 0;
150 if ((p += 1) < size(patt) and patt[p] == `^`) {
151 p += 1;
152 invert = 1;
153 }
154 for (var i = 0; p < size(patt); p += 1) {
155 if (patt[p] == `]` and i)
156 break;
157 x[patt[p]] = 1;
158 i += 1;
159
160 if (p + 2 < patt[p] and patt[p] != `-` and patt[p + 1] == `-`
161 and patt[p + 2] != `]` and patt[p + 2] != `-`) {
162 var from = patt[p];
163 var to = patt[p += 2];
164 for (var c = from; c <= to; c += 1)
165 x[c] = 1;
166 }
167 }
168 if (invert ? !!x[str[s]] : !x[str[s]])
169 return 0;
170 s += 1;
171 p += 1;
172 continue;
173 }
174
175 if (str[s] != patt[p])
176 return 0;
177 s += 1;
178 p += 1;
179 }
180
181 # eat trailing * in the pattern; this is needed to fix:
182 # https://sourceforge.net/p/flightgear/codetickets/2016/
183 for (;p < size(patt) and patt[p] == `*`; p += 1) {}
184
185 return s == size(str) and p == size(patt);
186 }
187
188
189 ##
190 # Removes superfluous slashes, empty and "." elements,
191 # expands all ".." elements keeping relative paths,
192 # and turns all backslashes into slashes.
193 # The result will start with a slash if it started with a slash or backslash,
194 # it will end without slash.
195 #
196 normpath = func(path) {
197 path = replace(path, "\\", "/");
198 var prefix = size(path) and path[0] == `/` ? "/" : "";
199
200 var stack = [];
201 var relative = 1;
202
203 foreach (var e; split("/", path)) {
204 if (e == "." or e == "")
205 continue;
206 elsif (e == ".." and !relative)
207 pop(stack);
208 else {
209 append(stack, e);
210 relative = 0;
211 }
212 }
213 return size(stack) ? prefix ~ join("/", stack) : "/";
214 }
215
216
217 ##
218 # Join all elements of a list inserting a separator between every two of them.
219 #
220 join = func(sep, list) {
221 if (!size(list))
222 return "";
223 var str = list[0];
224 foreach (var s; subvec(list, 1))
225 str ~= sep ~ s;
226 return str;
227 }
228
229
230 ##
231 # Replace all occurrences of 'old' by 'new'.
232 #
233 replace = func(str, old, new) {
234 return join(new, split(old, str));
235 }
236
237
238 ##
239 # Get a function out of a string template for fast insertion of template
240 # parameters. This allows to use the same templates as with most available tile
241 # mapping engines (eg. Leaflet, Polymaps). Return a callable function object on
242 # success, and nil if parsing the templated fails. See string._template_getargs
243 # for more on calling a compile object.
244 #
245 # Example (Build MapQuest tile url):
246 #
247 # var makeUrl = string.compileTemplate(
248 # "http://otile1.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpg"
249 # );
250 # print( makeUrl({x: 5, y: 4, z: 3}) );
251 #
252 # Output:
253 #
254 # http://otile1.mqcdn.com/tiles/1.0.0/map/3/5/4.jpg
255 #
256 var compileTemplate = func(template, type=nil) {
257 var code = 'func(__ENV=nil) { string._template_getargs();';
258 var len = size(template);
259 var start = 0;
260 var end = 0;
261 if (type == nil or type == "simple_names") {
262 # See http://james.padolsey.com/javascript/straight-up-interpolation/
263 while( (start = template.find('{', end)) >= 0 )
264 {
265 if( end > 0 )
266 code ~= '~';
267 code ~= '"' ~ substr(template, end, start - end) ~ '"';
268 if( (end = template.find('}', start)) < 0 )
269 {
270 debug.warn("string.compileTemplate: unclosed brace pair (" ~ template ~ ")");
271 return nil;
272 }
273
274 code ~= '~__ENV["' ~ substr(template, start + 1, end - start - 1) ~ '"]';
275 end += 1;
276 }
277 if( end < len )
278 code ~= '~"' ~ substr(template, end, len - end) ~ '"';
279 } elsif (type == "nasal_expression") {
280 var level = 0;
281 for (var i=0; i<len; i+=1) {
282 if (template[i] != `{`) continue;
283 start = i;
284 if ( end > 0 )
285 code ~= "~";
286 code ~= '"' ~ substr(template, end, start - end) ~ '"';
287 level = 1; var skip = 0;
288 for (var j=i+1; j<len and level > 0; j+=1)
289 if (template[j] == `{`) level += 1;
290 elsif (template[j] == `}`) level -= 1;
291 elsif (template[j] == `"`)
292 if (skip == `"`) skip = 0;
293 elsif (skip != `'`) skip = `"`;
294 elsif (template[j] == `'`)
295 if (skip == `'`) skip = 0;
296 elsif (skip != '"') skip = `'`;
297 elsif (skip)
298 if ((skip == `'` or skip == `"`) and template[j] == `\\`)
299 skip = `\\`;
300 elsif (skip == `\\` and template[j] == `\\`)
301 skip = skip;
302 else
303 skip = 0;
304 if (level)
305 die("string.compileTemplate: unclosed brace pair (" ~ template ~ ")");
306 end = j;
307 code ~= '~(' ~ substr(template, start + 1, end - start - 1)~")";
308 end += 1;
309 i = end;
310 }
311 if( end < len )
312 code ~= '~"' ~ substr(template, end, len - end) ~ '"';
313 }
314 code ~= "}";
315 var fn = compile(code)(); # get the inside function with the argument __ENV=nil
316 var (ns,fn1) = caller(1);
317 return bind(fn, ns, fn1);
318 }
319
320 ##
321 # Private function used by string.naCompileTemplate. Expands any __ENV parameter
322 # into the locals of the caller. This allows both named arguments and manual hash
323 # arguments via __ENV.
324 #
325 # Examples using (format = func(__ENV) {string._template_getargs()}):
326 #
327 # Pass arguments as hash:
328 # format({a: 1, "b ":2});
329 # Or:
330 # format(__ENV:{a: 1, "b ":2});
331 # Pass arguments as named:
332 # format(a: 1, "b ":2);
333 # Pass arguments as both named and hash, using
334 # __ENV to specify the latter:
335 # format(a: 1, __ENV:{"b ": 2});
336 #
337 var _template_getargs = func() {
338 var ns = caller(1)[0];
339 if (contains(ns, "__ENV")) {
340 var __ENV = ns.__ENV;
341 if (__ENV != nil)
342 foreach (var k; keys(__ENV))
343 ns[k] = __ENV[k];
344 }
345 ns.__ENV = ns;
346 }
347
348
349 ##
350 # Simple scanf function. Takes an input string, a pattern, and a
351 # vector. It returns 0 if the format didn't match, and appends
352 # all found elements to the given vector. Return values:
353 #
354 # -1 string matched format ending with % (i.e. more chars than format cared about)
355 # 0 string didn't match format
356 # 1 string matched, but would still match if the right chars were added
357 # 2 string matched, and would not if any character would be added
358 #
359 # var r = string.scanf("comm3freq123.456", "comm%ufreq%f", var result = []);
360 #
361 # The result vector will be set to [3, 123.456].
362 #
363 var Scan = {
364 new : func(s) {{ str: s, pos: 0, parents: [Scan] }},
365 getc : func {
366 if (me.pos >= size(me.str))
367 return nil;
368 var c = me.str[me.pos];
369 me.pos += 1;
370 return c;
371 },
372 ungetc : func { me.pos -= 1 },
373 rest : func { substr(me.str, me.pos) },
374 };
375
376
377 var scanf = func(test, format, result) {
378 if (find("%", format) < 0)
379 return cmp(test, format) ? 0 : 2;
380
381 var success = 0;
382 var str = Scan.new(test);
383 var format = Scan.new(format);
384
385 while (1) {
386 var f = format.getc();
387 if (f == nil) {
388 break;
389
390 } elsif (f == `%`) {
391 success = 1; # unsafe match
392 f = format.getc();
393 if (f == nil)
394 return -1; # format ended with %
395 if (f == `%`) {
396 if (str.getc() != `%`)
397 return 0;
398 success = 2;
399 continue;
400 }
401
402 if (isdigit(f)) {
403 var fnum = f - `0`;
404 while ((f = format.getc()) != nil and isdigit(f))
405 fnum = fnum * 10 + f - `0`;
406 } else {
407 var fnum = -2; # because we add one if !prefix
408 }
409
410 var scanstr = "";
411 var prefix = 0;
412 var sign = 1;
413 if (f == `d` or f == `f` or f == `u`) {
414 var c = str.getc();
415 if (c == nil) {
416 return 0;
417 } elsif (c == `+`) {
418 prefix = 1;
419 } elsif (c == `-`) {
420 if (f == `u`)
421 return 0;
422 (prefix, sign) = (1, -1);
423 } else {
424 str.ungetc();
425 }
426 if (!prefix)
427 fnum += 1;
428
429 while ((var c = str.getc()) != nil and (fnum -= 1)) {
430 if (f != `f` and c == `.`)
431 break;
432 elsif (num(scanstr ~ chr(c) ~ '0') != nil) # append 0 to digest e/E
433 scanstr ~= chr(c);
434 else
435 break;
436 }
437 if (c != nil)
438 str.ungetc();
439 if (num(scanstr) == nil)
440 return 0;
441 if (!size(scanstr) and prefix)
442 return 0;
443 append(result, sign * num(scanstr));
444
445 } elsif (f == `s`) {
446 fnum += 1;
447 while ((var c = str.getc()) != nil and c != ` ` and (fnum -= 1))
448 scanstr ~= chr(c);
449
450 if (c != nil)
451 str.ungetc();
452 if (!size(scanstr))
453 return 0;
454
455 append(result, scanstr);
456
457 } else {
458 die("scanf: bad format element %" ~ chr(f));
459 }
460
461
462 } elsif (isspace(f)) {
463 while ((var c = str.getc()) != nil and isspace(c))
464 nil;
465 if (c != nil)
466 str.ungetc();
467
468 } elsif (f != (var c = str.getc())) {
469 return 0;
470
471 } else {
472 success = 2; # safe match
473 }
474 }
475 return str.getc() == nil and format.getc() == nil ? success : 0;
476 }
477
478
479 ##
480 # ANSI colors (see $ man console_codes)
481 #
482 var setcolors = func(enabled) {
483 color_enabled = (enabled and getprop("/sim/startup/stderr-to-terminal"));
484 }
485 var color = func(color, s, enabled=nil) {
486 if (enabled == nil) enabled = color_enabled;
487 return enabled ? "\x1b[" ~ color ~ "m" ~ s ~ "\x1b[m" : s;
488 }
489
490
491 ##
492 # Add ANSI color codes to string, if terminal-ansi-colors are enabled and
493 # stderr prints to a terminal. Example:
494 #
495 # print(string.color("31;1", "this is red"));
496 #
497 var color_enabled = 0;
498 setlistener("/sim/startup/terminal-ansi-colors", func(n) setcolors(n.getBoolValue()), 1, 0);
499
500 ##
501 # shorten sting s to length by replacing characters in the middle by '...'
502 var squeeze = func(s, length) {
503 if (size(s) <= length or length < 7)
504 return s;
505
506 var l = substr(s, 0, (length - 3) / 2);
507 var r = substr(s, size(s) + size(l) + 3 - length);
508 return l ~ "..." ~ r;
509 }