grammars-v4 icon indicating copy to clipboard operation
grammars-v4 copied to clipboard

A possible parsing error related to type conversion of Golang

Open enochii opened this issue 4 years ago • 4 comments
trafficstars

Given the below code(code snippet from here):

var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem()

if I'm not wrong, (*Any)(nil) should be a conversion expression. But it seems it's parsed as an invocation(in which the (nil) has been parsed as ArgumentContext):

enochii avatar Aug 16 '21 13:08 enochii

How can you distinguish between the two without static semantics because they are syntactically identical? Consider (*ppfunc)("hello").

package main

import "fmt"

func hello(m string){
       fmt.Println(m)
}

func main(){
       pfunc := hello
       ppfunc := &pfunc
       (*ppfunc)("hello")
}

kaby76 avatar Aug 16 '21 18:08 kaby76

But, the grammar--which is scraped from https://golang.org/ref/spec#Conversions --includes a production for Conversion.

primaryExpr:
	...
	| conversion
	...

conversion: type_ L_PAREN expression COMMA? R_PAREN;

And, type conversion is parsed as a function call, even through conversion is provided.

Code

package main
import "fmt"
func main(){
	x := bool(true)
	fmt.Println(x)
}

cat code | trparse | trxgrep ' //expression' | tree:

( expression
  ( primaryExpr
    ( primaryExpr
      ( operand
	( operandName
	  ( IDENTIFIER i=48 txt=bool tt=27 DEFAULT_TOKEN_CHANNEL
    ) ) ) )
    ( arguments
      ( L_PAREN i=52 txt=( tt=28 DEFAULT_TOKEN_CHANNEL
      )
      ( expressionList
	( expression
	  ( primaryExpr
	    ( operand
	      ( operandName
		( IDENTIFIER i=53 txt=true tt=27 DEFAULT_TOKEN_CHANNEL
      ) ) ) ) ) )
      ( R_PAREN i=57 txt=) tt=29 DEFAULT_TOKEN_CHANNEL
) ) ) )

The intent is for static semantics to be involved in the parse. Otherwise, why provide the conversion rule in the Spec?

kaby76 avatar Aug 16 '21 19:08 kaby76

Can it be closed?

KvanTTT avatar Mar 08 '22 12:03 KvanTTT