Tree printing

This commit is contained in:
2026-07-13 14:34:14 +02:00
parent 36e95f2568
commit 4f3226b0b7
3 changed files with 69 additions and 6 deletions
+55 -1
View File
@@ -10,8 +10,62 @@ read_stdin :: proc() -> []string {
return strings.split_lines(content)
}
print_token :: proc(token: Token, depth: int) {
indent := strings.repeat(" ", depth, context.temp_allocator)
type_str := ""
switch token.type {
case TokenType.Text:
type_str = "Text"
case TokenType.Italics:
type_str = "Italics"
case TokenType.Bold:
type_str = "Bold"
case TokenType.BreakLine:
type_str = "BreakLine"
case TokenType.Heading:
type_str = "Heading"
case TokenType.Paragraph:
type_str = "Paragraph"
}
value_str := ""
switch v in token.value {
case string:
value_str = v
case int:
value_str = fmt.aprintf("%d", v, allocator = context.temp_allocator)
case TokenMode:
switch v {
case TokenMode.Start:
value_str = "Start"
case TokenMode.End:
value_str = "End"
case TokenMode.Modeless:
value_str = "Modeless"
}
}
if value_str != "" {
fmt.printf("%s%s(%s)", indent, type_str, value_str)
} else {
fmt.printf("%s%s", indent, type_str)
}
fmt.println()
for child in token.children {
print_token(child, depth + 1)
}
}
print_token_tree :: proc(tokens: [dynamic]Token) {
for token in tokens {
print_token(token, 0)
}
}
main :: proc() {
lines := read_stdin()
parsed := parse(lines)
fmt.println(parsed)
print_token_tree(parsed)
}
+11 -2
View File
@@ -9,11 +9,13 @@ TokenType :: enum {
Bold,
BreakLine,
Heading,
Paragraph,
}
TokenMode :: enum {
Start,
End,
Modeless,
}
TokenValue :: union {
@@ -25,10 +27,11 @@ TokenValue :: union {
Token :: struct {
type: TokenType,
value: TokenValue,
child: [dynamic]Token,
children: [dynamic]Token,
}
token_tree := [dynamic]Token{}
current_token := &token_tree[0]
replace_text :: proc(text: string, start: int, len_: int, repl: string) -> string {
builder := strings.builder_make(context.temp_allocator)
@@ -54,14 +57,20 @@ parse_header :: proc(line: string) -> (int, string) {
}
parse :: proc(lines: []string, allocator := context.allocator) -> [dynamic]Token {
token_tree := [dynamic]Token{}
append(&token_tree, Token{TokenType.Paragraph, TokenMode.Start, nil})
current_token := &token_tree[0]
for untrimmed_line in lines {
line := strings.trim_space(untrimmed_line)
if len(line) == 0 {
append(&token_tree, Token{TokenType.BreakLine, TokenMode.Start, nil})
append(&current_token.children, Token{TokenType.BreakLine, TokenMode.Modeless, nil})
continue
}
append(&current_token.children, Token{TokenType.Text, line, nil})
// lvl, text := parse_header(trimmed)
// is_header := lvl > 0
+1 -1
View File
@@ -1 +1 @@
clear && make format && cat README.tlm | make run | ./preview
clear && make format && cat README.tlm | make run # | ./preview