Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 1 | package parser |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "strings" |
| 6 | |
Akron | fa55bb2 | 2025-05-26 15:10:42 +0200 | [diff] [blame] | 7 | "github.com/KorAP/KoralPipe-TermMapper/ast" |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 8 | "github.com/alecthomas/participle/v2" |
| 9 | "github.com/alecthomas/participle/v2/lexer" |
| 10 | ) |
| 11 | |
| 12 | // GrammarParser parses a simple grammar into AST nodes |
| 13 | type GrammarParser struct { |
| 14 | defaultFoundry string |
| 15 | defaultLayer string |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 16 | tokenParser *participle.Parser[TokenGrammar] |
| 17 | mappingParser *participle.Parser[MappingGrammar] |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 18 | } |
| 19 | |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 20 | // TokenGrammar represents a single token expression |
| 21 | type TokenGrammar struct { |
| 22 | Token *TokenExpr `parser:"@@"` |
| 23 | } |
| 24 | |
| 25 | // MappingGrammar represents a mapping rule |
| 26 | type MappingGrammar struct { |
| 27 | Mapping *MappingRule `parser:"@@"` |
| 28 | } |
| 29 | |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 30 | // MappingRule represents a mapping between two token expressions |
| 31 | type MappingRule struct { |
| 32 | Upper *TokenExpr `parser:"@@"` |
| 33 | Lower *TokenExpr `parser:"'<>' @@"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 34 | } |
| 35 | |
| 36 | // TokenExpr represents a token expression in square brackets |
| 37 | type TokenExpr struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 38 | Expr *Expr `parser:"'[' @@ ']'"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | // Expr represents a sequence of terms and operators |
| 42 | type Expr struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 43 | First *Term `parser:"@@"` |
| 44 | Rest []*Op `parser:"@@*"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 45 | } |
| 46 | |
| 47 | type Op struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 48 | Operator string `parser:"@('&' | '|')"` |
| 49 | Term *Term `parser:"@@"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 50 | } |
| 51 | |
| 52 | // Term represents either a simple term or a parenthesized expression |
| 53 | type Term struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 54 | Simple *SimpleTerm `parser:"@@"` |
| 55 | Paren *ParenExpr `parser:"| @@"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 56 | } |
| 57 | |
| 58 | type ParenExpr struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 59 | Expr *Expr `parser:"'(' @@ ')'"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 60 | } |
| 61 | |
| 62 | // SimpleTerm represents any valid term form |
| 63 | type SimpleTerm struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 64 | WithFoundryLayer *FoundryLayerTerm `parser:"@@"` |
| 65 | WithFoundryKey *FoundryKeyTerm `parser:"| @@"` |
| 66 | WithLayer *LayerTerm `parser:"| @@"` |
| 67 | SimpleKey *KeyTerm `parser:"| @@"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 68 | } |
| 69 | |
| 70 | // FoundryLayerTerm represents foundry/layer=key:value |
| 71 | type FoundryLayerTerm struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 72 | Foundry string `parser:"@Ident '/'"` |
| 73 | Layer string `parser:"@Ident '='"` |
| 74 | Key string `parser:"@Ident"` |
| 75 | Value string `parser:"(':' @Ident)?"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 76 | } |
| 77 | |
| 78 | // FoundryKeyTerm represents foundry/key |
| 79 | type FoundryKeyTerm struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 80 | Foundry string `parser:"@Ident '/'"` |
| 81 | Key string `parser:"@Ident"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 82 | } |
| 83 | |
| 84 | // LayerTerm represents layer=key:value |
| 85 | type LayerTerm struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 86 | Layer string `parser:"@Ident '='"` |
| 87 | Key string `parser:"@Ident"` |
| 88 | Value string `parser:"(':' @Ident)?"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 89 | } |
| 90 | |
| 91 | // KeyTerm represents key:value |
| 92 | type KeyTerm struct { |
Akron | b40f5ac | 2025-05-21 11:22:33 +0200 | [diff] [blame] | 93 | Key string `parser:"@Ident"` |
| 94 | Value string `parser:"(':' @Ident)?"` |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 95 | } |
| 96 | |
| 97 | // NewGrammarParser creates a new grammar parser with optional default foundry and layer |
| 98 | func NewGrammarParser(defaultFoundry, defaultLayer string) (*GrammarParser, error) { |
| 99 | lex := lexer.MustSimple([]lexer.SimpleRule{ |
Akron | 121c66e | 2025-06-02 16:34:05 +0200 | [diff] [blame] | 100 | {Name: "Ident", Pattern: `(?:[a-zA-Z$]|\\.)(?:[a-zA-Z0-9_$]|\\.)*`}, |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 101 | {Name: "Punct", Pattern: `[\[\]()&\|=:/]|<>`}, |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 102 | {Name: "Whitespace", Pattern: `\s+`}, |
| 103 | }) |
| 104 | |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 105 | tokenParser, err := participle.Build[TokenGrammar]( |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 106 | participle.Lexer(lex), |
| 107 | participle.UseLookahead(2), |
| 108 | participle.Elide("Whitespace"), |
| 109 | ) |
| 110 | if err != nil { |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 111 | return nil, fmt.Errorf("failed to build token parser: %w", err) |
| 112 | } |
| 113 | |
| 114 | mappingParser, err := participle.Build[MappingGrammar]( |
| 115 | participle.Lexer(lex), |
| 116 | participle.UseLookahead(2), |
| 117 | participle.Elide("Whitespace"), |
| 118 | ) |
| 119 | if err != nil { |
| 120 | return nil, fmt.Errorf("failed to build mapping parser: %w", err) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 121 | } |
| 122 | |
| 123 | return &GrammarParser{ |
| 124 | defaultFoundry: defaultFoundry, |
| 125 | defaultLayer: defaultLayer, |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 126 | tokenParser: tokenParser, |
| 127 | mappingParser: mappingParser, |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 128 | }, nil |
| 129 | } |
| 130 | |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 131 | // Parse parses a grammar string into an AST node (for backward compatibility) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 132 | func (p *GrammarParser) Parse(input string) (ast.Node, error) { |
| 133 | // Remove extra spaces around operators to help the parser |
| 134 | input = strings.ReplaceAll(input, " & ", "&") |
| 135 | input = strings.ReplaceAll(input, " | ", "|") |
| 136 | |
Akron | 76b8797 | 2025-06-02 16:59:59 +0200 | [diff] [blame^] | 137 | // Add spaces around parentheses that are not escaped |
| 138 | // We need to be careful not to break escape sequences like \( |
| 139 | result := make([]rune, 0, len(input)*2) |
| 140 | runes := []rune(input) |
| 141 | for i, r := range runes { |
| 142 | if (r == '(' || r == ')') && (i == 0 || runes[i-1] != '\\') { |
| 143 | // Only add spaces if the parenthesis is not escaped |
| 144 | result = append(result, ' ', r, ' ') |
| 145 | } else { |
| 146 | result = append(result, r) |
| 147 | } |
| 148 | } |
| 149 | input = string(result) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 150 | |
| 151 | // Remove any extra spaces |
| 152 | input = strings.TrimSpace(input) |
| 153 | |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 154 | grammar, err := p.tokenParser.ParseString("", input) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 155 | if err != nil { |
| 156 | return nil, fmt.Errorf("failed to parse grammar: %w", err) |
| 157 | } |
| 158 | |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 159 | if grammar.Token == nil { |
| 160 | return nil, fmt.Errorf("expected token expression, got mapping rule") |
| 161 | } |
| 162 | |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 163 | wrap, err := p.parseExpr(grammar.Token.Expr) |
| 164 | if err != nil { |
| 165 | return nil, err |
| 166 | } |
| 167 | return &ast.Token{Wrap: wrap}, nil |
| 168 | } |
| 169 | |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 170 | // ParseMapping parses a mapping rule string into a MappingResult |
| 171 | func (p *GrammarParser) ParseMapping(input string) (*MappingResult, error) { |
| 172 | // Remove extra spaces around operators to help the parser |
| 173 | input = strings.ReplaceAll(input, " & ", "&") |
| 174 | input = strings.ReplaceAll(input, " | ", "|") |
| 175 | input = strings.ReplaceAll(input, " <> ", "<>") |
| 176 | |
Akron | 76b8797 | 2025-06-02 16:59:59 +0200 | [diff] [blame^] | 177 | // Add spaces around parentheses that are not escaped |
| 178 | // We need to be careful not to break escape sequences like \( |
| 179 | result := make([]rune, 0, len(input)*2) |
| 180 | runes := []rune(input) |
| 181 | for i, r := range runes { |
| 182 | if (r == '(' || r == ')') && (i == 0 || runes[i-1] != '\\') { |
| 183 | // Only add spaces if the parenthesis is not escaped |
| 184 | result = append(result, ' ', r, ' ') |
| 185 | } else { |
| 186 | result = append(result, r) |
| 187 | } |
| 188 | } |
| 189 | input = string(result) |
Akron | bb5065f | 2025-05-21 12:44:05 +0200 | [diff] [blame] | 190 | |
| 191 | // Remove any extra spaces |
| 192 | input = strings.TrimSpace(input) |
| 193 | |
| 194 | grammar, err := p.mappingParser.ParseString("", input) |
| 195 | if err != nil { |
| 196 | return nil, fmt.Errorf("failed to parse grammar: %w", err) |
| 197 | } |
| 198 | |
| 199 | if grammar.Mapping == nil { |
| 200 | return nil, fmt.Errorf("expected mapping rule, got token expression") |
| 201 | } |
| 202 | |
| 203 | upper, err := p.parseExpr(grammar.Mapping.Upper.Expr) |
| 204 | if err != nil { |
| 205 | return nil, err |
| 206 | } |
| 207 | |
| 208 | lower, err := p.parseExpr(grammar.Mapping.Lower.Expr) |
| 209 | if err != nil { |
| 210 | return nil, err |
| 211 | } |
| 212 | |
| 213 | return &MappingResult{ |
| 214 | Upper: &ast.Token{Wrap: upper}, |
| 215 | Lower: &ast.Token{Wrap: lower}, |
| 216 | }, nil |
| 217 | } |
| 218 | |
| 219 | // MappingResult represents the parsed mapping rule |
| 220 | type MappingResult struct { |
| 221 | Upper *ast.Token |
| 222 | Lower *ast.Token |
| 223 | } |
| 224 | |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 225 | // parseExpr builds the AST from the parsed Expr |
| 226 | func (p *GrammarParser) parseExpr(expr *Expr) (ast.Node, error) { |
| 227 | var operands []ast.Node |
| 228 | var operators []string |
| 229 | |
| 230 | // Parse the first term |
| 231 | first, err := p.parseTerm(expr.First) |
| 232 | if err != nil { |
| 233 | return nil, err |
| 234 | } |
| 235 | operands = append(operands, first) |
| 236 | |
| 237 | // Parse the rest |
| 238 | for _, op := range expr.Rest { |
| 239 | node, err := p.parseTerm(op.Term) |
| 240 | if err != nil { |
| 241 | return nil, err |
| 242 | } |
| 243 | operands = append(operands, node) |
| 244 | operators = append(operators, op.Operator) |
| 245 | } |
| 246 | |
| 247 | // If only one operand, return it |
| 248 | if len(operands) == 1 { |
| 249 | return operands[0], nil |
| 250 | } |
| 251 | |
| 252 | // Group operands by operator precedence (left-to-right, no precedence between & and |) |
| 253 | // We'll group by runs of the same operator |
| 254 | var groupOperands []ast.Node |
| 255 | var currentOp string |
| 256 | var currentGroup []ast.Node |
| 257 | for i, op := range operators { |
| 258 | if i == 0 { |
| 259 | currentOp = op |
| 260 | currentGroup = append(currentGroup, operands[i]) |
| 261 | } |
| 262 | if op == currentOp { |
| 263 | currentGroup = append(currentGroup, operands[i+1]) |
| 264 | } else { |
| 265 | groupOperands = append(groupOperands, &ast.TermGroup{ |
| 266 | Operands: append([]ast.Node{}, currentGroup...), |
| 267 | Relation: toRelation(currentOp), |
| 268 | }) |
| 269 | currentOp = op |
| 270 | currentGroup = []ast.Node{operands[i+1]} |
| 271 | } |
| 272 | } |
| 273 | if len(currentGroup) > 0 { |
| 274 | groupOperands = append(groupOperands, &ast.TermGroup{ |
| 275 | Operands: append([]ast.Node{}, currentGroup...), |
| 276 | Relation: toRelation(currentOp), |
| 277 | }) |
| 278 | } |
| 279 | if len(groupOperands) == 1 { |
| 280 | return groupOperands[0], nil |
| 281 | } |
| 282 | // If mixed operators, nest them left-to-right |
| 283 | result := groupOperands[0] |
| 284 | for i := 1; i < len(groupOperands); i++ { |
| 285 | result = &ast.TermGroup{ |
| 286 | Operands: []ast.Node{result, groupOperands[i]}, |
| 287 | Relation: toRelation(operators[0]), |
| 288 | } |
| 289 | } |
| 290 | return result, nil |
| 291 | } |
| 292 | |
| 293 | // parseTerm converts a Term into an AST node |
| 294 | func (p *GrammarParser) parseTerm(term *Term) (ast.Node, error) { |
| 295 | if term.Simple != nil { |
| 296 | return p.parseSimpleTerm(term.Simple) |
| 297 | } |
| 298 | if term.Paren != nil { |
| 299 | return p.parseExpr(term.Paren.Expr) |
| 300 | } |
| 301 | return nil, fmt.Errorf("invalid term: neither simple nor parenthesized") |
| 302 | } |
| 303 | |
| 304 | func toRelation(op string) ast.RelationType { |
| 305 | if op == "|" { |
| 306 | return ast.OrRelation |
| 307 | } |
| 308 | return ast.AndRelation |
| 309 | } |
| 310 | |
Akron | 121c66e | 2025-06-02 16:34:05 +0200 | [diff] [blame] | 311 | // unescapeString handles unescaping of backslash-escaped characters |
| 312 | func unescapeString(s string) string { |
| 313 | if s == "" { |
| 314 | return s |
| 315 | } |
| 316 | |
| 317 | result := make([]byte, 0, len(s)) |
| 318 | i := 0 |
| 319 | for i < len(s) { |
| 320 | if s[i] == '\\' && i+1 < len(s) { |
| 321 | // Escape sequence found, add the escaped character |
| 322 | result = append(result, s[i+1]) |
| 323 | i += 2 |
| 324 | } else { |
| 325 | // Regular character |
| 326 | result = append(result, s[i]) |
| 327 | i++ |
| 328 | } |
| 329 | } |
| 330 | return string(result) |
| 331 | } |
| 332 | |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 333 | // parseSimpleTerm converts a SimpleTerm into an AST Term node |
| 334 | func (p *GrammarParser) parseSimpleTerm(term *SimpleTerm) (ast.Node, error) { |
| 335 | var foundry, layer, key, value string |
| 336 | |
| 337 | switch { |
| 338 | case term.WithFoundryLayer != nil: |
Akron | 121c66e | 2025-06-02 16:34:05 +0200 | [diff] [blame] | 339 | foundry = unescapeString(term.WithFoundryLayer.Foundry) |
| 340 | layer = unescapeString(term.WithFoundryLayer.Layer) |
| 341 | key = unescapeString(term.WithFoundryLayer.Key) |
| 342 | value = unescapeString(term.WithFoundryLayer.Value) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 343 | case term.WithFoundryKey != nil: |
Akron | 121c66e | 2025-06-02 16:34:05 +0200 | [diff] [blame] | 344 | foundry = unescapeString(term.WithFoundryKey.Foundry) |
| 345 | key = unescapeString(term.WithFoundryKey.Key) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 346 | case term.WithLayer != nil: |
Akron | 121c66e | 2025-06-02 16:34:05 +0200 | [diff] [blame] | 347 | layer = unescapeString(term.WithLayer.Layer) |
| 348 | key = unescapeString(term.WithLayer.Key) |
| 349 | value = unescapeString(term.WithLayer.Value) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 350 | case term.SimpleKey != nil: |
Akron | 121c66e | 2025-06-02 16:34:05 +0200 | [diff] [blame] | 351 | key = unescapeString(term.SimpleKey.Key) |
| 352 | value = unescapeString(term.SimpleKey.Value) |
Akron | 22322ec | 2025-05-21 11:17:30 +0200 | [diff] [blame] | 353 | default: |
| 354 | return nil, fmt.Errorf("invalid term: no valid form found") |
| 355 | } |
| 356 | |
| 357 | if foundry == "" { |
| 358 | foundry = p.defaultFoundry |
| 359 | } |
| 360 | if layer == "" { |
| 361 | layer = p.defaultLayer |
| 362 | } |
| 363 | |
| 364 | return &ast.Term{ |
| 365 | Foundry: foundry, |
| 366 | Key: key, |
| 367 | Layer: layer, |
| 368 | Match: ast.MatchEqual, |
| 369 | Value: value, |
| 370 | }, nil |
| 371 | } |