Skip to content

Commit

Permalink
ERLang parser support for comments
Browse files Browse the repository at this point in the history
Signed-off-by: Laurent Goderre <laurent.goderre@docker.com>
  • Loading branch information
LaurentGoderre committed Dec 5, 2023
1 parent 8e382c1 commit 6fb153e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
33 changes: 33 additions & 0 deletions syft/pkg/cataloger/erlang/erlang_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package erlang

import (
"bytes"
"errors"
"fmt"
"io"
"strings"
Expand All @@ -12,6 +13,8 @@ type erlangNode struct {
value interface{}
}

var errSkipComments = errors.New("")

func (e erlangNode) Slice() []erlangNode {
out, ok := e.value.([]erlangNode)
if ok {
Expand Down Expand Up @@ -56,6 +59,10 @@ func parseErlang(reader io.Reader) (erlangNode, error) {
i := 0
for i < len(data) {
item, err := parseErlangBlock(data, &i)
if err == errSkipComments {
skipWhitespace(data, &i)
continue
}
if err != nil {
return node(nil), fmt.Errorf("%w\n%s", err, printError(data, i))
}
Expand Down Expand Up @@ -158,6 +165,9 @@ func parseErlangNode(data []byte, i *int) (erlangNode, error) {
return parseErlangString(data, i)
case '<':
return parseErlangAngleString(data, i)
case '%':
parseErlangComment(data, i)
return node(nil), errSkipComments
}

if isLiteral(c) {
Expand Down Expand Up @@ -228,6 +238,10 @@ func parseErlangList(data []byte, i *int) (erlangNode, error) {
for *i < len(data) {
item, err := parseErlangNode(data, i)
if err != nil {
if err == errSkipComments {
skipWhitespace(data, i)
continue
}
return node(nil), err
}
out.value = append(out.value.([]erlangNode), item)
Expand All @@ -237,6 +251,9 @@ func parseErlangList(data []byte, i *int) (erlangNode, error) {
case ',':
*i++
continue
case '%':
// Starts a new comment node
continue
case ']', '}':
*i++
return out, nil
Expand All @@ -246,3 +263,19 @@ func parseErlangList(data []byte, i *int) (erlangNode, error) {
}
return out, nil
}

func parseErlangComment(data []byte, i *int) {
for *i < len(data) {
c := data[*i]

*i++

// Rest of a line is a comment. Deals with CR, LF and CR/LF
if c == '\n' {
break
} else if c == '\r' && data[*i] == '\n' {
*i++
break
}
}
}
19 changes: 19 additions & 0 deletions syft/pkg/cataloger/erlang/erlang_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,25 @@ func Test_parseErlang(t *testing.T) {
{"1.2.0"}.
].`,
},
{
name: "valid comments",
content: `
{ comments, [
{ foo, bar },
%% this is a comment
% this is also a comment
{ hello, 'bar' }, %%inline comment
{ baz }
]}`,
},
{
name: "starts with a comments",
content: `
%% starts with comment
{ comments, [
{ foo, bar }
]}`,
},
}

for _, test := range tests {
Expand Down

0 comments on commit 6fb153e

Please sign in to comment.