1 /*
2  * Copyright (c) 2018 Helmut Neemann.
3  * Use of this source code is governed by the GPL v3 license
4  * that can be found in the LICENSE file.
5  */
6 package de.neemann.digital.hdl.vhdl2;
7 
8 import de.neemann.digital.draw.library.ElementLibrary;
9 import de.neemann.digital.draw.library.ElementNotFoundException;
10 import de.neemann.digital.hdl.model2.HDLException;
11 import de.neemann.digital.hdl.model2.HDLNode;
12 import de.neemann.digital.hdl.vhdl2.entities.VHDLEntity;
13 import de.neemann.digital.hdl.vhdl2.entities.VHDLTemplate;
14 import de.neemann.digital.lang.Lang;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17 
18 import java.io.IOException;
19 import java.util.HashMap;
20 
21 /**
22  * The template library.
23  * Ensures that every template is only loaded once.
24  */
25 public class VHDLLibrary {
26     private static final Logger LOGGER = LoggerFactory.getLogger(VHDLLibrary.class);
27     private final ElementLibrary library;
28 
29     private HashMap<String, VHDLEntity> map;
30 
31     /**
32      * Creates a new library
33      *
34      * @param library the element library used
35      */
VHDLLibrary(ElementLibrary library)36     VHDLLibrary(ElementLibrary library) {
37         this.library = library;
38         map = new HashMap<>();
39     }
40 
41     /**
42      * Gets the entity of the given node
43      *
44      * @param node the node
45      * @return the entity
46      * @throws HDLException HDLException
47      */
getEntity(HDLNode node)48     public VHDLEntity getEntity(HDLNode node) throws HDLException {
49         String elementName = node.getElementName();
50         VHDLEntity e = map.get(elementName);
51         if (e == null) {
52             try {
53                 ClassLoader cl = null;
54                 try {
55                     cl = library.getElementType(elementName).getClassLoader();
56                 } catch (ElementNotFoundException ex) {
57                     // try default
58                 }
59                 e = new VHDLTemplate(elementName, cl);
60                 map.put(elementName, e);
61             } catch (IOException ex) {
62                 ex.printStackTrace();
63                 LOGGER.info("could not load '" + VHDLTemplate.neededFileName(elementName) + "'");
64             }
65         }
66 
67         if (e == null)
68             throw new HDLException(Lang.get("err_vhdlNoEntity_N", elementName));
69         return e;
70     }
71 }
72