Skip to content

Commit

Permalink
Add support for comments
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Jan 30, 2023
1 parent f311f78 commit a9ba44d
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 1 deletion.
5 changes: 5 additions & 0 deletions checker/checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,11 @@ MapOfAny[0]
cannot use int to get an element from map[string]interface {} (1:10)
| MapOfAny[0]
| .........^
1 /* one */ + "2"
invalid operation: + (mismatched types int and string) (1:13)
| 1 /* one */ + "2"
| ............^
`

func TestCheck_error(t *testing.T) {
Expand Down
4 changes: 4 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,10 @@ func TestExpr(t *testing.T) {
`lowercase`,
"lowercase",
},
{
`1 /* one*/ + 2 /* two */`,
3,
},
}

for _, tt := range tests {
Expand Down
17 changes: 17 additions & 0 deletions parser/lexer/lexer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,23 @@ var lexTests = []lexTest{
{Kind: EOF},
},
},
{
`foo // comment
bar // comment`,
[]Token{
{Kind: Identifier, Value: "foo"},
{Kind: Identifier, Value: "bar"},
{Kind: EOF},
},
},
{
`foo /* comment */ bar`,
[]Token{
{Kind: Identifier, Value: "foo"},
{Kind: Identifier, Value: "bar"},
{Kind: EOF},
},
},
}

func compareTokens(i1, i2 []Token) bool {
Expand Down
40 changes: 39 additions & 1 deletion parser/lexer/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ func root(l *lexer) stateFn {
return number
case r == '?':
return questionMark
case r == '/':
return slash
case strings.ContainsRune("([{", r):
l.emit(Bracket)
case strings.ContainsRune(")]}", r):
l.emit(Bracket)
case strings.ContainsRune("#,?:%+-/^", r): // single rune operator
case strings.ContainsRune("#,?:%+-^", r): // single rune operator
l.emit(Operator)
case strings.ContainsRune("&|!=*<>", r): // possible double rune operator
l.accept("&|=*")
Expand Down Expand Up @@ -158,3 +160,39 @@ func questionMark(l *lexer) stateFn {
l.emit(Operator)
return root
}

func slash(l *lexer) stateFn {
if l.accept("/") {
return singleLineComment
}
if l.accept("*") {
return multiLineComment
}
l.emit(Operator)
return root
}

func singleLineComment(l *lexer) stateFn {
for {
r := l.next()
if r == eof || r == '\n' {
break
}
}
l.ignore()
return root
}

func multiLineComment(l *lexer) stateFn {
for {
r := l.next()
if r == eof {
return l.error("unclosed comment")
}
if r == '*' && l.accept("/") {
break
}
}
l.ignore()
return root
}

0 comments on commit a9ba44d

Please sign in to comment.