-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
53 lines (45 loc) · 1018 Bytes
/
parser.go
File metadata and controls
53 lines (45 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package satsolver
import (
"fmt"
"github.com/alecthomas/participle"
"io"
"strings"
)
// MustParse panics if Parse returns an error
func MustParse(s string) Formula {
r := strings.NewReader(s)
f, err := Parse(r)
if err != nil {
panic(err)
}
return f
}
// Parse parses a CNF formula and returns an AST representing it
// example: a ^ (~b v c) ^ ~d
func Parse(r io.Reader) (Formula, error) {
parser, err := participle.Build(&Formula{})
if err != nil {
return Formula{}, fmt.Errorf("error building grammer: %w", err)
}
var f Formula
err = parser.Parse(r, &f)
if err != nil {
return Formula{}, fmt.Errorf("error parsing input: %w", err)
}
CleanFormula(&f)
return f, nil
}
func CleanFormula(f *Formula) {
varsMap := map[string]*Variable{}
for ci, clause := range f.C {
for li, literal := range clause.L {
if v, ok := varsMap[literal.V.Name]; ok {
// fix the literal in clause
f.C[ci].L[li].V = v
} else {
varsMap[literal.V.Name] = literal.V
}
}
}
f.V = varsMap
}