feat: refactor some shit

This commit is contained in:
Max Richter
2025-08-17 00:46:45 +02:00
parent 43644c4f40
commit cc8f967f07
20 changed files with 459 additions and 209 deletions

View File

@@ -1,51 +1,32 @@
package parser
type BlockType string
import (
"fmt"
const (
BlockData BlockType = "data" // content between lines "{" and "}"
BlockMatching BlockType = "matching" // everything outside data blocks
"git.max-richter.dev/max/marka/parser/blocks"
)
type Block struct {
Type BlockType
Start, End int // byte offsets [Start, End)
src *string
}
func (b Block) GetContent() string {
if b.src == nil || b.Start < 0 || b.End > len(*b.src) || b.Start > b.End {
return ""
}
return (*b.src)[b.Start:b.End]
}
// ExtractBlocks scans once, emitting:
// - data blocks: inner content between a line that's exactly "{" and a line that's exactly "}"
// - matching blocks: gaps between data blocks (excluding the brace lines themselves)
func ExtractBlocks(src string) []Block {
var out []Block
func ExtractBlocks(template string) ([]blocks.TemplateBlock, error) {
var out []blocks.TemplateBlock
var curlyIndex int
const CLOSING = '}'
const OPENING = '{'
if len(src) > 0 && src[0] == OPENING {
var start int
var blockType blocks.BlockType
if len(template) > 0 && template[0] == OPENING {
curlyIndex = 1
out = append(out, Block{
Start: 0,
Type: BlockData,
src: &src,
})
blockType = blocks.DataBlock
} else {
out = append(out, Block{
Start: 0,
Type: BlockMatching,
src: &src,
})
blockType = blocks.MatchingBlock
}
for i, r := range src {
for i, r := range template {
var nextCurlyIndex = curlyIndex
@@ -57,41 +38,42 @@ func ExtractBlocks(src string) []Block {
}
var nextChar rune = ' '
if i+1 < len(src) {
nextChar = rune(src[i+1])
if i+1 < len(template) {
nextChar = rune(template[i+1])
}
if curlyIndex == 0 && nextCurlyIndex == 1 {
out[len(out)-1].End = i
out = append(out, Block{
Start: i,
Type: BlockData,
src: &src,
})
block, err := blocks.ParseTemplateBlock(template[start:i], blockType)
if err != nil {
return nil, fmt.Errorf("Failed to parse block: %w", err)
}
out = append(out, block)
start = i
blockType = blocks.DataBlock
} else if curlyIndex == 1 && nextCurlyIndex == 0 {
out[len(out)-1].End = i + 1
block, err := blocks.ParseTemplateBlock(template[start:i+1], blockType)
if err != nil {
return nil, fmt.Errorf("Failed to parse block: %w", err)
}
out = append(out, block)
if nextChar == OPENING {
out = append(out, Block{
Start: i + 1,
Type: BlockData,
src: &src,
})
start = i + 1
blockType = blocks.DataBlock
} else {
out = append(out, Block{
Start: i + 1,
Type: BlockMatching,
src: &src,
})
start = i + 1
blockType = blocks.MatchingBlock
}
}
curlyIndex = nextCurlyIndex
}
var lastBlock = out[len(out)-1]
if lastBlock.End == 0 {
out = out[:len(out)-1]
}
// var lastBlock = out[len(out)-1]
// if lastBlock.End == 0 {
// out = out[:len(out)-1]
// }
return out
return out, nil
}