Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix class fields using constructors not transpiling correctly #933

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/files/BrsFile.Class.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,44 @@ describe('BrsFile BrighterScript classes', () => {
end function
`, 'trim', 'source/main.bs');
});


it('adds namespacing to constructors on field definitions', async () => {
await testTranspile(`
namespace MyNS
class KlassOne
other = new KlassTwo()
end class

class KlassTwo
end class
end namespace
`, `
function __MyNS_KlassOne_builder()
instance = {}
instance.new = sub()
m.other = MyNS_KlassTwo()
end sub
return instance
end function
function MyNS_KlassOne()
instance = __MyNS_KlassOne_builder()
instance.new()
return instance
end function
function __MyNS_KlassTwo_builder()
instance = {}
instance.new = sub()
end sub
return instance
end function
function MyNS_KlassTwo()
instance = __MyNS_KlassTwo_builder()
instance.new()
return instance
end function
`, 'trim', 'source/main.bs');
});
});

it('detects using `new` keyword on non-classes', () => {
Expand Down
23 changes: 10 additions & 13 deletions src/parser/Statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2305,20 +2305,17 @@ export class MethodStatement extends FunctionStatement {
for (let field of state.classStatement.fields) {
let thisQualifiedName = { ...field.name };
thisQualifiedName.text = 'm.' + field.name.text;
if (field.initialValue) {
newStatements.push(
new AssignmentStatement(field.equal, thisQualifiedName, field.initialValue)
const fieldAssignment = field.initialValue
? new AssignmentStatement(field.equal, thisQualifiedName, field.initialValue)
: new AssignmentStatement(
createToken(TokenKind.Equal, '=', field.name.range),
thisQualifiedName,
//if there is no initial value, set the initial value to `invalid`
createInvalidLiteral('invalid', field.name.range)
);
} else {
//if there is no initial value, set the initial value to `invalid`
newStatements.push(
new AssignmentStatement(
createToken(TokenKind.Equal, '=', field.name.range),
thisQualifiedName,
createInvalidLiteral('invalid', field.name.range)
)
);
}
// Add parent so namespace lookups work
fieldAssignment.parent = state.classStatement;
newStatements.push(fieldAssignment);
}
state.editor.arraySplice(this.func.body.statements, startingIndex, 0, ...newStatements);
}
Expand Down