UNPKG

3.54 kBJavaScriptView Raw
1import Expression from './expression';
2import Sequence from './sequence';
3import GrammarToRRDiagram from './grammartorrdiagram';
4import RRElement from '../ui/rrelement';
5import GrammarToBNF from './grammartobnf';
6import RRChoice from '../ui/rrchoice';
7
8export default class Choice extends Expression {
9
10 /**
11 * @param {Expression | Expression[]} expressions
12 */
13 constructor(expressions) {
14 super();
15 if (arguments.length == 0) {
16 expressions = [];
17 } else if (expressions.constructor !== Array) {
18 expressions = arguments;
19 }
20 this.expressions = expressions;
21 }
22
23 /**
24 * @return {Expression[]}
25 */
26 getExpressions() {
27 return this.expressions;
28 }
29
30 /**
31 * @param {GrammarToRRDiagram} grammarToRRDiagram
32 * @return {RRElement}
33 */
34 toRRElement(grammarToRRDiagram) {
35 const rrElements = [];
36 for (let expression of this.expressions) {
37 rrElements.push(expression.toRRElement(grammarToRRDiagram));
38 }
39 return new RRChoice(rrElements);
40 }
41
42 /**
43 * @param {GrammarToBNF} grammarToBNF
44 * @param {string[]} sb
45 * @param {boolean} isNested
46 */
47 toBNF(grammarToBNF, sb, isNested) {
48 const expressionList = [];
49 let hasNoop = false;
50 for (const expression of this.expressions) {
51 if (expression instanceof Sequence && expression.getExpressions().length == 0) {
52 hasNoop = true;
53 } else {
54 expressionList.push(expression);
55 }
56 }
57 if (expressionList.length == 0) {
58 sb.push("( )");
59 } else if (hasNoop && expressionList.length == 1) {
60 const isUsingMultiplicationTokens = grammarToBNF.isUsingMultiplicationTokens;
61 if (!isUsingMultiplicationTokens) {
62 sb.push("[ ");
63 }
64 expressionList[0].toBNF(grammarToBNF, sb, isUsingMultiplicationTokens);
65 if (!isUsingMultiplicationTokens) {
66 sb.push(" ]");
67 }
68 } else {
69 const isUsingMultiplicationTokens = grammarToBNF.isUsingMultiplicationTokens;
70 if (hasNoop && !isUsingMultiplicationTokens) {
71 sb.push("[ ");
72 } else if (hasNoop || isNested && expressionList.length > 1) {
73 sb.push("( ");
74 }
75 const count = expressionList.length;
76 for (let i = 0; i < count; i++) {
77 if (i > 0) {
78 sb.push(" | ");
79 }
80 expressionList[i].toBNF(grammarToBNF, sb, false);
81 }
82 if (hasNoop && !isUsingMultiplicationTokens) {
83 sb.push(" ]");
84 } else if (hasNoop || isNested && expressionList.length > 1) {
85 sb.push(" )");
86 if (hasNoop) {
87 sb.push("?");
88 }
89 }
90 }
91 }
92
93 /**
94 * @param {*} o
95 * @return {boolean}
96 */
97 equals(o) {
98 if(!(o instanceof Choice)) {
99 return false;
100 }
101 if(this.expressions.length != o.expressions.length) {
102 return false;
103 }
104 for (let i = 0; i < this.expressions.length; i++) {
105 if(!this.expressions[i].equals(o.expressions[i])) {
106 return false;
107 }
108 }
109 return true;
110 }
111
112}
\No newline at end of file