antlr / antlr4

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
http://antlr.org
BSD 3-Clause "New" or "Revised" License
17.22k stars 3.29k forks source link

[CSharp] Rules and labels that collide with C# keywords aren't escaped with a `@` prefix in all cases. #3503

Open NickStrupat opened 2 years ago

NickStrupat commented 2 years ago

It seems the keyword escaping is not working in this example grammar. I believe the left recursion is to blame. Demonstration code is below. I suspect it's around here but not sure: https://github.com/antlr/antlr4/blob/master/tool/resources/org/antlr/v4/tool/templates/codegen/CSharp/CSharp.stg#L934

Just run dotnet build and you'll see the syntax errors of the ANTLR-generated code.

Grammar.g4

grammar Grammar;

root: keyword+;

keyword
    : string=keyword id #str
    | base=keyword id   #b
    | id                #kw
    ;

id: Id;

Id: [A-Za-z]+;

A.cs (blank file)

A.csproj

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <NoWarn>108,3021</NoWarn>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Antlr4.Runtime.Standard" Version="4.9.3"/>
        <PackageReference Include="Antlr4BuildTasks" Version="8.17">
            <PrivateAssets>all</PrivateAssets>
        </PackageReference>
    </ItemGroup>

    <ItemGroup>
        <Antlr4 Include="Grammar.g4"/>
    </ItemGroup>

</Project>
KvanTTT commented 2 years ago

Thanks, we've fixed escaping for some cases, see https://github.com/antlr/antlr4/pull/3451 But another part is ongoing. It looks like your case is already covered in master (reserved string and base for labels).