]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.spreadsheet.graph/src/org/simantics/spreadsheet/graph/formula/IfFormulaFunction.java
2d2ef8c5b74e9ce41a5398b7629e98320dae6cc3
[simantics/platform.git] / bundles / org.simantics.spreadsheet.graph / src / org / simantics / spreadsheet / graph / formula / IfFormulaFunction.java
1 package org.simantics.spreadsheet.graph.formula;
2
3 import org.simantics.spreadsheet.graph.CellFormulaFunction;
4 import org.simantics.spreadsheet.graph.CellValueVisitor;
5 import org.simantics.spreadsheet.graph.SpreadsheetGraphUtils;
6 import org.simantics.spreadsheet.graph.parser.ast.AstArgList;
7 import org.simantics.spreadsheet.graph.parser.ast.AstNothing;
8 import org.simantics.spreadsheet.graph.parser.ast.AstValue;
9
10 public class IfFormulaFunction implements CellFormulaFunction<Object> {
11
12     @Override
13     public Object evaluate(CellValueVisitor visitor, AstArgList args) {
14         if (args.values.size() != 3) throw new IllegalStateException();
15         
16         Object condition = args.values.get(0).accept(visitor);
17         AstValue ifTrueResult = args.values.get(1);
18         AstValue ifFalseResult = args.values.get(2);
19         
20         FormulaError2 error = FormulaError2.forObject(condition);
21                 if(error!=null) return error.getString();
22
23         if (SpreadsheetGraphUtils.asBoolean(condition)) {
24             if(ifTrueResult==null || ifTrueResult instanceof AstNothing)
25                 return 0;
26             try {
27                 return ifTrueResult.accept(visitor);
28             } catch (IllegalStateException e){
29                 return FormulaError2.NAME.getString();
30             }
31         }
32         else {
33             if(ifFalseResult==null || ifFalseResult instanceof AstNothing)
34                 return 0;
35             try {
36                 return ifFalseResult.accept(visitor);
37             } catch (IllegalStateException e){
38                 return FormulaError2.NAME.getString();
39             }
40         }
41     }
42 }