Search code examples
smalltalkpharopetitparser

Parsing comments with PetitParser in Pharo


Is there a simpler way to parse 1-line comments than this?

comment
    ^ '//' asParser ,
      (#any asParser starLazy: (#newline asParser)) ,
      #newline asParser
                  ==> [ :result | nil "Ignore comments" ]
program
    ^ (comment / instruction) star
        ==> [ :result | N2TProgramNode new
                                setNodes: (result copyWithout: nil) ]

I'm particularly unsure about the repetition of (#newline asParser) and the #copyWithout:.

After Lukas' answer I came up with the much simpler following solution:

program
    ^ programEntity star
        ==> [ :result | N2TProgramNode new setNodes: result]

programEntity
    ^ instruction trim: ignorable

ignorable
    ^ comment / #space asParser

comment
    ^ '//' asParser ,  #newline asParser negate star

Solution

  • Why wouldn't the following comment parser work as well?

    '//' asParser , #newline asParser negate star
    

    Also you might want to include the parsing of comments into the whitespace parsing with trim: (if the grammar allows it), so you don't have to think about it all the time.