-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathComponentStatementProvider.ts
More file actions
207 lines (189 loc) · 9.48 KB
/
Copy pathComponentStatementProvider.ts
File metadata and controls
207 lines (189 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import undent from 'undent';
import { createVisitor, WalkMode } from '../../astUtils/visitors';
import type { BrsFile } from '../../files/BrsFile';
import { ParseMode } from '../../parser/Parser';
import type { ComponentStatement, FunctionStatement } from '../../parser/Statement';
import { Cache } from '../../Cache';
import * as path from 'path';
import { util } from '../../util';
import type { ProvideFileEvent } from '../../interfaces';
import { isDottedGetExpression, isFieldStatement, isMethodStatement, isVariableExpression, isLiteralExpression, isTemplateStringExpression, isAnnotationExpression } from '../../astUtils/reflection';
import { createFunctionStatement, createFunctionExpression, createDottedSetStatement, createVariableExpression } from '../../astUtils/creators';
import type { Statement } from '../../parser/AstNode';
import { TokenKind } from '../../lexer/TokenKind';
import { VariableExpression } from '../../parser/Expression';
import type { AnnotationExpression } from '../../parser/Expression';
export class ComponentStatementProvider {
constructor(
private event: ProvideFileEvent
) {
}
/**
* Create virtual files for every component statement found in this physical file
*/
public process(file: BrsFile) {
const cache = new Cache<string, string>();
file.ast.walk(createVisitor({
ComponentStatement: (node) => {
//force the destPath for this component to be within the `pkg:/components` folder
const destDir = cache.getOrAdd(file.srcPath, () => {
return path.dirname(file.destPath).replace(/^(.+?)(?=[\/\\]|$)/, (match: string, firstDirName: string) => {
return 'components';
});
});
this.registerComponent(file, node, destDir);
}
}), {
walkMode: WalkMode.visitStatements
});
}
private registerComponent(file: BrsFile, statement: ComponentStatement, destDir: string) {
let name = statement.getName(ParseMode.BrightScript);
const codebehindFile = this.registerCodebehind(name, statement, destDir);
const xmlFile = this.event.fileFactory.XmlFile({
srcPath: `virtual:/${destDir}/${name}.xml`,
destPath: `${destDir}/${name}.xml`
});
const interfaceMembers = statement.getMembers().map((member) => {
//declare interface function
if (isMethodStatement(member) && member.accessModifier?.text.toLowerCase() === 'public') {
return `<function name="${member.name.text}" />`;
//declare interface field
} else if (isFieldStatement(member) && member.accessModifier?.text.toLowerCase() === 'public') {
return this.generateTagWithAttributes('field', {
id: member.name.text,
type: member.typeExpression.getName(),
alias: this.getAnnotationValue(member.annotations?.filter(x => x.name.toLowerCase() === 'alias')),
onChange: this.getAnnotationValue(member.annotations?.filter(x => x.name.toLowerCase() === 'onchange')),
alwaysNotify: this.getAnnotationValue(member.annotations?.filter(x => x.name.toLowerCase() === 'alwaysnotify')) === 'true' ? 'true' : ''
}, true);
} else {
return '';
}
}).filter(x => !!x);
let componentChildren = '';
const template = statement.annotations?.find(x => x.name.toLowerCase() === 'template');
if (isAnnotationExpression(template)) {
// TODO: Better strip of component and children elements.
componentChildren = `<children>${this.getAnnotationValue([template]).replaceAll('<component>', '').replaceAll('</component>', '').replaceAll('<children>', '').replaceAll('</children>', '')}</children>`;
}
let componentAttributes = {
name: name,
extends: statement.getParentName(ParseMode.BrightScript) ?? 'Group',
initialFocus: ''
};
const initialFocus = statement.annotations?.find(x => x.name.toLowerCase() === 'initialfocus');
if (isAnnotationExpression(initialFocus)) {
componentAttributes.initialFocus = this.getAnnotationValue([initialFocus]);
}
xmlFile.parse(undent`
${this.generateTagWithAttributes('component', componentAttributes)};
<script uri="${util.sanitizePkgPath(file.destPath)}" />
<script uri="${util.sanitizePkgPath(codebehindFile.destPath)}" />
${interfaceMembers.length > 0 ? '<interface>' : ''}
${interfaceMembers.join('\n ')}
${interfaceMembers.length > 0 ? '</interface>' : ''}
${componentChildren}
</component>
`);
this.event.files.push(xmlFile);
}
private generateTagWithAttributes(identifier = '' as string, attributes = {} as Record<string, any>, closeEnd = false as boolean) {
let tag = `<${identifier}`;
Object.keys(attributes).forEach(attribute => {
let value = attributes[attribute];
// Only add a attribute if the value is not empty.
if (value !== '') {
tag += ` ${attribute}="${attributes[attribute]}"`;
}
});
tag += closeEnd ? ' />': ' >';
return tag;
}
private getAnnotationValue(annotations: AnnotationExpression[]) {
let response = [];
if (annotations !== undefined) {
for (const annotation of annotations) {
let args = annotation?.call?.args[0];
if (isVariableExpression(args) || isDottedGetExpression(args)) {
response.push(args.name.text);
} else if (isLiteralExpression(args)) {
let values = args?.token?.text.replaceAll('\"', '').replaceAll(' ', '').split(',');
response = response.concat(values);
} else if (isTemplateStringExpression(args)) {
let textOutput = '';
args.quasis[0]?.expressions?.forEach((a: { token: { text: string } }) => {
textOutput += a.token.text;
});
response.push(textOutput);
}
}
response = response.filter((item, index) => response.indexOf(item) === index);
}
return response.join(', ');
}
private registerCodebehind(name: string, statement: ComponentStatement, destDir: string) {
//create the codebehind file
const file = this.event.fileFactory.BrsFile({
srcPath: `virtual:/${destDir}/${name}.codebehind.bs`,
destPath: `${destDir}/${name}.codebehind.bs`,
pkgPath: `${destDir}/${name}.codebehind.brs`
});
const initStatements: Statement[] = [];
let initFunc: FunctionStatement;
//create AST from all the fields and methods in the component statement
for (const member of statement.getMembers()) {
if (isMethodStatement(member)) {
const func = createFunctionStatement(member.name, member.func);
//convert the method into a standard function
file.ast.statements.push(func);
if (member?.name?.text.toLowerCase() === 'init') {
initFunc = func;
}
this.rewriteMAccess(func);
//if this is a private field, and it has a value
} else if (isFieldStatement(member) && member.accessModifier?.text.toLowerCase() === 'private' && member.initialValue) {
//add private fields to the global m
initStatements.push(
createDottedSetStatement(
createVariableExpression('m'),
member.name.text,
member.initialValue
)
);
}
}
//push statements to the start of `init()`
if (initStatements.length > 0) {
//create the `init` function if it doesn't exist
if (!initFunc) {
initFunc = createFunctionStatement('init',
createFunctionExpression(TokenKind.Sub)
);
file.ast.statements.unshift(initFunc);
initFunc.func.getSymbolTable().pushParentProvider(() => statement.getSymbolTable());
}
initFunc.func.body.statements.unshift(...initStatements);
}
//TODO these are hacks that we need until scope has been refactored to leverage the AST directly
file.parser.invalidateReferences();
// eslint-disable-next-line @typescript-eslint/dot-notation
file['findCallables']();
// eslint-disable-next-line @typescript-eslint/dot-notation
file['findFunctionCalls']();
this.event.files.push(file);
return file;
}
private rewriteMAccess(func: FunctionStatement) {
func.func.body.walk(createVisitor({
CallExpression: (call) => {
//if this is a `m.doSomething()` call, rewrite it to call the root level method
if (isDottedGetExpression(call.callee) && isVariableExpression(call.callee.obj) && call.callee.obj.name.text?.toLowerCase() === 'm') {
call.callee = new VariableExpression(call.callee.name);
}
}
}), {
walkMode: WalkMode.visitAll
});
}
}