Exemplo n.º 1
0
  private Var retrieveFnAsVar(String fn) throws Exception {
    String format = "Function %s not found in namespace %s";
    String ns, rawFn;

    if (fn.indexOf('/') == -1) {
      ns = itsNSOwner.getNS();
      rawFn = fn;
    } else {
      String[] names = fn.split("/");
      ns = names[0];
      rawFn = names[1];
    }

    // Var var = RT.var(ns, rawFn);
    Namespace namespace = Namespace.find(Symbol.intern(ns));

    if (namespace == null) {
      throw new IllegalArgumentException("No such namespace: " + ns);
    }

    Var var = namespace.findInternedVar(Symbol.intern(rawFn));

    if (var == null) {
      String msg = String.format(format, rawFn, ns);
      throw new NoSuchMethodException(msg);
    } else {
      return var;
    }
  }
  private void put(String name, Object value) {
    //	This is largely cargo-culting.
    if (name.indexOf('.') == -1) {
      String nsName = "user";
      if (name.indexOf('/') >= 0) {
        String[] names = name.split("/");
        nsName = names[0];
        name = names[1];
      }

      Var.intern(
          Namespace.findOrCreate(Symbol.create(nsName.intern())),
          Symbol.create(name.intern()),
          value);
    }
  }
Exemplo n.º 3
0
 public void onCreate(android.os.Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   RT.var("clojure.core", "require").invoke(Symbol.intern("hello-world.core"));
   try {
     Game game = (Game) RT.var("hello-world.core", "hello-world").deref();
     initialize(game);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 4
0
  protected static Var loadVar(String namespace, String varName) {
    try {
      Symbol namespaceSymbol = Symbol.intern(namespace);
      Namespace ns = Namespace.find(namespaceSymbol);
      if (ns != null) return (Var) ns.getMapping(Symbol.create(varName));

      RT.load(namespace, false);

      ns = Namespace.find(namespaceSymbol);
      if (ns != null) return (Var) ns.getMapping(Symbol.create(varName));

      final String coreFilename = Clj.nsToFilename(namespace);
      RT.loadResourceScript(coreFilename);
      ns = Namespace.find(namespaceSymbol);
      if (ns != null) return (Var) ns.getMapping(Symbol.create(varName));

      throw new RuntimeException(
          "var still not found after load attempts: " + namespace + "/" + varName);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("Failed to load var:" + namespace + "/" + varName, e);
    }
  }
/** This is raw Clojure, not JSR-223. */
public class NativeClojureSearchTests {
  private static final Symbol USER_SYM = Symbol.create("user");
  private static final Var IN_NS = RT.var("clojure.core", "in-ns");

  private void extendClasspath(File newDir) throws Exception {
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();

    URLClassLoader urlClassLoader =
        new URLClassLoader(new URL[] {newDir.toURI().toURL()}, currentClassLoader);

    Thread.currentThread().setContextClassLoader(urlClassLoader);
  }

  private Object run(File file) throws Exception {
    Reader reader = null;

    try {
      reader = new FileReader(file);

      Var.pushThreadBindings(
          RT.map(
              RT.CURRENT_NS,
              RT.CURRENT_NS.deref(),
              RT.IN,
              new LineNumberingPushbackReader(reader),
              RT.OUT,
              new OutputStreamWriter(System.out),
              RT.ERR,
              new OutputStreamWriter(System.err)));

      IN_NS.invoke(USER_SYM);
      return Compiler.load(reader);
    } finally {
      Var.popThreadBindings();
    }
  }

  private void put(String name, Object value) {
    //	This is largely cargo-culting.
    if (name.indexOf('.') == -1) {
      String nsName = "user";
      if (name.indexOf('/') >= 0) {
        String[] names = name.split("/");
        nsName = names[0];
        name = names[1];
      }

      Var.intern(
          Namespace.findOrCreate(Symbol.create(nsName.intern())),
          Symbol.create(name.intern()),
          value);
    }
  }

  private Object find00(String name) {
    for (ISeq seq = Namespace.all(); seq != null; seq = seq.next()) {
      Namespace ns = (Namespace) seq.first();
      String nsName = ns.toString();
      if (nsName.startsWith("clojure")) continue;

      for (ISeq mseq = ns.getMappings().seq(); mseq != null; mseq = mseq.next()) {
        IMapEntry e = (IMapEntry) mseq.first();
        String k = e.getKey().toString();
        if (k.equals(name)) {
          Object val = e.getValue();
          if (val.toString().startsWith("#'clojure")) continue;
          if (val instanceof Var) {
            val = ((Var) val).deref();
            return val;
          }
        }
      }
    }

    return null;
  }

  @Test
  public void loadViaClasspath() throws Exception {
    ResourceBundle bundle = ResourceBundle.getBundle("net.loadbang.clojure.props.TEST_CONFIG");
    String baseDir = bundle.getString("TEST_SCRIPT_BASE");
    System.out.println(baseDir);
    File location = new File(baseDir, "location1");
    extendClasspath(location);
    put("injected", 12345);
    Object obj = run(new File(location, "main.clj"));
    System.out.println(obj.toString());
    Object xxx = find00("xxx");
    System.out.println(xxx.getClass().toString());
  }
}
      public void run() {

        int caretOffset = component.getCaretPosition();
        String cname = component.getClass().getName();

        Boolean _isReplPanel = false;

        if (cname.equals("javax.swing.JEditorPane")) _isReplPanel = true;

        String value = getText();
        String javaList = "";

        if (toAdd != null) {
          value += toAdd;
        }

        try {

          String c = component.getText(caretOffset - 1, 1);

          if (!_isClojure && _isNamespaceOrPkg) // java package containing the Class at the end
          {
            value = setValueForClass(value, component);
            javaList = getJavaImportListStr(value);

            if ((javaList.contains("(")) && (!_isReplPanel)) {
              int messageret =
                  (JOptionPane.showConfirmDialog(
                      component,
                      "Do you want to add the import " + value + " to your ns imports?",
                      "add import ?",
                      0));

              if (messageret == 0) {
                PersistentArrayMap entry = addImportList(component, javaList);
                // component.setCaretPosition(caretOffset + javaList.length());
                value = getClassPart(value);

                if (entry != null) {
                  String origNS = (String) entry.get(Keyword.intern(Symbol.create("orignodestr")));
                  String newNS = (String) entry.get(Keyword.intern(Symbol.create("newnodestr")));

                  int insertOffset = newNS.length() - origNS.length();

                  _carretOffset = _carretOffset + insertOffset;
                  _dotOffset = _dotOffset + insertOffset;
                }
              }
            }
          }

          if (!c.equals("/") && (_layout != backSlashAfterParen) && (_layout != backSlashNoParen)) {

            switch (_layout) {
              case LowercaseAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseAfterParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case LowercaseAfterParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case backSlashAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case FirstDotAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case FirstDotNoParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseNoParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseNoParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case LowercaseNoParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case LowercaseNoParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
            }

            doc.insertString(_dotOffset, value, null);
          } else {
            if (!c.equals("/")) {
              int backSlashOffset = indexOfBackSlash(component);
              if (backSlashOffset == -1) backSlashOffset = caretOffset;

              if (_isStatic || _layout == backSlashAfterParen || _layout == backSlashNoParen) {
                if (_isClojure && _isMethodOrFunction) {
                  if (isInCurrentNamespace(_fullclassname, component)) {
                    doc.remove(_dotOffset, _carretOffset - _dotOffset);
                    doc.insertString(_dotOffset, setValue(value), null);
                  } else {
                    doc.remove(backSlashOffset + 1, caretOffset - backSlashOffset - 1);
                    doc.insertString(backSlashOffset + 1, value, null);
                  }
                } else {
                  doc.remove(backSlashOffset + 1, caretOffset - backSlashOffset - 1);
                  doc.insertString(backSlashOffset + 1, value, null);
                }
              } else {
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                doc.insertString(_dotOffset, setValue(value), null);
              }

            } else if (_isStatic || _layout == backSlashAfterParen || _layout == backSlashNoParen)
              if (_isClojure && _isMethodOrFunction) {
                if (isInCurrentNamespace(_fullclassname, component)) {
                  doc.remove(_dotOffset, _carretOffset - _dotOffset);
                  doc.insertString(_dotOffset, setValue(value), null);
                } else doc.insertString(_carretOffset, value, null);
              } else doc.insertString(_carretOffset, value, null);
            else {
              doc.remove(_dotOffset, _carretOffset - _dotOffset);
              doc.insertString(_dotOffset, setValue(value), null);
            }
          }

          component.setCaretPosition(component.getCaretPosition() - backOffset);

        } catch (BadLocationException e) {
          LOG.log(Level.FINEST, e.getMessage());
        }
      }
Exemplo n.º 7
0
  @Override
  public void run(String... args) throws Exception {
    final File schemeFile = new File(args[0]);
    final CypherParts parts = new CypherParts();
    final List<List<?>> lists = readScheme(schemeFile);
    for (final List<?> top : lists) {
      final Symbol symbol = (Symbol) top.get(0);
      switch (symbol.getName()) {
          // ignore 'define'
          // ignore 'display'
          // ignore 'set!'
        case "define":
        case "display":
        case "set!":
          break;
          // InheritanceLink is mapped to "rdfs:subClassOf"
        case "InheritanceLink":
          log.info("INHERITANCE {}", top);
          inheritanceToCypher(parts, top);
          break;
          // EvaluationLink
        case "EvaluationLink":
          log.info("EVALUATION {}", top);
          evaluationToCypher(parts, top);
          break;
          // MemberLink/2 gene:GeneNode concept:ConceptNode
          // MemberLink is mapped to "rdf:type" ("a" in TURTLE-speak)
        case "MemberLink":
          log.info("MEMBER {}", top);
          memberToCypher(parts, top);
          break;
        default:
          log.error("Unknown symbol in '{}'", top);
      }
    }
    log.info("Cypher:\n{}", parts);

    final GraphDatabaseService graphDb = graphDb();
    try (final Transaction tx = graphDb.beginTx()) {
      log.info("Ensuring constraints and indexes...");
      graphDb.execute("CREATE CONSTRAINT ON (n:opencog_Concept) ASSERT n.href IS UNIQUE");
      graphDb.execute("CREATE CONSTRAINT ON (n:opencog_Gene) ASSERT n.href IS UNIQUE");
      graphDb.execute("CREATE CONSTRAINT ON (n:opencog_Predicate) ASSERT n.href IS UNIQUE");
      graphDb.execute("CREATE CONSTRAINT ON (n:opencog_Phrase) ASSERT n.href IS UNIQUE");

      graphDb.execute("CREATE INDEX ON :opencog_Concept(prefLabel)");
      graphDb.execute("CREATE INDEX ON :opencog_Gene(prefLabel)");
      graphDb.execute("CREATE INDEX ON :opencog_Predicate(prefLabel)");
      graphDb.execute("CREATE INDEX ON :opencog_Phrase(prefLabel)");

      tx.success();
    }
    log.info("Ensured constraints and indexes.");

    try (final Transaction tx = graphDb.beginTx()) {
      for (CypherPart node : parts.nodes.values()) {
        String cypher = "";
        for (String matchDependency : node.matchDependencies) {
          cypher += matchDependency + "\n";
        }
        cypher += node.toString();
        log.info("Creating node {}: {}", node.varName, cypher);
        graphDb.execute(cypher, node.param);
      }

      for (CypherPart relationship : parts.relationships) {
        String cypher = "";
        for (String matchDependency : relationship.matchDependencies) {
          cypher += matchDependency + "\n";
        }
        cypher += relationship.toString();
        log.info("Creating relationship: {}", cypher);
        graphDb.execute(cypher, relationship.param);
      }
      tx.success();
    }
    log.info("Done");
  }
Exemplo n.º 8
0
 public static String nsToFilename(Symbol symbol) {
   return nsToFilename(symbol.getName());
 }