Открытие проекта leiningen в emacs / cider вызывает ошибку пути к классам

Я изучаю Clojure с помощью книги Clojure for the Brave and True и использую emacs, сидр и leiningen. Я создал проект.

lein new app the-divine-cheese-code

Затем я добавил в проект исходные файлы.

божественный-сыр-код \ src \ the_divine_cheese_code \ core.clj божественный-сыр-код \ src \ the_divine_cheese_code \ visualization \ svg.clj

В core.clj я имею в виду пространство имен svg.clj.

божественный-сыр-код \ SRC \ the_divine_cheese_code \ core.clj

(ns the-divine-cheese-code.core)
;; Ensure that the SVG code is evaluated
(require 'the-divine-cheese-code.visualization.svg)
;; Refer the namespace so that you don't have to use the 
;; fully qualified name to reference svg functions
(refer 'the-divine-cheese-code.visualization.svg)

(def heists [{:location "Cologne, Germany"
              :cheese-name "Archbishop Hildebold's Cheese Pretzel"
              :lat 50.95
              :lng 6.97}
             {:location "Zurich, Switzerland"
              :cheese-name "The Standard Emmental"
              :lat 47.37
              :lng 8.55}
             {:location "Marseille, France"
              :cheese-name "Le Fromage de Cosquer"
              :lat 43.30
              :lng 5.37}
             {:location "Zurich, Switzerland"
              :cheese-name "The Lesser Emmental"
              :lat 47.37
              :lng 8.55}
             {:location "Vatican City"
              :cheese-name "The Cheese of Turin"
              :lat 41.90
              :lng 12.45}])

(defn -main
  [& args]
  (println (points heists)))

божественный-сыр-код \ SRC \ the_divine_cheese_code \ визуализация \ svg.clj

(ns the-divine-cheese-code.visualization.svg)

(defn latlng->point
  "Convert lat/lng map to comma-separated string" 
  [latlng]
  (str (:lat latlng) "," (:lng latlng)))

(defn points
  [locations]
  (clojure.string/join " " (map latlng->point locations)))

Вот вся структура директории проекта.

the-divine-cheese-code              
the-divine-cheese-code\.gitignore               
the-divine-cheese-code\.hgignore                
the-divine-cheese-code\.nrepl-port              
the-divine-cheese-code\CHANGELOG.md             
the-divine-cheese-code\doc              
the-divine-cheese-code\doc\intro.md             
the-divine-cheese-code\LICENSE              
the-divine-cheese-code\project.clj              
the-divine-cheese-code\README.md                
the-divine-cheese-code\resources                
the-divine-cheese-code\src              
the-divine-cheese-code\src\the_divine_cheese_code               
the-divine-cheese-code\src\the_divine_cheese_code\core.clj              
the-divine-cheese-code\src\the_divine_cheese_code\visualization             
the-divine-cheese-code\src\the_divine_cheese_code\visualization\svg.clj             
the-divine-cheese-code\target               
the-divine-cheese-code\target\default               
the-divine-cheese-code\target\default\classes               
the-divine-cheese-code\target\default\classes\META-INF              
the-divine-cheese-code\target\default\classes\META-INF\maven                
the-divine-cheese-code\target\default\classes\META-INF\maven\the-divine-cheese-code             
the-divine-cheese-code\target\default\classes\META-INF\maven\the-divine-cheese-code\the-divine-cheese-code              
the-divine-cheese-code\target\default\classes\META-INF\maven\the-divine-cheese-code\the-divine-cheese-code\pom.properties
the-divine-cheese-code\target\default\repl-port             

божественный-сыр-код \ цель \ по умолчанию \ устаревший
божественный-сыр-код \ цель \ по умолчанию \ устаревший \ leiningen.core.classpath.extract-native-dependencies
божественный-сыр- код \ тест
код-божественного-сыра \ test \ код-божественного-сыра
-код-божественного-сыра \ test \ the_divine_cheese_code \ core_test.clj

Когда я запускаю проект с помощью lein run, он успешно выполняется. Однако, когда я открываю файл core.clj с помощью emacs / cider и пытаюсь его скомпилировать, я получаю ошибку пути к классам.

CompilerException java.io.FileNotFoundException: Could not locate 
the_divine_cheese_code/visualization/svg__init.class or 
the_divine_cheese_code/visualization/svg.clj on classpath. Please check 
that namespaces with dashes use underscores in the Clojure file name., 
compiling:(c:/temp/the-divine-cheese-code/src/the_divine_cheese_code/core.clj:2:1)

CIDER успешно компилирует исходники, если я помещаю их в тот же каталог (соответственно меняя пространство имен).

(ns the-divine-cheese-code.core)
(require 'the-divine-cheese-code.svg)
(refer 'the-divine-cheese-code.svg)

(def heists [{:location "Cologne, Germany"
    ...

Так что, возможно, проблема связана с ОС. Я использую Windows 7, которая не является основной ОС для Emacs / CIDER.

После некоторых экспериментов я обнаружил, что CIDER работает без: refer

(ns the-divine-cheese-code.core
  (:require [the-divine-cheese-code.visualization.svg]))

Это похоже на ошибку CIDER, и 'lein run' в этом случае предсказуемо выдает ошибку. Если я сделаю это правильно

(ns the-divine-cheese-code.core
  (:require [the-divine-cheese-code.visualization.svg :refer :all]))

CIDER теперь выдает еще одну ошибку:

Caused by java.lang.IllegalStateException
latlng->point already refers to:
#'the-divine-cheese-code.svg/latlng->point in namespace:
the-divine-cheese-code.core

person Alex    schedule 13.11.2018    source источник
comment
Пробовали ли вы вместо этого использовать макрос ns?   -  person Aleph Aleph    schedule 13.11.2018
comment
@AlephAleph Я не совсем понял комментарий. Я уже использую макрос ns в обоих исходных файлах. Ключевым моментом этого примера приложения является ссылка на одно пространство имен из другого. Также, еще раз отмечу, проект успешно выполняется с lein run. Таким образом, в этом случае пространства имен разрешаются успешно. Я отредактировал вопрос и добавил полные источники.   -  person Alex    schedule 14.11.2018


Ответы (2)


Предложил бы использовать параметры, предоставляемые макросом ns, вместо операторов naked require и refer - это рекомендуемый способ выполнения импорта / требований в Clojure, и большая часть инструментов написана с учетом этого способа управления пространствами имен. Даже если приведенный ниже код по-прежнему не работает в CIDER, его будет легче диагностировать:

;; the-divine-cheese-code\src\the_divine_cheese_code\core.clj

(ns the-divine-cheese-code.core
  (:require [the-divine-cheese-code.visualization.svg :refer :all]))

(def heists ...)

(defn- main ...)
person Aleph Aleph    schedule 14.11.2018
comment
Как вы и ожидали, это все еще не работает в CIDER. Ошибка такая же. - person Alex; 14.11.2018
comment
Вы используете cider-jack-in для подключения к REPL в CIDER? - person Aleph Aleph; 14.11.2018
comment
Да, я использую сидр-джек. Я также добавил дополнительную информацию к вопросу. - person Alex; 14.11.2018
comment
Это сообщение latlng->point already refers to: #'the-divine-cheese-code.svg/latlng->point, вероятно, означает, что у вас был файл the_divine_cheese_code/svg.clj, а затем его содержимое было перемещено в другой файл. Вы пробовали перезапустить CIDER repl? - person Aleph Aleph; 15.11.2018
comment
Я пробовал «cider-quit», «cider-jack-in», и после этого у меня возникла исходная ошибка пути к классам. - person Alex; 15.11.2018

В моем случае ошибка исчезла после того, как я рекурсивно переименовал (с тем же именем) папку src/the_divine_cheese_code/ и ее содержимое.

Не уверен, что вызвало проблему. Я предполагаю, что кодировка символов была испорчена. Я создал и файл, и папку в Emacs и переименовал в Double Commander.

person Herman Nurlygayanov    schedule 18.06.2019