1 /*
2 * Copyright 2020-2022 Foreseeti AB <https://foreseeti.com>
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.mal_lang.langspec.ttc;
18
19 import static java.util.Objects.requireNonNull;
20
21 import jakarta.json.JsonObject;
22
23 /**
24 * Immutable class representing a TTC expression in a MAL language.
25 *
26 * @since 1.0.0
27 */
28 public abstract class TtcExpression {
29 /**
30 * Returns the mean TTC of this {@code TtcExpression} object.
31 *
32 * @return the mean TTC of this {@code TtcExpression} object
33 * @throws java.lang.UnsupportedOperationException if this {@code TtcExpression} does not support
34 * mean TTC
35 * @since 1.0.0
36 */
37 public double getMeanTtc() {
38 throw new UnsupportedOperationException();
39 }
40
41 /**
42 * Returns the mean probability of this {@code TtcExpression} object.
43 *
44 * @return the mean probability of this {@code TtcExpression} object
45 * @throws java.lang.UnsupportedOperationException if this {@code TtcExpression} does not support
46 * mean probability
47 * @since 1.0.0
48 */
49 public double getMeanProbability() {
50 throw new UnsupportedOperationException();
51 }
52
53 /**
54 * Returns the JSON representation of this {@code TtcExpression} object.
55 *
56 * @return the JSON representation of this {@code TtcExpression} object
57 * @since 1.0.0
58 */
59 public abstract JsonObject toJson();
60
61 /**
62 * Creates a new {@code TtcExpression} from a {@link jakarta.json.JsonObject}.
63 *
64 * @param jsonTtcExpression the {@link jakarta.json.JsonObject}
65 * @return a new {@code TtcExpression}
66 * @throws java.lang.NullPointerException if {@code jsonTtcExpression} is {@code null}
67 * @since 1.0.0
68 */
69 public static TtcExpression fromJson(JsonObject jsonTtcExpression) {
70 requireNonNull(jsonTtcExpression);
71 switch (jsonTtcExpression.getString("type")) {
72 case "addition":
73 case "subtraction":
74 case "multiplication":
75 case "division":
76 case "exponentiation":
77 return TtcBinaryOperation.fromJson(jsonTtcExpression);
78 case "function":
79 return TtcFunction.fromJson(jsonTtcExpression);
80 case "number":
81 return TtcNumber.fromJson(jsonTtcExpression);
82 default:
83 throw new RuntimeException(
84 String.format(
85 "Invalid TTC expression type \"%s\"", jsonTtcExpression.getString("type")));
86 }
87 }
88 }