001package jmri.jmrit.logixng.util.parser;
002
003import java.util.*;
004
005/**
006 * Manager for LogixNG formula functions.
007 *
008 * @author Daniel Bergqvist   Copyright (C) 2020
009 */
010public class FunctionManager implements jmri.InstanceManagerAutoDefault {
011
012    private final Map<String, Constant> _constants = new HashMap<>();
013    private final Map<String, Function> _functions = new HashMap<>();
014
015
016    public FunctionManager() {
017        for (FunctionFactory actionFactory : ServiceLoader.load(FunctionFactory.class)) {
018            actionFactory.getConstants().forEach((constant) -> {
019                if (!constant.getModule().equals(actionFactory.getModule())) {
020                    log.error("Constant \"{}\" doesn't belong to the module \"{}\" of its declaring class {}",
021                            constant.getName(), actionFactory.getModule(), actionFactory.getClass().getName());
022                }
023                if (_constants.containsKey(constant.getName())) {
024                    throw new RuntimeException("Constant " + constant.getName() + " is already registered. Class: " + constant.getClass().getName());
025                }
026//                System.err.format("Add constant %s, %s%n", constant.getName(), constant.getClass().getName());
027                _constants.put(constant.getName(), constant);
028            });
029            actionFactory.getFunctions().forEach((function) -> {
030                if (!function.getModule().equals(actionFactory.getModule())) {
031                    log.error("Function \"{}\" doesn't belong to the module \"{}\" of its declaring class {}",
032                            function.getName(), actionFactory.getModule(), actionFactory.getClass().getName());
033                }
034                if (_functions.containsKey(function.getName())) {
035                    throw new RuntimeException("Function " + function.getName() + " is already registered. Class: " + function.getClass().getName());
036                }
037//                System.err.format("Add function %s, %s%n", function.getName(), function.getClass().getName());
038                _functions.put(function.getName(), function);
039            });
040        }
041    }
042
043    public Map<String, Function> getFunctions() {
044        return Collections.unmodifiableMap(_functions);
045    }
046
047    public Function get(String name) {
048        return _functions.get(name);
049    }
050
051    public Function put(String name, Function function) {
052        return _functions.put(name, function);
053    }
054
055    public Constant getConstant(String name) {
056        return _constants.get(name);
057    }
058
059    public void put(String name, Constant constant) {
060        _constants.put(name, constant);
061    }
062
063    private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(FunctionManager.class);
064}