12. Character string

12.1. Immutable string

Literal of character string is wrapped with double quotes such like "foo", and the type is string.

1
2
3
4
5
6
(* File: print_foo.dats *)
#include "share/atspre_staload.hats"

val () = println! "foo"

implement main0 () = ()
$ patscc print_foo.dats
$ ./a.out
foo

However, immutable string can’t do such like following:

  • append
  • reverse

12.2. Mutable string

How to concatenate two strings? Please use string_append function.

1
2
3
4
5
6
7
(* File: try_string_append.dats *)
#include "share/atspre_staload.hats"

implement main0 () = {
  val s3 = string_append ("Yokohama", "Station")
  val () = println! s3
}

However the code causes following compile error:

$ patscc try_string_append.dats
/home/kiwamu/tmp/try_string_append.dats: 60(line=3, offs=22) -- 135(line=6, offs=2): error(3): the linear dynamic variable [s3$3509(-1)] needs to be consumed but it is preserved with the type [S2Eapp(S2Ecst(strptr_addr_vtype); S2EVar(4175))] instead.
patsopt(TRANS3): there are [1] errors in total.
exit(ATS): uncaught exception: _2home_2kiwamu_2src_2ATS_2dPostiats_2src_2pats_error_2esats__FatalErrorExn(1025)

Why does the error occur? Because we forget to free the mutable string.

1
2
3
4
5
6
7
#include "share/atspre_staload.hats"

implement main0 () = {
  val s3 = string_append ("Yokohama", "Station")
  val () = println! s3
  val () = free s3
}
$ patscc string_append.dats -DATS_MEMALLOC_LIBC
$ ./a.out
YokohamaStation
_images/string_append.png

xxx