hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

ident.ha (981B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 use fmt;
      5 use hare::ast;
      6 use io;
      7 use memio;
      8 
      9 // Unparses an identifier.
     10 export fn ident(out: io::handle, id: ast::ident) (size | io::error) = {
     11 	let ctx = context {
     12 		out = out,
     13 		...
     14 	};
     15 	return _ident(&ctx, &syn_nowrap, id, synkind::IDENT);
     16 };
     17 
     18 fn _ident(
     19 	ctx: *context,
     20 	syn: *synfunc,
     21 	id: ast::ident,
     22 	kind: synkind,
     23 ) (size | io::error) = {
     24 	let n = 0z;
     25 	for (let i = 0z; i < len(id); i += 1) {
     26 		n += syn(ctx, id[i], kind)?;
     27 		if (i + 1 < len(id)) {
     28 			n += syn(ctx, "::", kind)?;
     29 		};
     30 	};
     31 	return n;
     32 };
     33 
     34 // Unparses an identifier into a string. The caller must free the return value.
     35 export fn identstr(id: ast::ident) str = {
     36 	let buf = memio::dynamic();
     37 	ident(&buf, id)!;
     38 	return memio::string(&buf)!;
     39 };
     40 
     41 @test fn ident() void = {
     42 	let s = identstr(["foo", "bar", "baz"]);
     43 	defer free(s);
     44 	assert(s == "foo::bar::baz");
     45 
     46 	let s = identstr(["foo"]);
     47 	defer free(s);
     48 	assert(s == "foo");
     49 };