Created
November 9, 2016 09:30
-
-
Save bergwerf/c2820ca6d59b1a33a63c7a3b10be1184 to your computer and use it in GitHub Desktop.
Dart math_expressions to eqlib conversion code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2016, Herman Bergwerf. All rights reserved. | |
// Use of this source code is governed by an AGPL-3.0-style license | |
// that can be found in the LICENSE file. | |
import 'package:eqlib/eqlib.dart'; | |
import 'package:eqlib/inline.dart'; | |
import 'package:math_expressions/math_expressions.dart' as mexpr; | |
/// Maps mexpr types to default function strings. | |
final _mexprMap = new Map<Type, String>.from({ | |
mexpr.Plus: 'add', | |
mexpr.Minus: 'sub', | |
mexpr.Times: 'mul', | |
mexpr.Divide: 'div' | |
}); | |
Expr exprFromMexpr(mexpr.Expression expr, ExprResolve resolver) { | |
if (expr is mexpr.Literal) { | |
// If the expression value is a string, resolve it, else create a numeric | |
// expression. | |
if (expr is mexpr.Variable) { | |
return new Expr(resolver(expr.name), false, []); | |
} else if (expr is mexpr.Number) { | |
return new Expr.numeric(expr.value); | |
} else { | |
throw new UnsupportedError( | |
'mexpr.Literal of type ${expr.runtimeType} is not supported.'); | |
} | |
} else if (expr is mexpr.UnaryMinus) { | |
return mul(-1, exprFromMexpr(expr.exp, resolver)); | |
} else if (expr is mexpr.BinaryOperator) { | |
// Try to resolve using _mexprMap. | |
if (_mexprMap.containsKey(expr.runtimeType)) { | |
return new Expr(resolver(_mexprMap[expr.runtimeType]), false, [ | |
exprFromMexpr(expr.first, resolver), | |
exprFromMexpr(expr.second, resolver) | |
]); | |
} else { | |
throw new UnimplementedError( | |
'mexpr.BinaryOperator of type ${expr.runtimeType} is not implemented'); | |
} | |
} else if (expr is mexpr.MathFunction) { | |
return new Expr( | |
resolver(expr.name), | |
false, | |
new List<Expr>.generate( | |
expr.args.length, (i) => exprFromMexpr(expr.args[i], resolver))); | |
} else { | |
throw new UnsupportedError( | |
'expr type ${expr.runtimeType} is not supported.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment