antlr / antlr/antlr4

[Swift] invalid swift generated for Dynamically-Scoped Attributes

Open
#4,476 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
19k
Forks
3.5k
PR merge metrics
No merged PRs in 30d

Description

when using the (slightly altered for swift) grammar from the [doc](https://github.com/antlr/antlr4/blob/master/doc/actions.md#dynamically-scoped-attributes)

```
grammar DynScope;

prog: block ;

block
/* List of symbols defined within this block */
locals [
symbols: [String]
]
: '{' decl* stat+ '}'
// print out all symbols found in block
// $block::symbols evaluates to a List as defined in scope
{print("symbols=\($symbols)");}
;

/** Match a declaration and add identifier name to list of symbols */
decl: 'int' ID {$block::symbols.append($ID.text);} ';' ;

/** Match an assignment then test list of symbols to verify
* that it contains the variable on the left side of the assignment.
* Method contains() is List.contains() because $block::symbols
* is a List.
*/
stat: ID '=' INT ';'
{
if ( !$block::symbols.contains($ID.text) ) {
print("undefined variable: "+$ID.text);
}
}
| block
;

ID : [a-z]+ ;
INT : [0-9]+ ;
WS : [ \t\r\n]+ -> skip ;

```

the generated code is:
`(BlockContext)getInvokingContext(1)).symbols.append((_localctx.castdown(DeclContext.self)._ID != nil ? _localctx.castdown(DeclContext.self)._ID!.getText()! : ""));`
which uses an invalid c-style cast.

it should generate something like:
`(getInvokingContext(1) as! BlockContext).symbols.append((_localctx.castdown(DeclContext.self)._ID != nil ? _localctx.castdown(DeclContext.self)._ID!.getText()! : ""));`

Contributor guide

Open the contributing guide

Research direction

Start with the dynamically scoped attributes example in doc/actions.md and reproduce the grammar using the Swift target. Trace the generated output containing `(BlockContext)getInvokingContext(1)` and verify that the completed output uses valid Swift casting while preserving the surrounding expression.

Written by the indexing model from the issue text.

Assessment

Tech stack
swift
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.