1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.millscript.millscript.expr;
23
24 import org.millscript.millscript.action.CheckAction;
25 import org.millscript.millscript.alert.Alerts;
26 import org.millscript.millscript.vm.CompilerState;
27
28 /**
29 * This class implements a check expression. A check expression is guaranteed to
30 * return one result.
31 *
32 * @see CheckAction
33 */
34 public final class CheckExpr extends Expr< CheckAction > {
35
36 /**
37 * Returns an expression that is guaranteed to return a single result. This
38 * method provides some compile-time optimisation, as it avoids creating
39 * additional unnecessary objects in the expression tree. If the specified
40 * expression already returns a single result, it is simply returned,
41 * otherwise if it returns an unknown number of results, a new check
42 * expression is created.
43 *
44 * @param e the expression which must return a single result
45 * @return the specified expression if it already returns a single
46 * result, otherwise a new {@link CheckExpr}
47 */
48 public static Expr< ? > make( final Expr< ? > e ) {
49 int n = e.arity();
50 if ( n == 1 ) {
51 return e;
52 } else if ( n < 0 ) {
53 return new CheckExpr( e );
54 } else {
55 throw(
56 Alerts.compile(
57 "Arity mismatch (" + n + " results)",
58 "This expression must return one result"
59 ).culprit( "expression", e ).mishap()
60 );
61 }
62 }
63
64 /**
65 * The expression which must return a single result.
66 */
67 private final Expr< ? > cont;
68
69 /**
70 * Creates a new check expression, to check the specified expression returns
71 * a single result.
72 *
73 * @param e the expression which must return a single result
74 */
75 public CheckExpr( final Expr< ? > e ) {
76 cont = e;
77 }
78
79 /**
80 * @see org.millscript.millscript.expr.Expr#compileIt()
81 */
82 @Override
83 public CheckAction compileIt() {
84 return new CheckAction( cont.compile() );
85 }
86
87 /**
88 * @see org.millscript.millscript.expr.Expr#resolve(org.millscript.millscript.vm.CompilerState)
89 */
90 @Override
91 public void resolve( final CompilerState state ) {
92 this.cont.resolve( state );
93 }
94
95 /**
96 * @see org.millscript.millscript.expr.Expr#showComponents(int)
97 */
98 @Override
99 void showComponents( final int n ) {
100 this.cont.show( n );
101 }
102
103 }