1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | 'use strict';
|
15 |
|
16 | const fsPath = require('path');
|
17 |
|
18 | const RelationshipDeclaration = require('composer-concerto').RelationshipDeclaration;
|
19 |
|
20 | const Writer = require('composer-concerto').Writer;
|
21 |
|
22 | const Logger = require('@accordproject/ergo-compiler').Logger;
|
23 |
|
24 | const nearley = require('nearley');
|
25 |
|
26 | const compile = require('nearley/lib/compile');
|
27 |
|
28 | const generate = require('nearley/lib/generate');
|
29 |
|
30 | const nearleyGrammar = require('nearley/lib/nearley-language-bootstrapped');
|
31 |
|
32 | const templateGrammar = require('./tdl.js');
|
33 |
|
34 | const GrammarVisitor = require('./grammarvisitor');
|
35 |
|
36 | const uuid = require('uuid');
|
37 |
|
38 | const nunjucks = require('nunjucks');
|
39 |
|
40 | const DateTimeFormatParser = require('./datetimeformatparser');
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | if (process.browser) {
|
47 | require('./compiled_template');
|
48 | }
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | class ParserManager {
|
58 | |
59 |
|
60 |
|
61 |
|
62 | constructor(template) {
|
63 | this.template = template;
|
64 | this.grammar = null;
|
65 | this.grammarAst = null;
|
66 | this.templatizedGrammar = null;
|
67 | this.templateAst = null;
|
68 | }
|
69 | |
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 | getParser() {
|
76 | if (!this.grammarAst) {
|
77 | throw new Error('Must call setGrammar or buildGrammar before calling getParser');
|
78 | }
|
79 |
|
80 | return new nearley.Parser(nearley.Grammar.fromCompiled(this.grammarAst));
|
81 | }
|
82 | |
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 | getTemplateAst() {
|
89 | if (!this.grammarAst) {
|
90 | throw new Error('Must call setGrammar or buildGrammar before calling getTemplateAst');
|
91 | }
|
92 |
|
93 | return this.templateAst;
|
94 | }
|
95 | |
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 | setGrammar(grammar) {
|
102 | this.grammarAst = ParserManager.compileGrammar(grammar);
|
103 | this.grammar = grammar;
|
104 | }
|
105 | |
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 | buildGrammar(templatizedGrammar) {
|
112 | Logger.debug('buildGrammar', templatizedGrammar);
|
113 | const parser = new nearley.Parser(nearley.Grammar.fromCompiled(templateGrammar));
|
114 | parser.feed(templatizedGrammar);
|
115 |
|
116 | if (parser.results.length !== 1) {
|
117 | throw new Error('Ambiguous parse!');
|
118 | }
|
119 |
|
120 |
|
121 | const ast = parser.results[0];
|
122 | this.templateAst = ast;
|
123 | Logger.debug('Template AST', ast);
|
124 | const parts = {
|
125 | textRules: [],
|
126 | modelRules: [],
|
127 | grammars: {}
|
128 | };
|
129 | parts.grammars.base = require('./grammars/base');
|
130 | this.buildGrammarRules(ast, this.template.getTemplateModel(), 'rule', parts);
|
131 |
|
132 | const parameters = {
|
133 | writer: new Writer(),
|
134 | rules: []
|
135 | };
|
136 | const gv = new GrammarVisitor();
|
137 | this.template.getModelManager().accept(gv, parameters);
|
138 | parts.modelRules.push(...parameters.rules);
|
139 |
|
140 | nunjucks.configure(fsPath.resolve(__dirname), {
|
141 | tags: {
|
142 | blockStart: '<%',
|
143 | blockEnd: '%>'
|
144 | },
|
145 | autoescape: false
|
146 |
|
147 | });
|
148 | const combined = nunjucks.render('template.ne', parts);
|
149 | Logger.debug('Generated template grammar' + combined);
|
150 |
|
151 | this.setGrammar(combined);
|
152 | this.templatizedGrammar = templatizedGrammar;
|
153 | }
|
154 | |
155 |
|
156 |
|
157 |
|
158 |
|
159 |
|
160 |
|
161 |
|
162 |
|
163 | buildGrammarRules(ast, templateModel, prefix, parts) {
|
164 |
|
165 | const rules = {};
|
166 |
|
167 | let textRules = {};
|
168 |
|
169 | textRules.prefix = prefix;
|
170 | textRules.symbols = [];
|
171 | ast.data.forEach((element, index) => {
|
172 |
|
173 | if (element && (element.type !== 'Chunk' || element.value.length > 0)) {
|
174 | Logger.debug("element ".concat(prefix).concat(index, " ").concat(JSON.stringify(element)));
|
175 | rules[prefix + index] = element;
|
176 | textRules.symbols.push(prefix + index);
|
177 | }
|
178 | }, this);
|
179 |
|
180 | textRules.class = templateModel.getFullyQualifiedName();
|
181 | const identifier = templateModel.getIdentifierFieldName();
|
182 |
|
183 | if (identifier !== null) {
|
184 | textRules.identifier = "".concat(identifier, " : \"").concat(uuid.v4(), "\"");
|
185 | }
|
186 |
|
187 |
|
188 |
|
189 | textRules.properties = [];
|
190 | templateModel.getProperties().forEach((property, index) => {
|
191 | const sep = index < templateModel.getProperties().length - 1 ? ',' : '';
|
192 | const bindingIndex = this.findFirstBinding(property.getName(), ast.data);
|
193 |
|
194 | if (bindingIndex !== -1) {
|
195 |
|
196 |
|
197 | textRules.properties.push("".concat(property.getName(), " : ").concat(prefix).concat(bindingIndex).concat(sep));
|
198 | }
|
199 | });
|
200 | parts.textRules.push(textRules);
|
201 |
|
202 | for (let rule in rules) {
|
203 | const element = rules[rule];
|
204 |
|
205 | switch (element.type) {
|
206 | case 'Chunk':
|
207 | case 'LastChunk':
|
208 | parts.modelRules.push({
|
209 | prefix: rule,
|
210 | symbols: [this.cleanChunk(element.value)]
|
211 | });
|
212 | break;
|
213 |
|
214 | case 'BooleanBinding':
|
215 | {
|
216 | const property = ParserManager.getProperty(templateModel, element.fieldName.value);
|
217 |
|
218 | if (property.getType() !== 'Boolean') {
|
219 | throw new Error("A boolean binding can only be used with a boolean property. Property ".concat(element.fieldName.value, " has type ").concat(property.getType()));
|
220 | }
|
221 |
|
222 | parts.modelRules.push({
|
223 | prefix: rule,
|
224 | symbols: ["".concat(element.string.value, ":? {% (d) => {return d[0] !== null;}%} # ").concat(element.fieldName.value)]
|
225 | });
|
226 | }
|
227 | break;
|
228 |
|
229 | case 'FormattedBinding':
|
230 | case 'Binding':
|
231 | case 'ClauseBinding':
|
232 | this.handleBinding(templateModel, parts, rule, element);
|
233 | break;
|
234 |
|
235 | default:
|
236 | throw new Error("Unrecognized type ".concat(element.type));
|
237 | }
|
238 | }
|
239 | }
|
240 | |
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 |
|
247 |
|
248 | static getProperty(templateModel, propertyName) {
|
249 | const property = templateModel.getProperty(propertyName);
|
250 |
|
251 | if (!property) {
|
252 | throw new Error("Template references a property '".concat(propertyName, "' that is not declared in the template model '").concat(templateModel.getFullyQualifiedName(), "'"));
|
253 | }
|
254 |
|
255 | return property;
|
256 | }
|
257 | |
258 |
|
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 |
|
265 |
|
266 | handleBinding(templateModel, parts, inputRule, element) {
|
267 | const propertyName = element.fieldName.value;
|
268 | const property = ParserManager.getProperty(templateModel, propertyName);
|
269 | let action = null;
|
270 | let suffix = ':';
|
271 | let type = property.getType();
|
272 |
|
273 | const decorator = property.getDecorator('AccordType');
|
274 |
|
275 | if (decorator) {
|
276 | if (decorator.getArguments().length > 0) {
|
277 | type = decorator.getArguments()[0];
|
278 | }
|
279 |
|
280 | if (decorator.getArguments().length > 1) {
|
281 | action = decorator.getArguments()[1];
|
282 | }
|
283 | }
|
284 |
|
285 |
|
286 | if (!action) {
|
287 | action = '{% id %}';
|
288 |
|
289 | if (element.type === 'FormattedBinding') {
|
290 | if (property.getType() !== 'DateTime') {
|
291 | throw new Error('Formatted types are currently only supported for DateTime properties.');
|
292 | }
|
293 |
|
294 |
|
295 | if (!parts.grammars.dateTime) {
|
296 | parts.grammars.dateTime = require('./grammars/datetime');
|
297 | parts.grammars.dateTimeEn = require('./grammars/datetime-en');
|
298 | }
|
299 |
|
300 |
|
301 | const formatRule = DateTimeFormatParser.buildDateTimeFormatRule(element.format.value);
|
302 | type = formatRule.name;
|
303 | const ruleExists = parts.modelRules.some(rule => rule.prefix === formatRule.name);
|
304 |
|
305 | if (!ruleExists) {
|
306 | parts.modelRules.push({
|
307 | prefix: formatRule.name,
|
308 | symbols: ["".concat(formatRule.tokens, " ").concat(formatRule.action, " # ").concat(propertyName, " as ").concat(element.format.value)]
|
309 | });
|
310 | }
|
311 | } else if (element.type === 'ClauseBinding') {
|
312 | const clauseTemplate = element.template;
|
313 | const clauseTemplateModel = this.template.getIntrospector().getClassDeclaration(property.getFullyQualifiedTypeName());
|
314 | this.buildGrammarRules(clauseTemplate, clauseTemplateModel, propertyName, parts);
|
315 | type = element.fieldName.value;
|
316 | } else {
|
317 |
|
318 | if (property instanceof RelationshipDeclaration) {
|
319 | type = 'String';
|
320 | }
|
321 | }
|
322 | }
|
323 |
|
324 | if (property.isArray()) {
|
325 | suffix += '+';
|
326 | }
|
327 |
|
328 | if (property.isOptional()) {
|
329 | suffix += '?';
|
330 | }
|
331 |
|
332 | if (suffix === ':') {
|
333 | suffix = '';
|
334 | }
|
335 |
|
336 |
|
337 | parts.modelRules.push({
|
338 | prefix: inputRule,
|
339 | symbols: ["".concat(type).concat(suffix, " ").concat(action, " # ").concat(propertyName)]
|
340 | });
|
341 | }
|
342 | |
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 | cleanChunk(input) {
|
353 |
|
354 | let text = input.replace(/\r?\n|\r/gm, '\\n');
|
355 |
|
356 | text = text.replace(/"/gm, '\\"');
|
357 | return "\"".concat(text, "\"");
|
358 | }
|
359 | |
360 |
|
361 |
|
362 |
|
363 |
|
364 |
|
365 |
|
366 |
|
367 |
|
368 | findFirstBinding(propertyName, elements) {
|
369 | for (let n = 0; n < elements.length; n++) {
|
370 | const element = elements[n];
|
371 |
|
372 | if (element !== null && ['Binding', 'FormattedBinding', 'BooleanBinding', 'ClauseBinding'].includes(element.type)) {
|
373 | if (element.fieldName.value === propertyName) {
|
374 | return n;
|
375 | }
|
376 | }
|
377 | }
|
378 |
|
379 | return -1;
|
380 | }
|
381 | |
382 |
|
383 |
|
384 |
|
385 |
|
386 |
|
387 | getGrammar() {
|
388 | return this.grammar;
|
389 | }
|
390 | |
391 |
|
392 |
|
393 |
|
394 |
|
395 |
|
396 | getTemplatizedGrammar() {
|
397 | return this.templatizedGrammar;
|
398 | }
|
399 | |
400 |
|
401 |
|
402 |
|
403 |
|
404 |
|
405 |
|
406 | static compileGrammar(sourceCode) {
|
407 | try {
|
408 |
|
409 | const grammarParser = new nearley.Parser(nearleyGrammar);
|
410 | grammarParser.feed(sourceCode);
|
411 | const grammarAst = grammarParser.results[0];
|
412 |
|
413 |
|
414 | const grammarInfoObject = compile(grammarAst, {});
|
415 |
|
416 | const grammarJs = generate(grammarInfoObject, 'grammar');
|
417 |
|
418 | const module = {
|
419 | exports: {}
|
420 | };
|
421 | eval(grammarJs);
|
422 | return module.exports;
|
423 | } catch (err) {
|
424 | Logger.error(err);
|
425 | throw err;
|
426 | }
|
427 | }
|
428 |
|
429 | }
|
430 |
|
431 | module.exports = ParserManager; |
\ | No newline at end of file |