Foundations Syntax and Atoms Lesson 06

Comments and strings

Mental Model

SJON has line comments and block comments:

; line comment
;; section heading by convention
#| block comment |#

Open in playground →

Comments attach to nearby structure and can be preserved by lossless printing. They are for authors and tools; canonical output may omit them.

SJON has two string surfaces:

"escaped\nstring"
"""raw string"""

Open in playground →

Both produce string values. Use escaped strings for normal text. Use raw strings when escaping would obscure the payload, such as shader source, regular expressions, paths with backslashes, or snippets of markup.

Worked Example

From ../../examples/wgsl-shader.sjon:

(shader-module :name "hello-triangle"
  :source """@vertex
fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
  var pos = array<vec2f, 3>(
    vec2(0.0, 0.5),
    vec2(-0.5, -0.5),
    vec2(0.5, -0.5),
  );
  return vec4f(pos[i], 0.0, 1.0);
}
""")

Open in playground →

The opening """ is immediately followed by @vertex, so the first byte of the string body is @.

This version starts with a newline:

:source """
@vertex
fn vs() -> @builtin(position) vec4f {
  return vec4f(0.0);
}
"""

Open in playground →

That may be fine, but it should be intentional.

Raw strings cannot contain three consecutive double quotes, because that sequence closes the string. If the payload contains """, use an escaped string.

Exercises

Write:

  1. A line comment above a non-obvious numeric value.
  2. A ;; section heading inside a long form.
  3. A raw string containing two lines of WGSL.
  4. An escaped string containing a quote and a newline.

Predict:

:source """
fn main() {}
"""

Open in playground →

The string starts with a newline before fn.

Repair if the leading newline is unwanted:

:source """fn main() {}
"""

Open in playground →

Repair this raw string:

(snippet :source """the delimiter is """ here""")

Open in playground →

Use an escaped string instead:

(snippet :source "the delimiter is \"\"\" here")

Open in playground →

Mastery Check

  1. When should you prefer raw strings ("""...""")?

  2. Does raw string content process \n escapes?

  3. Can block comments nest?