Compiler/Verifying syntax: Difference between revisions

→‎{{header|Go}}: Further tweaks and examples.
(→‎{{header|Go}}: Further tweaks and examples.)
Line 50:
After making the appropriate substitutions, we can therefore use the parser in Go's standard library to verify whether the statements are valid or not. As expressions cannot be statements in Go, we simply parse the latter as expressions.
 
However, before applying the parser, we first need to ensure that the expressions don't include any characters (including non-ASCII) or usages thereof which Go would otherwise permit. Note that it's not necessary to specifically check for '"++'" and '"--'" as these are statements in Go and can't appear in expressions anyway.
 
In particular, after substitutions, '"= not'", "+ not" etc. would be allowed by the Go parser so we need to exclude itthem. Curiously, the Go parser allows something like '"2 < 3 < 4'" even though it doesn't compile. We need therefore to exclude that also (see Talk page).
<lang go>package main
 
Line 63:
 
var (
re1 = regexp.MustCompile(`[^_a-zA-Z0-9\+\-\*/=<\(\) \s]`)
re2 = regexp.MustCompile(`\b_\w*\b`)
re3 = regexp.MustCompile(`=[ =<+*/-]\s*not`)
re4 = regexp.MustCompile(`(=|<)[ ]\s*[^=< ]+[ ]\s*([=|<+*/-])`)
)
 
Line 86:
matches = re4.FindStringSubmatch(expr)
if matches != nil {
return fmt.Errorf("expectedoperator EOF,%q foundis %qnon-associative", []rune(matches[21])[0])
}
return nil
Line 101:
func main() {
exprs := []string{
"3 + not 5",
"3 + (not 5)",
"(42 + 3",
" not 3 < 4 or (true or 3 / 4 + 8 * 5 - 5 * 2 < 56) and 4 * 3 < 12 or not true",
Line 106 ⟶ 108:
"not 7 < 2",
"2 < 3 < 4",
"2 < foobar - 3 < 4",
"2 < foobar and 3 < 4",
"4 * (32 - 16) + 9 = 73",
"235 76 + 1",
"a + b = not c and false",
"a + b = (not c) and false",
"a + b = (not c and false)",
"ab_c / bd2 or < e_f7",
"g not = h",
Line 140 ⟶ 145:
{{out}}
<pre>
Statement to verify: "3 + not 5"
"false" -> expected operand, found 'not'
 
Statement to verify: "3 + (not 5)"
"true"
 
Statement to verify: "(42 + 3"
"false" -> expected ')', found newline
Line 153 ⟶ 164:
 
Statement to verify: "2 < 3 < 4"
"false" -> expected EOF, foundoperator '<' is non-associative
 
Statement to verify: "2 < foobar - 3 < 4"
"false" -> operator '<' is non-associative
 
Statement to verify: "2 < foobar and 3 < 4"
"true"
 
Statement to verify: "4 * (32 - 16) + 9 = 73"
Line 165 ⟶ 182:
 
Statement to verify: "a + b = (not c) and false"
"true"
 
Statement to verify: "a + b = (not c and false)"
"true"
 
9,485

edits