├── settings.gradle.kts ├── res ├── icons │ ├── jojo.png │ ├── lice.png │ ├── ast_leaf.png │ ├── ast_node.png │ ├── ast_node_0.png │ ├── ast_node_2.png │ ├── lice_big_icon.png │ └── lice.svg ├── colorSchemes │ └── LiceDefault.xml ├── META-INF │ ├── descriptions.html │ ├── change-notes.html │ └── plugin.xml ├── liveTemplates │ └── Lice.xml └── org │ └── lice │ └── lang │ └── lice-bundle.properties ├── test ├── org │ └── lice │ │ └── lang │ │ ├── presentation-cn.lice │ │ ├── java-language-feature-test.kt │ │ ├── lice-icon-editor.kt │ │ ├── presentation.lice │ │ └── lice-code-gen.kt └── test.lice ├── gradle └── wrapper │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── org │ └── lice │ │ └── lang │ │ ├── action │ │ ├── LiceExceptionWrapper.java │ │ ├── lice-file-actions.kt │ │ └── lice-edit-actions.kt │ │ ├── module │ │ ├── LiceFacetSettingsTab.java │ │ ├── lice-sdks.kt │ │ ├── lice-facet-support.kt │ │ └── LiceFacetSettingsTab.form │ │ ├── lice-constants.kt │ │ ├── editing │ │ ├── lice-completion.kt │ │ ├── lice-quick-fixes.kt │ │ ├── lice-basic-editing.kt │ │ └── lice-annotator.kt │ │ ├── lice-parser.kt │ │ ├── lice-infos.kt │ │ ├── psi │ │ ├── impl │ │ │ ├── lice-impl-utils.kt │ │ │ └── lice-psi-mixin.kt │ │ ├── lice-resolving.kt │ │ └── lice-java-interop.kt │ │ ├── execution │ │ ├── LiceRunConfigurationEditor.java │ │ ├── lice-executor.kt │ │ ├── ui-impl.kt │ │ ├── lice-run-config.kt │ │ └── LiceRunConfigurationEditor.form │ │ ├── tool │ │ └── lice-tools.kt │ │ ├── lice-highlight.kt │ │ └── lice-settings.kt └── icons │ └── LiceIcons.java ├── grammar ├── lice-grammar.bnf └── lice-lexer.flex ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "lice-intellij" 2 | 3 | -------------------------------------------------------------------------------- /res/icons/jojo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lice-lang/lice-intellij/HEAD/res/icons/jojo.png -------------------------------------------------------------------------------- /res/icons/lice.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lice-lang/lice-intellij/HEAD/res/icons/lice.png -------------------------------------------------------------------------------- /res/icons/ast_leaf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lice-lang/lice-intellij/HEAD/res/icons/ast_leaf.png -------------------------------------------------------------------------------- /res/icons/ast_node.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lice-lang/lice-intellij/HEAD/res/icons/ast_node.png -------------------------------------------------------------------------------- /res/icons/ast_node_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lice-lang/lice-intellij/HEAD/res/icons/ast_node_0.png -------------------------------------------------------------------------------- /res/icons/ast_node_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lice-lang/lice-intellij/HEAD/res/icons/ast_node_2.png -------------------------------------------------------------------------------- /res/icons/lice_big_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lice-lang/lice-intellij/HEAD/res/icons/lice_big_icon.png -------------------------------------------------------------------------------- /test/org/lice/lang/presentation-cn.lice: -------------------------------------------------------------------------------- 1 | ;; 2 | ;; Created by ice1000 on 2018-01-14 3 | ;; 4 | 5 | (println "Hello world") 6 | 7 | (exit 0) 8 | (.. 1 1000) 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /test/org/lice/lang/java-language-feature-test.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang 2 | 3 | fun main(args: Array) { 4 | try { 5 | throw RuntimeException("233") 6 | } catch (e: RuntimeException) { 7 | throw e 8 | } catch (e: Exception) { 9 | println("caught!") 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /res/colorSchemes/LiceDefault.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | -------------------------------------------------------------------------------- /res/META-INF/descriptions.html: -------------------------------------------------------------------------------- 1 | Lice language support.
2 | Functions provided:

3 | 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Java template 3 | # Compiled class file 4 | *.class 5 | 6 | # Log file 7 | *.log 8 | 9 | # BlueJ files 10 | *.ctxt 11 | 12 | # Mobile Tools for Java (J2ME) 13 | .mtj.tmp/ 14 | 15 | # Package Files # 16 | *.jar 17 | *.war 18 | *.ear 19 | *.zip 20 | *.tar.gz 21 | *.rar 22 | 23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 24 | hs_err_pid* 25 | 26 | .idea/ 27 | out/ 28 | gen/ 29 | 30 | lice-ij 31 | *.iml 32 | lib 33 | 34 | resources 35 | -------------------------------------------------------------------------------- /src/org/lice/lang/action/LiceExceptionWrapper.java: -------------------------------------------------------------------------------- 1 | package org.lice.lang.action; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.lice.model.MetaData; 5 | import org.lice.util.LiceException; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * @author ice1000 11 | * @see org.lice.util.LiceException 12 | */ 13 | public class LiceExceptionWrapper extends LiceException { 14 | public @NotNull String show(@NotNull List cachedCodes) { 15 | return prettify(cachedCodes); 16 | } 17 | 18 | public LiceExceptionWrapper(@NotNull LiceException original) throws NoSuchFieldException, IllegalAccessException { 19 | super(original.getMessage(), (MetaData) LiceException.class.getDeclaredField("meta").get(original)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/icons/LiceIcons.java: -------------------------------------------------------------------------------- 1 | package icons; 2 | 3 | import com.intellij.openapi.util.IconLoader; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import javax.swing.*; 7 | 8 | /** 9 | * @author ice1000 10 | */ 11 | public interface LiceIcons { 12 | @NotNull Icon LICE_ICON = IconLoader.getIcon("/icons/lice.png"); 13 | @NotNull Icon LICE_BIG_ICON = IconLoader.getIcon("/icons/lice_big_icon.png"); 14 | 15 | @NotNull Icon LICE_AST_LEAF_ICON = IconLoader.getIcon("/icons/ast_leaf.png"); 16 | @NotNull Icon LICE_AST_NODE_ICON = IconLoader.getIcon("/icons/ast_node.png"); 17 | @NotNull Icon LICE_AST_NODE2_ICON = IconLoader.getIcon("/icons/ast_node_2.png"); 18 | @NotNull Icon LICE_AST_NODE0_ICON = IconLoader.getIcon("/icons/ast_node_0.png"); 19 | @NotNull Icon JOJO_ICON = IconLoader.getIcon("/icons/jojo.png"); 20 | } 21 | -------------------------------------------------------------------------------- /src/org/lice/lang/module/LiceFacetSettingsTab.java: -------------------------------------------------------------------------------- 1 | package org.lice.lang.module; 2 | 3 | import com.intellij.facet.ui.FacetEditorTab; 4 | import com.intellij.openapi.ui.TextFieldWithBrowseButton; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import javax.swing.*; 8 | 9 | /** 10 | * @author ice1000 11 | */ 12 | public abstract class LiceFacetSettingsTab extends FacetEditorTab { 13 | protected @NotNull JPanel mainPanel; 14 | protected @NotNull TextFieldWithBrowseButton jarPathField; 15 | protected @NotNull JTextField mainClassField; 16 | protected @NotNull JButton usePluginJarButton; 17 | protected @NotNull JButton resetToDefaultButton; 18 | protected @NotNull JLabel validationInfo; 19 | protected @NotNull JFormattedTextField timeLimitField; 20 | protected @NotNull JFormattedTextField textLimitField; 21 | } 22 | -------------------------------------------------------------------------------- /src/org/lice/lang/module/lice-sdks.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.module 2 | 3 | import com.intellij.facet.ui.libraries.LibraryInfo 4 | import com.intellij.ide.util.frameworkSupport.FrameworkVersion 5 | import com.intellij.openapi.module.ModuleManager 6 | import com.intellij.openapi.project.Project 7 | import org.jetbrains.annotations.NonNls 8 | import org.lice.lang.* 9 | 10 | class LiceSdkVersion(version: String) : FrameworkVersion( 11 | version, 12 | LiceBundle.message("lice.name"), 13 | arrayOf(createJarDownloadInfo(version))) 14 | 15 | private fun makeLiceDownloadUrl(version: String) = "$URL_GITHUB/download/v$version/lice-$version-all.jar" 16 | fun createJarDownloadInfo(@NonNls version: String) = 17 | LibraryInfo("lice-$version-all.jar", makeLiceDownloadUrl(version), URL_GITHUB, null, LICE_MAIN_DEFAULT) 18 | 19 | val Project.moduleSettings 20 | get() = ModuleManager 21 | .getInstance(this) 22 | .modules 23 | .map(LiceFacet.InstanceHolder::getInstance) 24 | .firstOrNull() 25 | ?.configuration 26 | ?.settings 27 | -------------------------------------------------------------------------------- /test/test.lice: -------------------------------------------------------------------------------- 1 | ;; comments 2 | (def fib n 3 | (if (in? (list 1 2) n) 4 | 1 5 | (+ (fib (- n 1)) (fib (- n 2))))) 6 | 7 | ;; travel through a range 8 | (for-each i (.. 1 10) (print i " ")) 9 | 10 | (|> 11 | (println "DIO! The World!")) 12 | 13 | ((if (in? (list 1 2 3) 6) 14 | + 15 | -) 1 2 3) 16 | 17 | (union 18 | (split "It was me, DIO!", " ") 19 | (list "Hello" "World") 20 | (array->list (array "DIO!" "The" "World"))) 21 | 22 | ; define a call-by-name function 23 | (defexpr fold ls init op 24 | (for-each index-var ls 25 | (-> init (op init index-var)))) 26 | fold 27 | ; invoke the function defined above 28 | (fold (.. 1 5) 0 +) 29 | 30 | ; passing a call-by-value lambda to a call-by-value lambda 31 | ((lambda op (op 3 4)) 32 | (lambda a b (+ (* a a) (* b b)))) 33 | 34 | ;; command line output 35 | (print "String literals", ) 36 | 37 | ;; unresolved reference 38 | (println unresolved-reference) 39 | 40 | ;; omega-combinator 41 | ((lambda x (x x)) (lambda x (x x))) 42 | 43 | ((lambda l 44 | (l "qaq" "qaq" "qaq")) 45 | (lambda a b c (|> 46 | (print a) 47 | (print (str-con " " b)) 48 | (print c)))) 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /test/org/lice/lang/lice-icon-editor.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang 2 | 3 | 4 | import java.awt.Color 5 | import java.awt.image.BufferedImage 6 | import java.io.File 7 | import javax.imageio.ImageIO 8 | 9 | fun task2() { 10 | val bigIcon = ImageIO.read(File("res/icons/lice_big_icon.png")) 11 | (0 until bigIcon.width).forEach { x -> 12 | (0 until bigIcon.height).forEach { y -> 13 | val o = bigIcon.getRGB(x, y) 14 | print((Color(o).rgb + 0xFFFFFF).toString(16)) 15 | dealWithPixel(bigIcon, x, y) 16 | } 17 | println() 18 | } 19 | ImageIO.write(bigIcon, "PNG", File("lice_big_icon.png")) 20 | } 21 | 22 | fun Array.main() { 23 | task2() 24 | } 25 | 26 | private fun dealWithPixel(icon: BufferedImage, x: Int, y: Int) { 27 | val o = icon.getRGB(x, y) + 0xFFFFFF 28 | var a = 256L - listOf(o and 0xFF, (o shr 8) and 0xFF, o shr 16).sum() / 3 29 | a = (16 * Math.sqrt(a.toDouble())).toLong() 30 | a = (16 * Math.sqrt(a.toDouble())).toLong() 31 | when { 32 | a < 0x90 -> a = a / 2 33 | a < 0xa0 -> a = a * 2 / 3 34 | a < 0xb0 -> a = a * 3 / 4 35 | } 36 | if (o == 0xfffffe) a = 0 37 | icon.setRGB(x, y, ((a shl 24) or o.toLong()).toInt()) 38 | print("[${"%02x".format(a)}] ") 39 | } 40 | -------------------------------------------------------------------------------- /grammar/lice-grammar.bnf: -------------------------------------------------------------------------------- 1 | { 2 | parserClass='org.lice.lang.LiceParser' 3 | extends='com.intellij.extapi.psi.ASTWrapperPsiElement' 4 | psiClassPrefix='Lice' 5 | psiImplClassSuffix='Impl' 6 | psiPackage='org.lice.lang.psi' 7 | psiImplPackage='org.lice.lang.psi.impl' 8 | 9 | tokenTypeClass='org.lice.lang.LiceTokenType' 10 | elementTypeHolderClass='org.lice.lang.psi.LiceTypes' 11 | elementTypeClass='org.lice.lang.LiceElementType' 12 | psiImplUtilClass='org.lice.lang.psi.impl.LicePsiImplUtils' 13 | } 14 | 15 | file ::= element* 16 | element ::= string | number | symbol | comment | null | functionCall { 17 | methods=[getNonCommentElements] 18 | } 19 | 20 | functionCall ::= LEFT_BRACKET element+ RIGHT_BRACKET { 21 | mixin='org.lice.lang.psi.impl.LiceFunctionCallMixin' 22 | implements=['org.lice.lang.psi.impl.ILiceFunctionCallMixin'] 23 | } 24 | 25 | number ::= NUM 26 | null ::= LEFT_BRACKET RIGHT_BRACKET 27 | symbol ::= SYM { 28 | mixin='org.lice.lang.psi.impl.LiceSymbolMixin' 29 | implements=['org.lice.lang.psi.impl.ILiceSymbolMixin'] 30 | } 31 | 32 | string ::= STR 33 | comment ::= LINE_COMMENT { 34 | methods=[isValidHost updateText createLiteralTextEscaper getTokenType] 35 | implements=['com.intellij.psi.PsiLanguageInjectionHost' 'com.intellij.psi.PsiComment'] 36 | } 37 | -------------------------------------------------------------------------------- /test/org/lice/lang/presentation.lice: -------------------------------------------------------------------------------- 1 | ;; 2 | ;; Created by ice1000 on 2018-01-12 3 | ;; 4 | 5 | ;; Let's take a look at Lice's IntelliJ IDEA plugin 6 | ;; To know how easy it can be to use Lice 7 | 8 | (|> 9 | (print "Hello World\n") 10 | (print "Bye world\n")) 11 | 12 | ;; These are some quick fixes 13 | 14 | ;; This is "Try evaluate" 15 | ;; You can use it to figure out how to use Lice's functions properly 16 | 17 | ;; What is this? 18 | ;; Oh, 3 args are needed 19 | ;; Do you understand now? :D 20 | ;; Let's print them! 21 | (for-each i (.. 2 12) (println i)) 22 | ;; Oh, unsupported! 23 | ;; Let's do "execution" instead of "Try evaluate"! 24 | 25 | ;; See? 26 | 27 | ;; Let's try to make a `fold` function 28 | 29 | (def fold list init-value op 30 | (for-each i list (-> init-value (op init-value i)))) 31 | 32 | ;; What's 1+2+3+...+100? 33 | ;; Here's the answer :D 34 | (fold (.. 1 100) 0 +) 35 | 36 | ;; Long output will be displayed in a TextArea 37 | ;; Selection and copying is allowed 38 | 39 | ;; What will happen if we do time-consuming operations? 40 | ;; Oh 41 | ;; Oh.. 42 | (while true (println "Oh no")) 43 | ;; 1500ms is the time limit 44 | ;; So please do "execution" if timeout :D 45 | 46 | ;; :D 47 | 48 | ;; Bye 49 | 50 | (++ (list 1 2 3) (list 3 4 5)) 51 | -------------------------------------------------------------------------------- /test/org/lice/lang/lice-code-gen.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang 2 | 3 | import org.intellij.lang.annotations.Language 4 | import org.junit.Test 5 | import org.lice.Lice 6 | import org.lice.core.SymbolList 7 | import java.nio.file.Files 8 | import java.nio.file.Paths 9 | 10 | class StarPlatinum { 11 | @Test 12 | fun ora() { 13 | SymbolList::class.java.canonicalName.let(::println) 14 | } 15 | 16 | @Test 17 | fun oraOraOraOra() { 18 | //language=Lice 19 | Lice.run("((233))").let(::println) 20 | //language=Lice 21 | Lice.run("((\"666\"))").let(::println) 22 | } 23 | 24 | @Test 25 | fun generateStdlibStub() { 26 | (SymbolList.preludeSymbols.map { 27 | //language=Lice 28 | "(defexpr $it ()) ;; this is a stub, used for indexing" 29 | } 30 | + 31 | SymbolList.preludeVariables.map { 32 | //language=Lice 33 | "(-> $it ()) ;; this is a stub, used for indexing" 34 | }) 35 | .sorted() 36 | .joinToString("\n") 37 | .let { 38 | println(it) 39 | val destination = Paths.get("./lice-stdlib.lice") 40 | if (!Files.exists(destination)) Files.createFile(destination) 41 | Files.write(destination, it.toByteArray()) 42 | } 43 | } 44 | 45 | @Test 46 | fun codesShownToMikecovlee() { 47 | @Language("Lice") 48 | val liceCode = "(+ 1 1)" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/org/lice/lang/lice-constants.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by ice1000 on 2017/3/29. 3 | * 4 | * @author ice1000 5 | */ 6 | package org.lice.lang 7 | 8 | import com.intellij.ide.plugins.PluginManager 9 | import com.intellij.openapi.extensions.PluginId 10 | import org.jetbrains.annotations.NonNls 11 | import java.nio.file.Files 12 | import java.nio.file.Paths 13 | 14 | @NonNls const val LICE_PLACEHOLDER = "(…)" 15 | @NonNls const val LICE_PLUGIN_ID = "org.lice.lang" 16 | @NonNls const val LICE_EXTENSION = "lice" 17 | 18 | @NonNls @JvmField val licePluginPath = PluginManager.getPlugin(PluginId.findId(LICE_PLUGIN_ID))?.path?.absolutePath.orEmpty() 19 | @NonNls @JvmField val liceJarPath = Paths.get(licePluginPath, "lib", "lice.jar").toAbsolutePath().toString() 20 | 21 | @JvmField val is64Bit = Files.exists(Paths.get("../jre64")) 22 | @JvmField val JAVA_PATH: String = Paths.get("../jre${if (!is64Bit) "" else "64"}/bin/java").toAbsolutePath().toString() 23 | 24 | @JvmField @NonNls val KOTLIN_RUNTIME_PATH: String = Paths.get("../lib/kotlin-runtime.jar").toAbsolutePath().toString() 25 | @JvmField @NonNls val KOTLIN_REFLECT_PATH: String = Paths.get("../lib/kotlin-reflect.jar").toAbsolutePath().toString() 26 | 27 | @NonNls const val LICE_RUN_CONFIG_ID = "LICE_RUN_CONFIGURATION" 28 | @NonNls const val LICE_MAIN_DEFAULT = "org.lice.repl.Main" 29 | @NonNls const val URL_GITHUB = "https://github.com/lice-lang/lice/releases" 30 | 31 | @JvmField @NonNls val LICE_STABLE_VERSION = listOf("3.3.2") 32 | -------------------------------------------------------------------------------- /src/org/lice/lang/editing/lice-completion.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.editing 2 | 3 | import com.intellij.codeInsight.completion.* 4 | import com.intellij.codeInsight.lookup.LookupElement 5 | import com.intellij.codeInsight.lookup.LookupElementBuilder 6 | import com.intellij.patterns.PlatformPatterns.psiElement 7 | import com.intellij.psi.PsiComment 8 | import com.intellij.psi.PsiElement 9 | import com.intellij.util.ProcessingContext 10 | import org.lice.core.SymbolList 11 | import org.lice.lang.psi.LiceTypes 12 | 13 | private class Completer(private val list: List) : CompletionProvider() { 14 | override fun addCompletions( 15 | parameters: CompletionParameters, 16 | context: ProcessingContext?, 17 | resultSet: CompletionResultSet) = list.forEach(resultSet::addElement) 18 | } 19 | 20 | class LiceBuiltinSymbolsCompletionContributor : CompletionContributor() { 21 | private companion object Completions { 22 | private val functions = SymbolList.preludeSymbols.map { LookupElementBuilder.create("$it ") } 23 | private val variables = LiceSymbols.allSymbols.map(LookupElementBuilder::create) 24 | } 25 | 26 | override fun invokeAutoPopup(position: PsiElement, typeChar: Char) = position !is PsiComment && typeChar in "( \t\n" 27 | 28 | init { 29 | extend(CompletionType.BASIC, psiElement(LiceTypes.SYM).afterLeaf("("), Completer(functions)) 30 | extend(CompletionType.BASIC, psiElement(LiceTypes.SYM).andNot(psiElement().afterLeaf("(")), Completer(variables)) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/org/lice/lang/lice-parser.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang 2 | 3 | import com.intellij.lang.* 4 | import com.intellij.openapi.project.Project 5 | import com.intellij.psi.* 6 | import com.intellij.psi.tree.* 7 | import org.lice.lang.psi.LiceTypes 8 | 9 | class LiceParserDefinition : ParserDefinition { 10 | private companion object { 11 | private val FILE = IFileElementType(LiceLanguage) 12 | } 13 | 14 | override fun getWhitespaceTokens(): TokenSet = TokenSet.WHITE_SPACE 15 | override fun createElement(astNode: ASTNode): PsiElement = LiceTypes.Factory.createElement(astNode) 16 | override fun getFileNodeType() = FILE 17 | override fun createFile(viewProvider: FileViewProvider) = LiceFile(viewProvider) 18 | override fun createParser(project: Project) = LiceParser() 19 | override fun getStringLiteralElements() = LiceTokenType.STRINGS 20 | override fun getCommentTokens() = LiceTokenType.COMMENTS 21 | override fun createLexer(project: Project) = LiceLexerAdapter() 22 | override fun spaceExistanceTypeBetweenTokens(astNode: ASTNode, astNode2: ASTNode) = 23 | ParserDefinition.SpaceRequirements.MAY 24 | } 25 | 26 | class LiceTokenType(debugName: String) : IElementType(debugName, LiceLanguage) { 27 | companion object { 28 | @JvmField val COMMENTS = TokenSet.create(LiceTypes.COMMENT) 29 | @JvmField val STRINGS = TokenSet.create(LiceTypes.STR) 30 | fun fromText(project: Project, code: String) = PsiFileFactory 31 | .getInstance(project) 32 | .createFileFromText(LiceLanguage, code) 33 | .let { it as? LiceFile } 34 | ?.firstChild 35 | } 36 | } 37 | 38 | class LiceElementType(debugName: String) : IElementType(debugName, LiceLanguage) 39 | -------------------------------------------------------------------------------- /res/icons/lice.svg: -------------------------------------------------------------------------------- 1 | 2 | lice 3 | 4 | 5 | 6 | 9 | 12 | 13 | 15 | 16 | 18 | 20 | LC 21 | 22 | -------------------------------------------------------------------------------- /grammar/lice-lexer.flex: -------------------------------------------------------------------------------- 1 | package org.lice.lang; 2 | 3 | import com.intellij.lexer.FlexLexer; 4 | import com.intellij.psi.tree.IElementType; 5 | import com.intellij.psi.TokenType; 6 | import org.lice.lang.psi.LiceTypes; 7 | 8 | %% 9 | 10 | %{ 11 | public LiceLexer() { this((java.io.Reader) null); } 12 | %} 13 | 14 | %class LiceLexer 15 | %implements FlexLexer 16 | %unicode 17 | %function advance 18 | %type IElementType 19 | %eof{ return; 20 | %eof} 21 | 22 | COMMENT=,|;[^\n]* 23 | WHITE_SPACE=[ \n\r\t] 24 | LBRACKET=\( 25 | RBRACKET=\) 26 | 27 | INCOMPLETE_STRING=\"([^\"\\]|\\[^])* 28 | STRING_LITERAL={INCOMPLETE_STRING}\" 29 | 30 | DIGIT=[0-9] 31 | 32 | HEX_NUM=0[xX][0-9a-fA-F]+ 33 | OCT_NUM=0[oO][0-7]+ 34 | BIN_NUM=0[bB][01]+ 35 | DEC_NUM={DIGIT}+[dDfFbBsSlLnNmM]? 36 | FLOAT={DIGIT}+\.{DIGIT}+[dDfFmM]? 37 | NUMBER=-?({BIN_NUM}|{OCT_NUM}|{DEC_NUM}|{HEX_NUM}|{FLOAT}) 38 | 39 | SYMBOL_CHAR=[a-zA-Z!@$\^&_:=<|>?.\\+\-~*/%\[\]#{}] 40 | SYMBOL={SYMBOL_CHAR}({SYMBOL_CHAR}|{DIGIT})* 41 | 42 | UNKNOWN_CHARACTER=[^a-zA-Z!@$\^&_:=<|>?.\\+\-~*/%\[\]#{}0-9\"\(\);] 43 | 44 | %state AFTER_NUM 45 | 46 | %% 47 | 48 | {SYMBOL} 49 | { yybegin(YYINITIAL); return TokenType.BAD_CHARACTER; } 50 | 51 | {NUMBER} 52 | { yybegin(AFTER_NUM); return LiceTypes.NUM; } 53 | 54 | {COMMENT} 55 | { yybegin(YYINITIAL); return LiceTypes.LINE_COMMENT; } 56 | 57 | {LBRACKET} 58 | { yybegin(YYINITIAL); return LiceTypes.LEFT_BRACKET; } 59 | 60 | {INCOMPLETE_STRING} 61 | { yybegin(YYINITIAL); return TokenType.BAD_CHARACTER; } 62 | 63 | {STRING_LITERAL} 64 | { yybegin(YYINITIAL); return LiceTypes.STR; } 65 | 66 | {SYMBOL} 67 | { yybegin(YYINITIAL); return LiceTypes.SYM; } 68 | 69 | {RBRACKET} 70 | { yybegin(YYINITIAL); return LiceTypes.RIGHT_BRACKET; } 71 | 72 | {WHITE_SPACE}+ 73 | { yybegin(YYINITIAL); return TokenType.WHITE_SPACE; } 74 | 75 | {UNKNOWN_CHARACTER} 76 | { yybegin(YYINITIAL); return TokenType.BAD_CHARACTER; } 77 | 78 | -------------------------------------------------------------------------------- /res/META-INF/change-notes.html: -------------------------------------------------------------------------------- 1 | 1.8.3
2 |
    3 |
4 |
5 | 1.8.2
6 |
    7 |
  • Icon migration
  • 8 |
  • Add mnemonic
  • 9 |
  • Efficiency improvements
  • 10 |
  • Configuration bug fixes
  • 11 |
12 |
13 | 1.8.1
14 |
    15 |
  • Bug fix of try-eval
  • 16 |
  • Improved renaming
  • 17 |
  • Improved thread-safety
  • 18 |
19 |
20 | 1.8
21 |
    22 |
  • Improved completion
  • 23 |
  • Supported renaming
  • 24 |
  • Bug fixes
  • 25 |
26 |
27 | 1.7.1
28 |
    29 |
  • Improved Windows capability and command line output
  • 30 |
  • Removed classes that are not working
  • 31 |
32 |
33 | 1.7
34 |
    35 |
  • Some minor changes and internal refactorings
  • 36 |
  • Improved parser, try-eval error reporter and annotator
  • 37 |
  • Better handling functions and anonymous functions when try-eval
  • 38 |
  • Support conversion of prelude functions in in-place evaluation
  • 39 |
  • Added download option for v3.3.2 and removed older buggy versions
  • 40 |
41 |
42 | 1.6
43 |
    44 |
  • A fatal bug fix. Now it's tested and verified to be bugless
  • 45 |
46 |
47 | 1.5
48 |
    49 |
  • Basic reference resolving, marking unresolved references
  • 50 |
  • Add in-place evaluation
  • 51 |
  • Support Lice v3.3.1 and v3.3.2 (final stable version)
  • 52 |
  • Fix bug of finding plugin path
  • 53 |
54 |
55 | 1.4
56 |
    57 |
  • Parser and action bug fixes
  • 58 |
  • Added bread crumb, code folding, structure view and spell checker
  • 59 |
60 |
61 | 1.3
62 |
    63 |
  • Try evaluate action
  • 64 |
  • Support Lice v3.3.0
  • 65 |
66 |
67 | 1.2
68 |
    69 |
  • Fixed no default working directory bug
  • 70 |
  • Improved File IO
  • 71 |
  • Added some basic quick fixes
  • 72 |
  • Improved SDK settings
  • 73 |
74 |
75 | 1.1
76 |
    77 |
  • Fixed color settings bug
  • 78 |
  • Added SDK configuration and code execution
  • 79 |
80 | -------------------------------------------------------------------------------- /src/org/lice/lang/lice-infos.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by ice1000 on 2017/3/28. 3 | * 4 | * @author ice1000 5 | */ 6 | package org.lice.lang 7 | 8 | import com.intellij.CommonBundle 9 | import com.intellij.codeInsight.template.TemplateContextType 10 | import com.intellij.extapi.psi.PsiFileBase 11 | import com.intellij.lang.Language 12 | import com.intellij.openapi.fileTypes.* 13 | import com.intellij.psi.FileViewProvider 14 | import com.intellij.psi.PsiFile 15 | import com.intellij.psi.util.PsiUtilCore 16 | import icons.LiceIcons 17 | import org.jetbrains.annotations.NonNls 18 | import org.jetbrains.annotations.PropertyKey 19 | import java.util.* 20 | 21 | object LiceLanguage : Language(LiceBundle.message("lice.name"), "text/$LICE_EXTENSION") { 22 | override fun getDisplayName() = LiceBundle.message("lice.name") 23 | override fun isCaseSensitive() = true 24 | } 25 | 26 | object LiceFileType : LanguageFileType(LiceLanguage) { 27 | override fun getDefaultExtension() = LICE_EXTENSION 28 | override fun getName() = LiceBundle.message("lice.file.name") 29 | override fun getIcon() = LiceIcons.LICE_ICON 30 | override fun getDescription() = LiceBundle.message("lice.name") 31 | } 32 | 33 | class LiceFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, LiceLanguage) { 34 | override fun getFileType() = LiceFileType 35 | } 36 | 37 | class LiceFileTypeFactory : FileTypeFactory() { 38 | override fun createFileTypes(consumer: FileTypeConsumer) = consumer.consume(LiceFileType, LICE_EXTENSION) 39 | } 40 | 41 | class LiceContext : TemplateContextType(LiceBundle.message("lice.name"), LiceBundle.message("lice.name")) { 42 | override fun isInContext(file: PsiFile, offset: Int) = PsiUtilCore.getLanguageAtOffset(file, offset) 43 | .isKindOf(LiceLanguage) 44 | } 45 | 46 | object LiceBundle { 47 | @NonNls private const val BUNDLE = "org.lice.lang.lice-bundle" 48 | private val bundle: ResourceBundle by lazy { ResourceBundle.getBundle(BUNDLE) } 49 | 50 | @JvmStatic 51 | fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = 52 | CommonBundle.message(bundle, key, *params) 53 | } 54 | -------------------------------------------------------------------------------- /src/org/lice/lang/psi/impl/lice-impl-utils.kt: -------------------------------------------------------------------------------- 1 | @file:JvmName("LicePsiImplUtils") 2 | @file:Suppress("EXTENSION_SHADOWED_BY_MEMBER", "ConflictingExtensionProperty") 3 | 4 | package org.lice.lang.psi.impl 5 | 6 | import com.intellij.openapi.util.TextRange 7 | import com.intellij.psi.* 8 | import com.intellij.psi.tree.IElementType 9 | import org.lice.lang.psi.* 10 | import java.lang.StringBuilder 11 | 12 | val LiceComment.tokenType: IElementType get() = LiceTypes.COMMENT 13 | val LiceComment.isValidHost get() = true 14 | fun LiceComment.updateText(string: String): LiceComment = ElementManipulators.handleContentChange(this, string) 15 | fun LiceComment.createLiteralTextEscaper() = object : LiteralTextEscaper(this@createLiteralTextEscaper) { 16 | private var numOfSemicolon = 1 17 | override fun isOneLine() = true 18 | override fun getOffsetInHost(offsetInDecoded: Int, rangeInHost: TextRange) = offsetInDecoded + numOfSemicolon 19 | override fun decode(rangeInHost: TextRange, builder: StringBuilder): Boolean { 20 | numOfSemicolon = myHost.text.indexOfFirst { it != ';' } 21 | builder.append(myHost.text, rangeInHost.startOffset + numOfSemicolon, rangeInHost.endOffset) 22 | return true 23 | } 24 | } 25 | 26 | val LiceElement.nonCommentElements: PsiElement? 27 | get() = children.firstOrNull { it is LiceFunctionCall || it is LiceNull || it is LiceSymbol || it is LiceNumber || it is LiceString } 28 | 29 | //val LiceString.isValidHost get() = true 30 | //fun LiceString.updateText(string: String): LiceString = ElementManipulators.handleContentChange(this, string) 31 | //fun LiceString.createLiteralTextEscaper() = object : LiteralTextEscaper(this@createLiteralTextEscaper) { 32 | // // private val mapping = IntIntHashMap() 33 | // override fun isOneLine() = false 34 | // 35 | // override fun getOffsetInHost(offsetInDecoded: Int, rangeInHost: TextRange) = offsetInDecoded + 1 36 | // override fun decode(rangeInHost: TextRange, builder: StringBuilder): Boolean { 37 | // builder.append(myHost.text, rangeInHost.startOffset + 1, rangeInHost.endOffset - 1) 38 | // return true 39 | // } 40 | //} 41 | -------------------------------------------------------------------------------- /src/org/lice/lang/execution/LiceRunConfigurationEditor.java: -------------------------------------------------------------------------------- 1 | package org.lice.lang.execution; 2 | 3 | import com.intellij.execution.ui.CommonJavaParametersPanel; 4 | import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; 5 | import com.intellij.openapi.options.SettingsEditor; 6 | import com.intellij.openapi.ui.TextBrowseFolderListener; 7 | import com.intellij.openapi.ui.TextFieldWithBrowseButton; 8 | import org.jetbrains.annotations.NotNull; 9 | import org.lice.lang.LiceFileType; 10 | 11 | import javax.swing.*; 12 | 13 | import static org.lice.lang.execution.Lice_run_configKt.jarChooser; 14 | 15 | /** 16 | * @author ice1000 17 | */ 18 | public class LiceRunConfigurationEditor extends SettingsEditor { 19 | private @NotNull JPanel mainPanel; 20 | private @NotNull CommonJavaParametersPanel javaParamsPanel; 21 | private @NotNull TextFieldWithBrowseButton jarLocationField; 22 | private @NotNull TextFieldWithBrowseButton targetFileField; 23 | private @NotNull JTextField jreLocationField; 24 | 25 | public LiceRunConfigurationEditor(@NotNull LiceRunConfiguration configuration) { 26 | jarLocationField.addBrowseFolderListener(new TextBrowseFolderListener(jarChooser)); 27 | targetFileField.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileDescriptor( 28 | LiceFileType.INSTANCE))); 29 | javaParamsPanel.getProgramParametersComponent().setEnabled(false); 30 | resetEditorFrom(configuration); 31 | } 32 | 33 | @Override protected void resetEditorFrom(@NotNull LiceRunConfiguration configuration) { 34 | javaParamsPanel.reset(configuration); 35 | jreLocationField.setText(configuration.getJreLocation()); 36 | jarLocationField.setText(configuration.getJarLocation()); 37 | targetFileField.setText(configuration.getTargetFile()); 38 | } 39 | 40 | @Override protected void applyEditorTo(@NotNull LiceRunConfiguration configuration) { 41 | javaParamsPanel.applyTo(configuration); 42 | configuration.setJarLocation(jarLocationField.getText()); 43 | configuration.setTargetFile(targetFileField.getText()); 44 | configuration.setJreLocation(jreLocationField.getText()); 45 | } 46 | 47 | @Override protected @NotNull JPanel createEditor() { 48 | return mainPanel; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Lice IntelliJ 2 | 3 | [![JetBrains Plugins](https://img.shields.io/jetbrains/plugin/v/10319-lice.svg)](https://plugins.jetbrains.com/plugin/10319-lice) 4 | [![JetBrains plugins](https://img.shields.io/jetbrains/plugin/d/10319-lice.svg)](https://plugins.jetbrains.com/plugin/10319-lice) 5 | 6 | This is a IDE for [the Lice programming language](https://github.com/lice-lang/lice), 7 | based on the intellij platform. 8 | 9 | It provides syntax highlighting and some structural editing tools. 10 | 11 | ![image](https://user-images.githubusercontent.com/16398479/34985341-b49c7f16-faee-11e7-9704-f759f2251c8e.png) 12 | 13 | Apart from syntax highlighting, there're also quick fixes: 14 | 15 | ![image](https://plugins.jetbrains.com/files/10319/screenshot_17800.png) 16 | 17 | Also, you can "Try evaluate" by Ctrl+Shift+E 18 | (you may adjust it in the settings page to avoid conflicting): 19 | 20 | ![](https://plugins.jetbrains.com/files/10319/screenshot_17801.png) 21 | ![](https://plugins.jetbrains.com/files/10319/screenshot_17810.png) 22 | 23 | You can even replace the current symbol with the evaluated results: 24 | 25 | ![image](https://plugins.jetbrains.com/files/10319/screenshot_17797.png) 26 | ![image](https://plugins.jetbrains.com/files/10319/screenshot_17799.png) 27 | 28 | Code folding and bread crumbs are also supported: 29 | 30 | ![image](https://user-images.githubusercontent.com/16398479/34902990-4ee9f7a4-f862-11e7-8f1c-9876b29494bd.png) 31 | ![image](https://user-images.githubusercontent.com/16398479/34902932-391f5d20-f861-11e7-8167-c5bf3b3bbd35.png) 32 | 33 | You can rename variables: 34 | 35 | ![](https://plugins.jetbrains.com/files/10319/screenshot_17827.png) 36 | 37 | For more screenshots please see [issue #1](https://github.com/lice-lang/lice-intellij/issues/1). 38 | 39 | ## Progress 40 | 41 | + [X] Live templates 42 | + [X] Ast viewer 43 | + [X] Commenter 44 | + [X] Create new file 45 | + [X] Parser and lexer 46 | + [X] Braces matcher 47 | + [X] Highlighting 48 | + [X] Giving warnings to dangerous operations 49 | + [ ] Resolving reference 50 | + [X] Completion 51 | + [X] Try evaluate (features!) 52 | + [X] Run configurations 53 | + [X] SDK management 54 | + [ ] Renaming 55 | + [X] Quick fixes (will be continuously added) 56 | + [X] Structure view 57 | + [X] Code folding 58 | + [X] Bread crumbs 59 | + [X] Spell checking support 60 | + [ ] Structural editing 61 | -------------------------------------------------------------------------------- /src/org/lice/lang/tool/lice-tools.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.tool 2 | 3 | import com.intellij.ui.components.JBScrollPane 4 | import com.intellij.ui.treeStructure.Tree 5 | import com.intellij.util.io.readText 6 | import org.lice.core.SymbolList 7 | import org.lice.model.* 8 | import org.lice.parse.* 9 | import java.awt.Dimension 10 | import java.nio.file.Path 11 | import javax.swing.JComponent 12 | import javax.swing.JTextArea 13 | import javax.swing.tree.DefaultMutableTreeNode 14 | 15 | object LiceSemanticTreeViewerFactory { 16 | /** 17 | * map the ast 18 | */ 19 | private fun mapAst2Display( 20 | node: Node, 21 | viewRoot: DefaultMutableTreeNode 22 | ): DefaultMutableTreeNode = when (node) { 23 | is ValueNode, 24 | is SymbolNode, 25 | is LazyValueNode -> DefaultMutableTreeNode(node) 26 | is ExpressionNode -> viewRoot.apply { 27 | add(mapAst2Display(node.node, DefaultMutableTreeNode(node.node))) 28 | node.params.forEach { add(mapAst2Display(it, DefaultMutableTreeNode(it))) } 29 | } 30 | else -> DefaultMutableTreeNode("unknown node") 31 | } 32 | 33 | private fun createTreeRootFromFile(file: Path) = Parser 34 | .parseTokenStream(Lexer(file.readText())) 35 | .accept(SymbolList()) 36 | .let { ast -> Tree(mapAst2Display(ast, DefaultMutableTreeNode(ast))) } 37 | 38 | fun create(file: Path): JComponent = try { 39 | JBScrollPane(createTreeRootFromFile(file).apply { 40 | preferredSize = Dimension(520, 520) 41 | }) 42 | } catch (e: Exception) { 43 | JTextArea(e.message) 44 | } 45 | } 46 | 47 | /* 48 | /** 49 | * @author ice1000 50 | */ 51 | fun displaySemanticTree(file: File) { 52 | private fun File.neighbour() = "$parent/$name-edited-${System.currentTimeMillis()}.lice" 53 | val frame = JFrame("Lice Semantic Tree") 54 | ToolWindowFactory { project, toolWindow -> 55 | } 56 | frame.layout = BorderLayout() 57 | frame.defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE 58 | frame.setLocation(80, 80) 59 | try { 60 | frame.add(JBScrollPane(createTreeRootFromFile(file).apply { 61 | preferredSize = Dimension(520, 520) 62 | }), BorderLayout.CENTER) 63 | } catch (e: RuntimeException) { 64 | val label = JTextArea(e.message) 65 | e.stackTrace.forEach { label.append("\t$it\n") } 66 | label.isEditable = false 67 | label.preferredSize = Dimension(600, 600) 68 | frame.add(label, BorderLayout.CENTER) 69 | } 70 | frame.pack() 71 | frame.isVisible = true 72 | } 73 | */ -------------------------------------------------------------------------------- /src/org/lice/lang/psi/lice-resolving.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.psi 2 | 3 | import com.intellij.codeInsight.lookup.LookupElementBuilder 4 | import com.intellij.lang.refactoring.RefactoringSupportProvider 5 | import com.intellij.openapi.util.TextRange 6 | import com.intellij.psi.* 7 | import org.lice.lang.LiceFile 8 | import org.lice.lang.LiceLanguage 9 | import org.lice.lang.editing.LiceSymbols 10 | 11 | class LiceSymbolReference(val symbol: LiceSymbol, private var definition: PsiElement? = null) : PsiReference { 12 | init { 13 | symbol.isResolved = true 14 | } 15 | 16 | private val collected = mutableListOf() 17 | private fun tryFindingDefinition() = (symbol.containingFile as? LiceFile)?.let { 18 | it.children 19 | .firstOrNull { 20 | it is LiceElement && it.functionCall != null 21 | } 22 | ?.let { it as? LiceElement } 23 | ?.functionCall 24 | ?.takeIf { it.liceCallee?.text in LiceSymbols.nameIntroducingFamily } 25 | ?.also { 26 | it.forceResolve() 27 | it.nonCommentElements.getOrNull(1)?.let { collected += LookupElementBuilder.create(it) } 28 | } 29 | } ?: LiceSymbolsExtractingAnnotator.javaDefinitions.let { 30 | it.removeIf { !it.isValid } 31 | it.firstOrNull { it.text == """"${symbol.text}"""" } 32 | } 33 | 34 | private val range = 0.let { TextRange(it, it + symbol.textLength) } 35 | override fun equals(other: Any?) = (other as? LiceSymbolReference)?.symbol == symbol 36 | override fun toString() = "${symbol.text}: ${symbol.javaClass.name}" 37 | override fun hashCode() = symbol.hashCode() 38 | override fun isReferenceTo(element: PsiElement) = element == definition 39 | override fun bindToElement(element: PsiElement) = element 40 | override fun isSoft() = false 41 | override fun getElement() = symbol 42 | override fun getRangeInElement(): TextRange = range 43 | override fun getCanonicalText(): String = symbol.text 44 | override fun resolve() = definition ?: tryFindingDefinition()?.also { definition = it } 45 | override fun getVariants() = collected.also(::println).toTypedArray() 46 | override fun handleElementRename(newElementName: String) = PsiFileFactory 47 | .getInstance(symbol.project) 48 | .createFileFromText(LiceLanguage, newElementName) 49 | .let { it as? LiceFile } 50 | ?.firstChild 51 | } 52 | 53 | class LiceRefactoringSupportProvider : RefactoringSupportProvider() { 54 | override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?) = true 55 | } 56 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/org/lice/lang/psi/lice-java-interop.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.psi 2 | 3 | import com.intellij.lang.annotation.AnnotationHolder 4 | import com.intellij.lang.annotation.Annotator 5 | import com.intellij.openapi.util.TextRange 6 | import com.intellij.psi.* 7 | import org.intellij.lang.annotations.Language 8 | import org.lice.core.SymbolList 9 | import org.lice.lang.LiceBundle 10 | import org.lice.lang.LiceSyntaxHighlighter 11 | import org.lice.lang.editing.LiceSymbols 12 | import java.util.regex.Pattern 13 | 14 | class LiceSymbolsExtractingAnnotator : Annotator { 15 | companion object RegExes { 16 | @Language("RegExp") private 17 | const val SYMBOL_CHAR = "[a-zA-Z!@\$^&_:=<|>?.\\\\+\\-~*/%\\[\\]#{}]" 18 | 19 | @Language("RegExp") private 20 | const val SYMBOL = "$SYMBOL_CHAR($SYMBOL_CHAR|[0-9])*" 21 | 22 | val SYMBOL_REGEX = Pattern.compile(SYMBOL).toRegex() 23 | 24 | @get:Synchronized 25 | val javaDefinitions = mutableSetOf() 26 | } 27 | 28 | override fun annotate(element: PsiElement, holder: AnnotationHolder) { 29 | val methodCall = element as? PsiMethodCallExpression ?: return 30 | val callee = methodCall.methodExpression.children.firstOrNull { it is PsiExpression } as? PsiExpression ?: return 31 | val calleeType = callee.type ?: return 32 | if (calleeType.isValid && calleeType.canonicalText == SymbolList::class.java.canonicalName) { 33 | val method = methodCall.methodExpression.children.firstOrNull { it is PsiIdentifier } ?: return 34 | val possibleString = methodCall.argumentList.children 35 | .firstOrNull { it is PsiLiteralExpression } as? PsiLiteralExpression ?: return 36 | val str = possibleString.value as? String ?: return 37 | val isFunc = "Function" in method.text 38 | val isVar = "Variable" in method.text 39 | javaDefinitions += possibleString 40 | if ((isVar or isFunc) and !SYMBOL_REGEX.matches(str)) { 41 | holder.createWarningAnnotation( 42 | TextRange(possibleString.textRange.startOffset + 1, possibleString.textRange.endOffset - 1), 43 | LiceBundle.message("lice.lint.java.invalid-symbol")) 44 | } 45 | if (isFunc) { 46 | holder.createInfoAnnotation( 47 | TextRange(possibleString.textRange.startOffset + 1, possibleString.textRange.endOffset - 1), 48 | LiceBundle.message("lice.lint.java.func-def")) 49 | .textAttributes = LiceSyntaxHighlighter.FUNCTION_DEFINITION 50 | } else if (isVar) { 51 | if (possibleString.value is String) holder.createInfoAnnotation( 52 | TextRange(possibleString.textRange.startOffset + 1, possibleString.textRange.endOffset - 1), 53 | LiceBundle.message("lice.lint.java.var-def")) 54 | .textAttributes = LiceSyntaxHighlighter.VARIABLE_DEFINITION 55 | } 56 | LiceSymbols.checkName(possibleString, holder, str) 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/org/lice/lang/execution/lice-executor.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.execution 2 | 3 | import com.intellij.execution.* 4 | import com.intellij.execution.configurations.* 5 | import com.intellij.execution.filters.TextConsoleBuilderFactory 6 | import com.intellij.execution.process.* 7 | import com.intellij.execution.runners.ExecutionEnvironment 8 | import com.intellij.execution.runners.ProgramRunner 9 | import com.intellij.execution.ui.ConsoleView 10 | import com.intellij.execution.ui.ConsoleViewContentType 11 | import com.intellij.icons.AllIcons 12 | import com.intellij.openapi.actionSystem.AnActionEvent 13 | import com.intellij.openapi.actionSystem.ToggleAction 14 | import com.intellij.openapi.application.ApplicationManager 15 | import com.intellij.openapi.project.DumbAware 16 | import org.lice.lang.* 17 | import java.io.File 18 | 19 | class LiceCommandLineState( 20 | private val configuration: LiceRunConfiguration, 21 | env: ExecutionEnvironment) : RunProfileState { 22 | private val consoleBuilder = TextConsoleBuilderFactory 23 | .getInstance() 24 | .createBuilder(env.project, 25 | SearchScopeProvider.createSearchScope(env.project, env.runProfile)) 26 | 27 | override fun execute(executor: Executor?, run: ProgramRunner): ExecutionResult { 28 | val handler = OSProcessHandler(GeneralCommandLine(listOf( 29 | JAVA_PATH, 30 | "-classpath", 31 | arrayOf( 32 | configuration.jarLocation, 33 | KOTLIN_RUNTIME_PATH, 34 | KOTLIN_REFLECT_PATH 35 | ).joinToString(File.pathSeparator), 36 | LICE_MAIN_DEFAULT, 37 | configuration.targetFile 38 | ) + configuration 39 | .vmParameters 40 | .split(" ") 41 | .filter(String::isNotBlank)) 42 | .withWorkDirectory(configuration.workingDirectory) 43 | ) 44 | ProcessTerminatedListener.attach(handler) 45 | handler.startNotify() 46 | val console = consoleBuilder.console 47 | console.print("${handler.commandLine}\n", ConsoleViewContentType.NORMAL_OUTPUT) 48 | console.allowHeavyFilters() 49 | console.attachToProcess(handler) 50 | return DefaultExecutionResult(console, handler, PauseOutputAction(console, handler)) 51 | } 52 | 53 | private class PauseOutputAction(private val console: ConsoleView, private val handler: ProcessHandler) : 54 | ToggleAction( 55 | ExecutionBundle.message("run.configuration.pause.output.action.name"), 56 | null, AllIcons.Actions.Pause), DumbAware { 57 | override fun isSelected(event: AnActionEvent) = console.isOutputPaused 58 | override fun setSelected(event: AnActionEvent, flag: Boolean) { 59 | console.isOutputPaused = flag 60 | ApplicationManager.getApplication().invokeLater { update(event) } 61 | } 62 | 63 | override fun update(event: AnActionEvent) { 64 | super.update(event) 65 | when { 66 | !handler.isProcessTerminated -> event.presentation.isEnabled = true 67 | !console.canPause() or !console.hasDeferredOutput() -> event.presentation.isEnabled = false 68 | else -> { 69 | event.presentation.isEnabled = true 70 | console.performWhenNoDeferredOutput { update(event) } 71 | } 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/org/lice/lang/lice-highlight.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang 2 | 3 | import com.intellij.openapi.editor.DefaultLanguageHighlighterColors 4 | import com.intellij.openapi.editor.HighlighterColors 5 | import com.intellij.openapi.editor.colors.TextAttributesKey 6 | import com.intellij.openapi.fileTypes.SyntaxHighlighter 7 | import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory 8 | import com.intellij.openapi.project.Project 9 | import com.intellij.openapi.vfs.VirtualFile 10 | import com.intellij.psi.tree.IElementType 11 | import org.lice.lang.psi.* 12 | 13 | class LiceSyntaxHighlighter : SyntaxHighlighter { 14 | companion object { 15 | @JvmField val SYMBOL = TextAttributesKey.createTextAttributesKey("LICE_SYMBOL", DefaultLanguageHighlighterColors.LOCAL_VARIABLE) 16 | @JvmField val NUMBER = TextAttributesKey.createTextAttributesKey("LICE_NUMBER", DefaultLanguageHighlighterColors.NUMBER) 17 | @JvmField val COMMENT = TextAttributesKey.createTextAttributesKey("LICE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT) 18 | @JvmField val STRING = TextAttributesKey.createTextAttributesKey("LICE_STRING", DefaultLanguageHighlighterColors.STRING) 19 | @JvmField val STRING_ESCAPE = TextAttributesKey.createTextAttributesKey("LICE_STRING_ESCAPE", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE) 20 | @JvmField val STRING_ESCAPE_INVALID = TextAttributesKey.createTextAttributesKey("LICE_STRING_ESCAPE_INVALID", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE) 21 | @JvmField val BRACKET = TextAttributesKey.createTextAttributesKey("LICE_BRACKET", DefaultLanguageHighlighterColors.BRACKETS) 22 | @JvmField val FUNCTION_DEFINITION = TextAttributesKey.createTextAttributesKey("LICE_FUNCTION_DEF", DefaultLanguageHighlighterColors.STATIC_METHOD) 23 | @JvmField val VARIABLE_DEFINITION = TextAttributesKey.createTextAttributesKey("LICE_VARIABLE_DEF", DefaultLanguageHighlighterColors.STATIC_FIELD) 24 | @JvmField val UNRESOLVED_SYMBOL = TextAttributesKey.createTextAttributesKey("LICE_UNRESOLVED", HighlighterColors.TEXT) 25 | @JvmField val IMPORTANT_SYMBOLS = TextAttributesKey.createTextAttributesKey("LICE_IMPORTANT_SYMBOLS", DefaultLanguageHighlighterColors.KEYWORD) 26 | @JvmField val PARAMETER = TextAttributesKey.createTextAttributesKey("LICE_PARAMETER", DefaultLanguageHighlighterColors.PARAMETER) 27 | private val SYMBOL_KEYS = arrayOf(SYMBOL) 28 | private val NUMBER_KEYS = arrayOf(NUMBER) 29 | private val COMMENT_KEYS = arrayOf(COMMENT) 30 | private val STRING_KEYS = arrayOf(STRING) 31 | private val BRACKET_KEYS = arrayOf(BRACKET) 32 | } 33 | 34 | override fun getTokenHighlights(type: IElementType?): Array = when (type) { 35 | LiceTypes.RIGHT_BRACKET, 36 | LiceTypes.LEFT_BRACKET -> BRACKET_KEYS 37 | LiceTypes.STR -> STRING_KEYS 38 | LiceTypes.SYM -> SYMBOL_KEYS 39 | LiceTypes.NUM -> NUMBER_KEYS 40 | LiceTypes.LINE_COMMENT -> COMMENT_KEYS 41 | else -> arrayOf() 42 | } 43 | 44 | override fun getHighlightingLexer() = LiceLexerAdapter() 45 | } 46 | 47 | class LiceSyntaxHighlighterFactory : SyntaxHighlighterFactory() { 48 | override fun getSyntaxHighlighter(project: Project?, file: VirtualFile?) = LiceSyntaxHighlighter() 49 | } 50 | 51 | -------------------------------------------------------------------------------- /res/liveTemplates/Lice.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 22 | 33 | 43 | 52 | 57 | 62 | 69 | -------------------------------------------------------------------------------- /src/org/lice/lang/execution/ui-impl.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.execution 2 | 3 | import com.intellij.openapi.options.ConfigurationException 4 | import com.intellij.openapi.project.Project 5 | import com.intellij.openapi.ui.Messages 6 | import com.intellij.ui.DocumentAdapter 7 | import icons.LiceIcons 8 | import org.jetbrains.annotations.Nls 9 | import org.lice.lang.* 10 | import org.lice.lang.module.LiceFacetSettingsTab 11 | import java.text.NumberFormat 12 | import javax.swing.event.DocumentEvent 13 | import javax.swing.text.DefaultFormatterFactory 14 | import javax.swing.text.NumberFormatter 15 | 16 | class LiceFacetSettingsTabImpl( 17 | private val settings: LiceModuleSettings, project: Project?) : LiceFacetSettingsTab() { 18 | init { 19 | val format = NumberFormat.getIntegerInstance() 20 | format.isGroupingUsed = false 21 | val factory = DefaultFormatterFactory(NumberFormatter(format)) 22 | mainClassField.text = settings.mainClass 23 | timeLimitField.value = settings.tryEvaluateTimeLimit 24 | timeLimitField.formatterFactory = factory 25 | textLimitField.value = settings.tryEvaluateTextLimit 26 | textLimitField.formatterFactory = factory 27 | jarPathField.text = settings.jarPath 28 | jarPathField.addBrowseFolderListener(LiceBundle.message("lice.messages.select-jar.title"), 29 | LiceBundle.message("lice.messages.select-jar.body"), 30 | project, 31 | jarChooser) 32 | jarPathField.textField.document.addDocumentListener(object : DocumentAdapter() { 33 | override fun textChanged(documentEvent: DocumentEvent) { 34 | validationInfo.isVisible = !validateLice(jarPathField.text) 35 | } 36 | }) 37 | resetToDefaultButton.addActionListener { 38 | mainClassField.text = LICE_MAIN_DEFAULT 39 | settings.mainClass = LICE_MAIN_DEFAULT 40 | } 41 | usePluginJarButton.addActionListener { 42 | if (Messages.showYesNoDialog(LiceBundle.message("lice.messages.give-up-old"), 43 | LiceBundle.message("lice.messages.use-plugin-jar"), 44 | LiceBundle.message("lice.messages.yes-yes-yes"), 45 | LiceBundle.message("lice.messages.no-no-no"), 46 | LiceIcons.JOJO_ICON) == Messages.YES) { 47 | jarPathField.text = liceJarPath 48 | settings.jarPath = liceJarPath 49 | } 50 | } 51 | validationInfo.isVisible = false 52 | } 53 | 54 | @Throws(ConfigurationException::class) 55 | override fun apply() { 56 | settings.mainClass = mainClassField.text 57 | settings.tryEvaluateTextLimit = (textLimitField.value as Number).toInt() 58 | settings.tryEvaluateTimeLimit = (timeLimitField.value as Number).toLong() 59 | settings.jarPath = jarPathField.text 60 | if (validationInfo.isVisible) throw ConfigurationException("Invalid Lice jar") 61 | super.apply() 62 | } 63 | 64 | override fun createComponent() = mainPanel 65 | 66 | override fun isModified() = jarPathField.text.trim { it <= ' ' } != settings.jarPath || 67 | mainClassField.text.trim { it <= ' ' } != settings.mainClass || 68 | textLimitField.text.trim { it <= ' ' } != settings.tryEvaluateTextLimit.toString() || 69 | timeLimitField.text.trim { it <= ' ' } != settings.tryEvaluateTimeLimit.toString() 70 | 71 | @Nls 72 | override fun getDisplayName() = LiceBundle.message("lice.name") 73 | } 74 | 75 | -------------------------------------------------------------------------------- /src/org/lice/lang/module/lice-facet-support.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.module 2 | 3 | import com.intellij.facet.* 4 | import com.intellij.facet.ui.* 5 | import com.intellij.ide.util.frameworkSupport.FrameworkVersion 6 | import com.intellij.openapi.components.* 7 | import com.intellij.openapi.module.Module 8 | import com.intellij.openapi.module.ModuleType 9 | import com.intellij.openapi.roots.ModifiableRootModel 10 | import com.intellij.openapi.roots.OrderRootType 11 | import com.intellij.openapi.ui.Messages 12 | import com.intellij.util.xmlb.XmlSerializerUtil 13 | import icons.LiceIcons 14 | import org.jdom.Element 15 | import org.lice.lang.* 16 | import org.lice.lang.execution.* 17 | 18 | @State( 19 | name = "LiceFacetConfiguration", 20 | storages = [Storage(file = "liceConfig.xml", scheme = StorageScheme.DIRECTORY_BASED)]) 21 | class LiceFacetConfiguration : FacetConfiguration, PersistentStateComponent { 22 | @Suppress("OverridingDeprecatedMember") 23 | override fun readExternal(element: Element?) = Unit 24 | 25 | @Suppress("OverridingDeprecatedMember") 26 | override fun writeExternal(element: Element?) = Unit 27 | 28 | val settings = LiceModuleSettings() 29 | override fun getState() = settings 30 | override fun createEditorTabs( 31 | context: FacetEditorContext?, manager: FacetValidatorsManager?) = 32 | arrayOf(LiceFacetSettingsTabImpl(settings, context?.project)) 33 | 34 | override fun loadState(moduleSettings: LiceModuleSettings) { 35 | moduleSettings.let { XmlSerializerUtil.copyBean(it, settings) } 36 | } 37 | } 38 | 39 | object LiceFacetType : 40 | FacetType(LiceFacet.LICE_FACET_ID, LiceBundle.message("lice.name"), LiceBundle.message("lice.name")) { 41 | override fun createDefaultConfiguration() = LiceFacetConfiguration() 42 | override fun getIcon() = LiceIcons.LICE_BIG_ICON 43 | override fun isSuitableModuleType(type: ModuleType<*>?) = type != null 44 | override fun createFacet(module: Module, s: String?, configuration: LiceFacetConfiguration, facet: Facet<*>?) = 45 | LiceFacet(this, module, configuration, facet) 46 | } 47 | 48 | class LiceFacet( 49 | facetType: FacetType, 50 | module: Module, 51 | configuration: LiceFacetConfiguration, 52 | underlyingFacet: Facet<*>?) : 53 | Facet(facetType, module, LiceBundle.message("lice.name"), configuration, underlyingFacet) { 54 | companion object InstanceHolder { 55 | @JvmField val LICE_FACET_ID = FacetTypeId(LiceBundle.message("lice.name")) 56 | fun getInstance(module: Module) = FacetManager.getInstance(module).getFacetByType(LICE_FACET_ID) 57 | } 58 | } 59 | 60 | class LiceFacetBasedFrameworkSupportProvider : FacetBasedFrameworkSupportProvider(LiceFacetType) { 61 | override fun getVersions() = LICE_STABLE_VERSION.map(::LiceSdkVersion) 62 | override fun getTitle() = LiceBundle.message("lice.name") 63 | override fun setupConfiguration(facet: LiceFacet, model: ModifiableRootModel, version: FrameworkVersion) { 64 | val orderEntry = model.orderEntries.firstOrNull { it.presentableName.contains("lice", true) } ?: return 65 | orderEntry.getFiles(OrderRootType.CLASSES).firstOrNull()?.let { 66 | val path = it.path.trimMysteriousPath() 67 | if (validateLice(path)) facet.configuration.settings.jarPath = path 68 | else Messages.showDialog( 69 | LiceBundle.message("lice.messages.invalid.body", path), 70 | LiceBundle.message("lice.messages.invalid.title"), 71 | arrayOf(LiceBundle.message("lice.messages.yes-yes-yes")), 72 | 0, 73 | LiceIcons.JOJO_ICON) 74 | } 75 | } 76 | } 77 | 78 | -------------------------------------------------------------------------------- /res/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | Lice 3 | Custom Languages 4 | ice1000 5 | 6 | 7 | 8 | com.intellij.modules.lang 9 | com.intellij.modules.java 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 26 | 29 | 32 | 35 | 38 | 41 | 44 | 47 | 50 | 53 | 56 | 57 | 58 | 59 | 64 | 68 | 69 | 72 | 73 | 74 | 75 | 76 | 77 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /src/org/lice/lang/action/lice-file-actions.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.action 2 | 3 | import com.intellij.CommonBundle 4 | import com.intellij.ide.actions.CreateFileAction 5 | import com.intellij.openapi.actionSystem.* 6 | import com.intellij.openapi.application.ApplicationManager 7 | import com.intellij.openapi.fileEditor.FileDocumentManager 8 | import com.intellij.openapi.project.DumbAware 9 | import com.intellij.openapi.project.Project 10 | import com.intellij.openapi.ui.Messages 11 | import com.intellij.openapi.ui.popup.JBPopupFactory 12 | import com.intellij.openapi.util.io.FileUtilRt 13 | import com.intellij.psi.* 14 | import icons.LiceIcons 15 | import org.intellij.lang.annotations.Language 16 | import org.lice.lang.* 17 | import org.lice.lang.tool.LiceSemanticTreeViewerFactory 18 | import java.awt.Dimension 19 | import java.nio.file.Paths 20 | import java.time.LocalDate 21 | import javax.swing.Icon 22 | 23 | class NewLiceFileAction : CreateFileAction( 24 | LiceBundle.message("lice.actions.new-file.title"), 25 | LiceBundle.message("lice.actions.new-file.description"), 26 | LiceIcons.LICE_ICON), DumbAware { 27 | 28 | override fun getErrorTitle(): String = CommonBundle.getErrorTitle() 29 | override fun getDefaultExtension() = LICE_EXTENSION 30 | override fun getActionName(directory: PsiDirectory?, s: String?) = 31 | LiceBundle.message("lice.actions.new-file.title") 32 | 33 | @Language("Lice") 34 | override fun create(name: String, directory: PsiDirectory) = 35 | arrayOf(directory.add(PsiFileFactory 36 | .getInstance(directory.project) 37 | .createFileFromText(when (FileUtilRt.getExtension(name)) { 38 | LICE_EXTENSION -> name 39 | else -> "$name.$LICE_EXTENSION" 40 | }, LiceFileType, """;; 41 | ;; ${LiceBundle.message("lice.actions.new-file.content", System.getProperty("user.name"), LocalDate.now())} 42 | ;; 43 | 44 | (|>) 45 | """))) 46 | 47 | override fun invokeDialog(project: Project, directory: PsiDirectory): Array { 48 | val validator = MyInputValidator(project, directory) 49 | Messages.showInputDialog( 50 | project, 51 | LiceBundle.message("lice.actions.new-file.dialog.description"), 52 | LiceBundle.message("lice.actions.new-file.title"), 53 | Messages.getQuestionIcon(), 54 | "bizarre.lice", 55 | validator) 56 | return validator.createdElements 57 | } 58 | } 59 | 60 | abstract class LiceFileAction(text: String?, description: String?, icon: Icon?) : AnAction(text, description, icon) { 61 | protected fun compatibleFiles(event: AnActionEvent) = CommonDataKeys 62 | .VIRTUAL_FILE_ARRAY 63 | .getData(event.dataContext) 64 | ?.filter { it.fileType == LiceFileType } 65 | ?: emptyList() 66 | 67 | override fun update(event: AnActionEvent) { 68 | event.presentation.isEnabledAndVisible = compatibleFiles(event).run { 69 | isNotEmpty() and all { LICE_EXTENSION == it.extension } 70 | } 71 | } 72 | } 73 | 74 | class ShowLiceFileSemanticTreeAction : LiceFileAction( 75 | LiceBundle.message("lice.actions.semantic-tree.title"), 76 | LiceBundle.message("lice.actions.semantic-tree.description"), 77 | LiceIcons.LICE_AST_NODE2_ICON), DumbAware { 78 | override fun actionPerformed(event: AnActionEvent) { 79 | compatibleFiles(event).forEach { file -> 80 | FileDocumentManager 81 | .getInstance() 82 | .getDocument(file) 83 | ?.let(FileDocumentManager.getInstance()::saveDocument) 84 | val view = LiceSemanticTreeViewerFactory.create(Paths.get(file.path)) 85 | val popup = JBPopupFactory 86 | .getInstance() 87 | .createComponentPopupBuilder(view, view) 88 | .createPopup() 89 | popup.size = Dimension(600, 600) 90 | ApplicationManager.getApplication().invokeLater(popup::showInFocusCenter) 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/org/lice/lang/lice-settings.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang 2 | 3 | import com.intellij.execution.configurations.ConfigurationFactory 4 | import com.intellij.execution.configurations.ConfigurationType 5 | import com.intellij.openapi.options.colors.* 6 | import com.intellij.openapi.project.Project 7 | import icons.LiceIcons 8 | import org.lice.lang.execution.LiceRunConfiguration 9 | import org.lice.lang.execution.trimMysteriousPath 10 | 11 | class LiceColorSettingsPage : ColorSettingsPage { 12 | private companion object { 13 | private val DESCRIPTORS = arrayOf( 14 | AttributesDescriptor(LiceBundle.message("lice.settings.color.symbols.ordinary"), LiceSyntaxHighlighter.SYMBOL), 15 | AttributesDescriptor(LiceBundle.message("lice.settings.color.symbols.important"), LiceSyntaxHighlighter.IMPORTANT_SYMBOLS), 16 | AttributesDescriptor(LiceBundle.message("lice.settings.color.bracket"), LiceSyntaxHighlighter.BRACKET), 17 | AttributesDescriptor(LiceBundle.message("lice.settings.color.strings.literals"), LiceSyntaxHighlighter.STRING), 18 | AttributesDescriptor(LiceBundle.message("lice.settings.color.strings.escape"), LiceSyntaxHighlighter.STRING_ESCAPE), 19 | AttributesDescriptor(LiceBundle.message("lice.settings.color.strings.invalid"), LiceSyntaxHighlighter.STRING_ESCAPE_INVALID), 20 | AttributesDescriptor(LiceBundle.message("lice.settings.color.number"), LiceSyntaxHighlighter.NUMBER), 21 | AttributesDescriptor(LiceBundle.message("lice.settings.color.ignored"), LiceSyntaxHighlighter.COMMENT), 22 | AttributesDescriptor(LiceBundle.message("lice.settings.color.def.function"), LiceSyntaxHighlighter.FUNCTION_DEFINITION), 23 | AttributesDescriptor(LiceBundle.message("lice.settings.color.def.variable"), LiceSyntaxHighlighter.VARIABLE_DEFINITION), 24 | AttributesDescriptor(LiceBundle.message("lice.settings.color.def.parameter"), LiceSyntaxHighlighter.PARAMETER), 25 | AttributesDescriptor(LiceBundle.message("lice.settings.color.symbols.unresolved"), LiceSyntaxHighlighter.UNRESOLVED_SYMBOL)) 26 | private val MAPS = mapOf( 27 | "unresolved" to LiceSyntaxHighlighter.UNRESOLVED_SYMBOL, 28 | "reservedWord" to LiceSyntaxHighlighter.IMPORTANT_SYMBOLS, 29 | "functionName" to LiceSyntaxHighlighter.FUNCTION_DEFINITION, 30 | "variableName" to LiceSyntaxHighlighter.VARIABLE_DEFINITION, 31 | "parameterName" to LiceSyntaxHighlighter.PARAMETER, 32 | "strEscape" to LiceSyntaxHighlighter.STRING_ESCAPE, 33 | "strEscapeInvalid" to LiceSyntaxHighlighter.STRING_ESCAPE_INVALID 34 | ) 35 | } 36 | 37 | override fun getAdditionalHighlightingTagToDescriptorMap() = MAPS 38 | override fun getHighlighter() = LiceSyntaxHighlighter() 39 | override fun getIcon() = LiceIcons.LICE_ICON 40 | override fun getDisplayName() = LiceBundle.message("lice.name") 41 | override fun getAttributeDescriptors() = DESCRIPTORS 42 | override fun getColorDescriptors(): Array = ColorDescriptor.EMPTY_ARRAY 43 | // @Language("Lice") 44 | override fun getDemoText() = """ 45 | ;; comments 46 | (def fib n 47 | (if (<= n 2) 48 | 1 49 | (+ (fib (- n 1)) (fib (- n 2))))) 50 | 51 | (undef unresolved-reference) 52 | (-> some-var 233) 53 | 54 | ;; command line output 55 | (print "Strin\g", "literals\n") 56 | """ 57 | } 58 | 59 | object LiceConfigurationType : ConfigurationType { 60 | override fun getIcon() = LiceIcons.LICE_BIG_ICON 61 | override fun getDisplayName() = LiceBundle.message("lice.name") 62 | override fun getConfigurationTypeDescription() = LiceBundle.message("lice.run.config.description") 63 | override fun getId() = LICE_RUN_CONFIG_ID 64 | override fun getConfigurationFactories() = arrayOf(LiceConfigurationFactory(this)) 65 | } 66 | 67 | class LiceConfigurationFactory(type: ConfigurationType) : ConfigurationFactory(type) { 68 | override fun createTemplateConfiguration(project: Project) = LiceRunConfiguration(project, this) 69 | } 70 | 71 | class LiceModuleSettings { 72 | var tryEvaluateTextLimit = 300 73 | var tryEvaluateTimeLimit = 1500L 74 | var mainClass = LICE_MAIN_DEFAULT 75 | var jarPath = liceJarPath 76 | set(value) { 77 | field = value.trimMysteriousPath() 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/org/lice/lang/execution/lice-run-config.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.execution 2 | 3 | import com.intellij.execution.CommonJavaRunConfigurationParameters 4 | import com.intellij.execution.Executor 5 | import com.intellij.execution.actions.ConfigurationContext 6 | import com.intellij.execution.actions.RunConfigurationProducer 7 | import com.intellij.execution.configurations.ConfigurationFactory 8 | import com.intellij.execution.configurations.LocatableConfigurationBase 9 | import com.intellij.execution.runners.ExecutionEnvironment 10 | import com.intellij.openapi.components.PathMacroManager 11 | import com.intellij.openapi.fileChooser.FileChooserDescriptor 12 | import com.intellij.openapi.project.Project 13 | import com.intellij.openapi.util.JDOMExternalizer 14 | import com.intellij.openapi.util.Ref 15 | import com.intellij.psi.PsiElement 16 | import org.jdom.Element 17 | import org.lice.lang.* 18 | import org.lice.lang.module.moduleSettings 19 | import java.util.jar.* 20 | 21 | class LiceRunConfiguration( 22 | project: Project, 23 | factory: ConfigurationFactory, 24 | var targetFile: String = "") 25 | : LocatableConfigurationBase(project, factory, LiceBundle.message("lice.name")), 26 | CommonJavaRunConfigurationParameters { 27 | var jreLocation = JAVA_PATH 28 | var jarLocation = project.moduleSettings?.jarPath.orEmpty() 29 | 30 | private var vmParams = "" 31 | private var workingDir = "" 32 | override fun setAlternativeJrePath(s: String?) = Unit 33 | override fun setProgramParameters(s: String?) = Unit 34 | override fun getEnvs() = mutableMapOf() 35 | override fun isPassParentEnvs() = true 36 | override fun isAlternativeJrePathEnabled() = false 37 | override fun getPackage() = null 38 | override fun getRunClass() = null 39 | override fun getWorkingDirectory() = workingDir 40 | override fun getVMParameters() = vmParams 41 | override fun setAlternativeJrePathEnabled(bool: Boolean) = Unit 42 | override fun setPassParentEnvs(bool: Boolean) = Unit 43 | override fun setEnvs(map: MutableMap) = Unit 44 | override fun getProgramParameters() = null 45 | override fun getAlternativeJrePath() = null 46 | override fun setWorkingDirectory(s: String?) = s.orEmpty().let { workingDir = it } 47 | override fun setVMParameters(s: String?) = s.orEmpty().let { vmParams = it } 48 | override fun getConfigurationEditor() = LiceRunConfigurationEditor(this) 49 | override fun getState(executor: Executor, environment: ExecutionEnvironment) = LiceCommandLineState(this, environment) 50 | override fun writeExternal(element: Element) { 51 | PathMacroManager.getInstance(project).expandPaths(element) 52 | super.writeExternal(element) 53 | JDOMExternalizer.write(element, "vmParams", vmParams) 54 | JDOMExternalizer.write(element, "jarLocation", jarLocation) 55 | JDOMExternalizer.write(element, "workingDir", workingDir) 56 | JDOMExternalizer.write(element, "targetFile", targetFile) 57 | } 58 | 59 | override fun readExternal(element: Element) { 60 | super.readExternal(element) 61 | JDOMExternalizer.readString(element, "vmParams")?.let { vmParams = it } 62 | JDOMExternalizer.readString(element, "jarLocation")?.let { jarLocation = it } 63 | JDOMExternalizer.readString(element, "workingDir")?.let { workingDir = it } 64 | JDOMExternalizer.readString(element, "targetFile")?.let { targetFile = it } 65 | PathMacroManager.getInstance(project).collapsePathsRecursively(element) 66 | } 67 | } 68 | 69 | @JvmField val jarChooser = FileChooserDescriptor(false, false, true, false, false, false) 70 | fun String.trimMysteriousPath() = trimEnd('/', '!', '"', ' ', '\n', '\t', '\r').trimStart(' ', '\n', '\t', '\r') 71 | fun validateLice(path: String) = LICE_MAIN_DEFAULT == findMainClass(path) 72 | fun findMainClass(path: String) = try { 73 | JarFile(path).use { jarFile -> 74 | val inputStream = jarFile.getInputStream(jarFile.getJarEntry("META-INF/MANIFEST.MF")) 75 | Manifest(inputStream).mainAttributes.getValue(Attributes.Name.MAIN_CLASS) 76 | } 77 | } catch (e: Exception) { 78 | null 79 | } 80 | 81 | class LiceRunConfigurationProducer : RunConfigurationProducer(LiceConfigurationType) { 82 | override fun isConfigurationFromContext( 83 | configuration: LiceRunConfiguration, context: ConfigurationContext) = 84 | configuration.targetFile == context 85 | .location 86 | ?.virtualFile 87 | ?.path 88 | ?.trimMysteriousPath() 89 | 90 | override fun setupConfigurationFromContext( 91 | configuration: LiceRunConfiguration, context: ConfigurationContext, ref: Ref?): Boolean { 92 | if (context.psiLocation?.containingFile !is LiceFile) return false 93 | configuration.targetFile = context.location?.virtualFile?.path.orEmpty().trimMysteriousPath() 94 | configuration.workingDirectory = context.project.basePath.orEmpty() 95 | configuration.jarLocation = context.project.moduleSettings?.jarPath.orEmpty() 96 | return true 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/org/lice/lang/execution/LiceRunConfigurationEditor.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 |
94 | -------------------------------------------------------------------------------- /src/org/lice/lang/psi/impl/lice-psi-mixin.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.psi.impl 2 | 3 | import com.intellij.extapi.psi.ASTWrapperPsiElement 4 | import com.intellij.lang.ASTNode 5 | import com.intellij.psi.* 6 | import com.intellij.util.IncorrectOperationException 7 | import org.lice.lang.* 8 | import org.lice.lang.editing.LiceSymbols 9 | import org.lice.lang.psi.* 10 | 11 | interface ILiceFunctionCallMixin : PsiNameIdentifierOwner { 12 | var isPossibleEval: Boolean 13 | 14 | /** Should be implemented lazily. */ 15 | val nonCommentElements: List 16 | val liceCallee: LiceElement? 17 | fun forceResolve(): Array 18 | } 19 | 20 | abstract class LiceFunctionCallMixin(node: ASTNode) : 21 | ASTWrapperPsiElement(node), 22 | LiceFunctionCall { 23 | private var references: Array? = null 24 | private var nonCommentElementsCache: List? = null 25 | override val nonCommentElements 26 | get() = nonCommentElementsCache ?: elementList.filter { it.comment == null }.also { nonCommentElementsCache = it } 27 | override val liceCallee get() = elementList.firstOrNull { it.comment == null } 28 | final override var isPossibleEval = true 29 | override fun forceResolve(): Array { 30 | val it = makeRef() 31 | references = it 32 | for (reference in it) reference.symbol.isResolved = true 33 | return it 34 | } 35 | 36 | private fun makeRef(): Array { 37 | val innerNames = nameIdentifierAndParams.mapNotNull(LiceElement::getSymbol) 38 | val innerNameTexts = innerNames.map(LiceSymbol::getText) 39 | if (liceCallee?.text in LiceSymbols.closureFamily) return SyntaxTraverser.psiTraverser(this) 40 | .filterIsInstance() 41 | .filter { it !in innerNames && it.text in innerNameTexts } 42 | .map { symbol -> LiceSymbolReference(symbol, this) } 43 | .toTypedArray() 44 | val name = innerNames.firstOrNull() ?: return emptyArray() 45 | val nameText = name.text 46 | val params = innerNames.drop(1) 47 | val paramTexts = params.map(LiceSymbol::getText) 48 | if (liceCallee?.text !in LiceSymbols.nameIntroducingFamily) return emptyArray() 49 | val list1 = SyntaxTraverser.psiTraverser(parent.parent) 50 | .filterIsInstance() 51 | .filter { it != name && it.text == nameText } 52 | .map { symbol -> LiceSymbolReference(symbol, this) } 53 | val list2 = SyntaxTraverser.psiTraverser(this) 54 | .filterIsInstance() 55 | .filter { it !in params && it.text in paramTexts } 56 | .map { symbol -> LiceSymbolReference(symbol, this) } 57 | return (list1 + list2).toTypedArray() 58 | } 59 | 60 | override fun getReferences() = references ?: forceResolve() 61 | private val nameIdentifierAndParams 62 | get() = when (liceCallee?.text) { 63 | in LiceSymbols.nameIntroducingFamily, 64 | in LiceSymbols.closureFamily -> 65 | nonCommentElements.run { if (size >= 1) subList(1, size).toList() else emptyList() } 66 | else -> emptyList() 67 | } 68 | 69 | override fun getNameIdentifier() = when (liceCallee?.text) { 70 | in LiceSymbols.closureFamily -> nonCommentElements.firstOrNull()?.symbol 71 | !in LiceSymbols.nameIntroducingFamily -> null 72 | else -> nonCommentElements.getOrNull(1)?.symbol 73 | } 74 | 75 | override fun setName(newName: String): PsiElement { 76 | val liceSymbol = nameIdentifier 77 | ?: throw IncorrectOperationException(LiceBundle.message("lice.messages.psi.cannot-rename", newName)) 78 | val newChild = PsiFileFactory 79 | .getInstance(liceSymbol.project) 80 | .createFileFromText(LiceLanguage, newName) 81 | .takeIf { it is LiceFile } 82 | ?.firstChild 83 | .let { if (it is LiceElement) it.symbol else it as? LiceSymbol } 84 | ?: throw IncorrectOperationException( 85 | LiceBundle.message("lice.messages.psi.cannot-rename-to", liceSymbol.text, newName)) 86 | references?.forEach { it.element.replace(newChild) } 87 | newChild.isResolved = true 88 | return liceSymbol.replace(newChild) 89 | } 90 | 91 | override fun getName() = nameIdentifier?.text 92 | override fun subtreeChanged() { 93 | references = null 94 | nonCommentElementsCache = null 95 | isPossibleEval = true 96 | super.subtreeChanged() 97 | } 98 | } 99 | 100 | interface ILiceSymbolMixin : PsiElement, PsiNameIdentifierOwner { 101 | var isResolved: Boolean 102 | } 103 | 104 | abstract class LiceSymbolMixin(node: ASTNode) : 105 | ASTWrapperPsiElement(node), 106 | LiceSymbol { 107 | override var isResolved = false 108 | private var reference: LiceSymbolReference? = null 109 | override fun getReference() = reference ?: LiceSymbolReference(this).also { reference = it } 110 | override fun getReferences(): Array = parent.parent.references 111 | override fun getNameIdentifier() = this 112 | override fun setName(name: String) = LiceTokenType.fromText(project, name)?.let(::replace) 113 | override fun subtreeChanged() { 114 | isResolved = false 115 | reference = null 116 | super.subtreeChanged() 117 | } 118 | } 119 | 120 | 121 | -------------------------------------------------------------------------------- /res/org/lice/lang/lice-bundle.properties: -------------------------------------------------------------------------------- 1 | lice.name=Lice 2 | lice.file.name=Lice file 3 | 4 | lice.run.config.description=Lice run configuration 5 | lice.run.config.title=Lice Run Configuration 6 | lice.run.config.jar-location=&Jar location: 7 | lice.run.config.jre-used=J&RE used: 8 | 9 | lice.ast.number=Number: {0} 10 | lice.ast.string=String: {0} 11 | lice.ast.function=function: <{0}> 12 | 13 | lice.actions.semantic-tree.title=View Lice Semantic Tree 14 | lice.actions.semantic-tree.description=View Lice file semantic tree in a window 15 | lice.actions.new-file.dialog.description=Enter a new Lice script name 16 | lice.actions.new-file.title=New Lice File 17 | lice.actions.new-file.description=Creates new Lice file 18 | lice.actions.new-file.content=Created by {0} on {1} 19 | lice.actions.try-eval.name=Try Evaluate 20 | lice.actions.try-eval.description=Use the Lice interpreter inside the plugin to evaluate the selected code 21 | 22 | lice.messages.psi.cannot-rename=Unable to rename to {0} 23 | lice.messages.psi.cannot-rename-to=Unable to rename {0} to {1} 24 | lice.messages.yes-yes-yes=Yes Yes Yes 25 | lice.messages.no-no-no=No No No 26 | lice.messages.use-plugin-jar=Use Lice Jar in the Plugin 27 | lice.messages.give-up-old=Are you sure to give up the old path? 28 | lice.messages.select-jar.title=Select Lice Jar 29 | lice.messages.select-jar.body=Selecting a Lice jar file 30 | lice.messages.invalid.title=Invalid jar Warning 31 | lice.messages.invalid.body={0}\n is not a valid lice jar.\n\ 32 | will be replaced with the jar used by the plugin. 33 | lice.messages.try-eval.overflowed-text=Evaluation output longer than {0} characters 34 | lice.messages.try-eval.function-named=A function named "{0}" 35 | lice.messages.try-eval.function-unnamed=An anonymous function 36 | lice.messages.try-eval.result=Result:\n\ 37 | {0} 38 | lice.messages.try-eval.timeout=Execution timeout.\n\ 39 | Extend time limit in Project Structure | Facets 40 | lice.messages.try-eval.unsupported=Use of function "{0}"\n\ 41 | is unsupported. 42 | lice.messages.try-eval.exception=Oops! A {0} is thrown:\n\ 43 | {1} 44 | 45 | lice.lint.illegal-escape=Illegal escape character 46 | lice.lint.missing-name=Missing {0} name 47 | lice.lint.parameter=parameter 48 | lice.lint.remove-symbol=Remove current symbol 49 | lice.lint.should-be-symbol=Name of {0} should be a symbol 50 | lice.lint.replace-empty-with-null=Empty nodes can be replaced with "null"s 51 | lice.lint.replace-run-with-null=Empty |> nodes can be replaced with "null"s 52 | lice.lint.null=null literal 53 | lice.lint.can-eval=Can evaluate {0} 54 | lice.lint.unresolved=Unresolved reference: {0} 55 | lice.lint.missing=Missing {0} 56 | lice.lint.lambda-body=lambda body 57 | lice.lint.var-value=variable value 58 | lice.lint.var=variable 59 | lice.lint.better=better name 60 | lice.lint.func-body=function body 61 | lice.lint.func=function 62 | lice.lint.inner-node=inner node 63 | lice.lint.condition=condition 64 | lice.lint.can-unwrap=Can be unwrapped 65 | lice.lint.unreachable=Unreachable code 66 | lice.lint.undef-std=Trying to undef a standard function 67 | lice.lint.overwrite-std=Trying to overwrite a standard name 68 | lice.lint.overwrite-danger-std=Trying to overwrite an important standard name 69 | lice.lint.name-lice-style=Use Lice style identifier: 70 | lice.lint.fix.cannot-convert=Cannot convert {0}\n\ 71 | to a valid lice expression 72 | lice.lint.fix.try-eval=Try evaluating {0} in-place 73 | lice.lint.fix.replace-with=Replace with {0} 74 | 75 | lice.lint.java.invalid-symbol=Not a valid Lice symbol, can't be used in Lice code 76 | lice.lint.java.func-def=Lice function definition 77 | lice.lint.java.var-def=Lice variable definition 78 | 79 | lice.settings.color.symbols.ordinary=Symbols//Ordinary symbols 80 | lice.settings.color.symbols.important=Symbols//Important symbols 81 | lice.settings.color.symbols.unresolved=Reference//Unresolved reference 82 | lice.settings.color.strings.literals=Strings//String literals 83 | lice.settings.color.strings.escape=Strings//Escape characters 84 | lice.settings.color.strings.invalid=Strings//Invalid escape characters 85 | lice.settings.color.bracket=Bracket 86 | lice.settings.color.number=Number 87 | lice.settings.color.ignored=Ignored character 88 | lice.settings.color.def.function=Definitions//Function definition 89 | lice.settings.color.def.variable=Definitions//Variable definition 90 | lice.settings.color.def.parameter=Definitions//Parameter name 91 | 92 | lice.settings.facet.jar-path=&Lice jar path: 93 | lice.settings.facet.main-class=&Main class: 94 | lice.settings.facet.try-eval.title=Try evaluate settings 95 | lice.settings.facet.try-eval.time-limit=&Time limit (millis): 96 | lice.settings.facet.try-eval.text-limit=&Output limit (char): 97 | lice.settings.facet.try-eval.time-limit.hint=If timeout, "try evaluate" will stop and give error. 98 | lice.settings.facet.try-eval.text-limit.hint=If overflowed, the output will be displayed in a JTextArea. 99 | lice.settings.facet.invalid-jar=This is not a valid lice jar. 100 | lice.settings.facet.use-plugin-jar=\ &Use jar from plugin 101 | lice.settings.facet.reset-main=&Reset to default 102 | lice.run.config.script-path=&Lice script path: 103 | lice.run.config.jre.tooltip=Currently unsupported to change 104 | -------------------------------------------------------------------------------- /src/org/lice/lang/editing/lice-quick-fixes.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.editing 2 | 3 | import com.intellij.codeInsight.intention.impl.BaseIntentionAction 4 | import com.intellij.openapi.application.ApplicationManager 5 | import com.intellij.openapi.editor.Editor 6 | import com.intellij.openapi.project.Project 7 | import com.intellij.psi.* 8 | import org.lice.core.Func 9 | import org.lice.lang.* 10 | import org.lice.lang.action.TryEvaluate 11 | import org.lice.lang.psi.LiceElement 12 | import org.lice.lang.psi.LiceFunctionCall 13 | import java.math.BigDecimal 14 | import java.math.BigInteger 15 | 16 | class LiceRemovingIntention(private val element: PsiElement, private val intentionText: String) : 17 | BaseIntentionAction() { 18 | override fun getText() = intentionText 19 | override fun isAvailable(project: Project, editor: Editor?, psiFile: PsiFile?) = true 20 | override fun getFamilyName() = LiceBundle.message("lice.name") 21 | override operator fun invoke(project: Project, editor: Editor?, psiFile: PsiFile?) { 22 | ApplicationManager.getApplication().runWriteAction(element::delete) 23 | } 24 | } 25 | 26 | class LiceReplaceWithAnotherSymbolIntention( 27 | private val element: PsiElement, 28 | private val anotherSymbolName: String, 29 | private val anotherSymbolCode: String) : BaseIntentionAction() { 30 | override fun getText() = LiceBundle.message("lice.lint.fix.replace-with", anotherSymbolName) 31 | override fun isAvailable(project: Project, editor: Editor?, psiFile: PsiFile?) = true 32 | override fun getFamilyName() = LiceBundle.message("lice.name") 33 | override operator fun invoke(project: Project, editor: Editor?, psiFile: PsiFile?) { 34 | val symbol = LiceTokenType.fromText(project, anotherSymbolCode) ?: return 35 | ApplicationManager.getApplication().runWriteAction { element.replace(symbol) } 36 | } 37 | } 38 | 39 | class LiceTryReplaceEvaluatedResultIntention( 40 | private var element: LiceFunctionCall) : BaseIntentionAction() { 41 | private val text = LiceBundle.message("lice.lint.fix.try-eval", cutText(element.text, SHORT_TEXT_MAX)) 42 | override fun getText() = text 43 | override fun isAvailable(project: Project, editor: Editor?, psiFile: PsiFile?) = true 44 | override fun getFamilyName() = LiceBundle.message("lice.name") 45 | override operator fun invoke(project: Project, editor: Editor, psiFile: PsiFile?) { 46 | val eval = TryEvaluate() 47 | val selectedText = editor.selectionModel.selectedText 48 | val result = (eval.tryEval(editor, selectedText ?: element.text, project, false) 49 | ?: run { 50 | element.isPossibleEval = false 51 | return 52 | }).get() 53 | 54 | @Suppress("UNCHECKED_CAST") 55 | fun convert(res: Any?, isOuterPair: Boolean = false): String = when (res) { 56 | is String -> """"${res 57 | .replace("\n", "\\n") 58 | .replace("\r", "\\r") 59 | .replace("\u000C", "\\f") 60 | .replace("\t", "\\t")}"""" 61 | is BigInteger -> "${res}N" 62 | is BigDecimal -> "${res.toPlainString()}M" 63 | is Iterable<*> -> "(list ${res.joinToString(" ") { convert(it) }})" 64 | is Array<*> -> "(array ${res.joinToString(" ") { convert(it) }})" 65 | is Pair<*, *> -> 66 | if (isOuterPair) "${convert(res.first)} ${convert(res.second, true)}" 67 | else "([|] ${convert(res.first)} ${convert(res.second, true)})" 68 | is Long -> "${res}L" 69 | is Short -> "${res}S" 70 | is Byte -> "${res}B" 71 | is Double -> "${res}D" 72 | is Float -> "${res}F" 73 | is Boolean, is Number -> "$res" 74 | null -> "null" 75 | else -> (res as? Func)?.let { f -> eval.prelude.firstOrNull { it.value == f }?.key } 76 | ?: throw UnsupportedOperationException(LiceBundle.message("lice.lint.fix.cannot-convert", res)) 77 | } 78 | 79 | val code = try { 80 | convert(result) 81 | } catch (e: UnsupportedOperationException) { 82 | element.isPossibleEval = false 83 | eval.showPopupWindow(e.message.orEmpty(), editor, 0xEDC209, 0xC26500) 84 | return 85 | } 86 | val symbol = LiceTokenType.fromText(project, code) ?: run { 87 | element.isPossibleEval = false 88 | return 89 | } 90 | (symbol as? LiceElement)?.functionCall?.run { isPossibleEval = false } 91 | ApplicationManager.getApplication().runWriteAction { 92 | if (selectedText != null && selectedText.indexOf(element.text) < 0) { 93 | val sub = element 94 | .children 95 | .filter { it.text.isNotBlank() } 96 | .sortedByDescending { it.textLength } 97 | .firstOrNull { it.textOffset >= editor.selectionModel.selectionStart && it.textLength <= selectedText.length } 98 | (sub ?: element).replace(symbol) 99 | } else element.replace(symbol) 100 | } 101 | } 102 | } 103 | 104 | class LiceReplaceWithAnotherElementIntention( 105 | private val element: PsiElement, 106 | private val anotherSymbolName: String, 107 | private val anotherSymbolNode: PsiElement) : BaseIntentionAction() { 108 | override fun getText() = LiceBundle.message("lice.lint.fix.replace-with", anotherSymbolName) 109 | override fun isAvailable(project: Project, editor: Editor?, psiFile: PsiFile?) = true 110 | override fun getFamilyName() = LiceBundle.message("lice.name") 111 | override operator fun invoke(project: Project, editor: Editor?, psiFile: PsiFile?) { 112 | ApplicationManager.getApplication().runWriteAction { element.replace(anotherSymbolNode) } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/org/lice/lang/editing/lice-basic-editing.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by ice1000 on 2017/3/28. 3 | * 4 | * @author ice1000 5 | */ 6 | package org.lice.lang.editing 7 | 8 | import com.intellij.codeInsight.template.impl.DefaultLiveTemplatesProvider 9 | import com.intellij.ide.structureView.* 10 | import com.intellij.ide.structureView.impl.common.PsiTreeElementBase 11 | import com.intellij.ide.util.treeView.smartTree.SortableTreeElement 12 | import com.intellij.lang.* 13 | import com.intellij.lang.folding.FoldingBuilderEx 14 | import com.intellij.lang.folding.FoldingDescriptor 15 | import com.intellij.lang.parser.GeneratedParserUtilBase 16 | import com.intellij.navigation.LocationPresentation 17 | import com.intellij.openapi.editor.Document 18 | import com.intellij.openapi.editor.Editor 19 | import com.intellij.psi.* 20 | import com.intellij.psi.tree.IElementType 21 | import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy 22 | import com.intellij.spellchecker.tokenizer.Tokenizer 23 | import com.intellij.ui.breadcrumbs.BreadcrumbsProvider 24 | import icons.LiceIcons 25 | import org.lice.lang.* 26 | import org.lice.lang.psi.* 27 | 28 | class LiceCommenter : Commenter { 29 | override fun getCommentedBlockCommentPrefix() = blockCommentPrefix 30 | override fun getCommentedBlockCommentSuffix() = blockCommentSuffix 31 | override fun getBlockCommentPrefix(): String? = null 32 | override fun getBlockCommentSuffix(): String? = null 33 | override fun getLineCommentPrefix() = "; " 34 | } 35 | 36 | class LiceBraceMatcher : PairedBraceMatcher { 37 | private companion object Pairs { 38 | private val PAIRS = arrayOf(BracePair(LiceTypes.LEFT_BRACKET, LiceTypes.RIGHT_BRACKET, false)) 39 | } 40 | 41 | override fun getPairs() = PAIRS 42 | override fun getCodeConstructStart(psiFile: PsiFile, openingBraceOffset: Int) = openingBraceOffset 43 | override fun isPairedBracesAllowedBeforeType(type: IElementType, elementType: IElementType?) = true 44 | } 45 | 46 | class LiceLiveTemplateProvider : DefaultLiveTemplatesProvider { 47 | override fun getDefaultLiveTemplateFiles() = arrayOf("liveTemplates/Lice") 48 | override fun getHiddenLiveTemplateFiles(): Array? = null 49 | } 50 | 51 | class LiceSpellCheckingStrategy : SpellcheckingStrategy() { 52 | override fun getTokenizer(element: PsiElement): Tokenizer<*> = when (element) { 53 | is LiceComment, is LiceSymbol -> super.getTokenizer(element) 54 | is LiceString -> super.getTokenizer(element).takeIf { it != EMPTY_TOKENIZER } ?: TEXT_TOKENIZER 55 | else -> EMPTY_TOKENIZER 56 | } 57 | } 58 | 59 | const val SHORT_TEXT_MAX = 12 60 | const val LONG_TEXT_MAX = 24 61 | fun cutText(it: String, textMax: Int) = if (it.length <= textMax) it else "${it.take(textMax)}…" 62 | 63 | class LiceBreadCrumbProvider : BreadcrumbsProvider { 64 | override fun getLanguages() = arrayOf(LiceLanguage) 65 | override fun acceptElement(o: PsiElement) = o is LiceFunctionCall 66 | override fun getElementTooltip(o: PsiElement) = (o as? LiceFunctionCall)?.let { LiceBundle.message("lice.ast.function", it.text) } 67 | override fun getElementInfo(o: PsiElement): String = when (o) { 68 | is LiceFunctionCall -> o.liceCallee?.text.let { 69 | when (it) { 70 | in LiceSymbols.closureFamily -> "λ" 71 | in LiceSymbols.importantFamily -> "[$it]" 72 | null -> LICE_PLACEHOLDER 73 | else -> cutText(it, SHORT_TEXT_MAX) 74 | } 75 | } 76 | else -> "???" 77 | } 78 | } 79 | 80 | class LiceFoldingBuilder : FoldingBuilderEx() { 81 | override fun getPlaceholderText(node: ASTNode): String = LICE_PLACEHOLDER 82 | override fun isCollapsedByDefault(node: ASTNode) = false 83 | override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean) = SyntaxTraverser 84 | .psiTraverser(root) 85 | .forceDisregardTypes { it == GeneratedParserUtilBase.DUMMY_BLOCK } 86 | .traverse() 87 | .filter { it is LiceFunctionCall || it is LiceNull } 88 | .filter { 89 | it.textRange.let { r -> 90 | document.getLineNumber(r.endOffset) - document.getLineNumber(r.startOffset) >= 1 || 91 | r.length >= LONG_TEXT_MAX 92 | } 93 | } 94 | .transform { FoldingDescriptor(it, it.textRange) } 95 | .toList() 96 | .toTypedArray() 97 | } 98 | 99 | class LiceStructureViewFactory : PsiStructureViewFactory { 100 | override fun getStructureViewBuilder(psiFile: PsiFile) = object : TreeBasedStructureViewBuilder() { 101 | override fun createStructureViewModel(editor: Editor?) = LiceModel(psiFile, editor) 102 | override fun isRootNodeShown() = true 103 | } 104 | 105 | private class LiceModel(file: PsiFile, editor: Editor?) : 106 | StructureViewModelBase(file, editor, LiceStructureElement(file)), StructureViewModel.ElementInfoProvider { 107 | init { 108 | withSuitableClasses(LiceFunctionCall::class.java, PsiFile::class.java) 109 | } 110 | 111 | override fun isAlwaysShowsPlus(o: StructureViewTreeElement) = false 112 | override fun isAlwaysLeaf(o: StructureViewTreeElement) = false 113 | override fun shouldEnterElement(o: Any?) = true 114 | } 115 | 116 | private class LiceStructureElement(o: PsiElement) : PsiTreeElementBase(o), SortableTreeElement, 117 | LocationPresentation { 118 | override fun getIcon(open: Boolean) = element.let { o -> 119 | when (o) { 120 | is LiceFile -> LiceIcons.LICE_ICON 121 | is LiceFunctionCall -> LiceIcons.LICE_AST_NODE_ICON 122 | is LiceNull -> LiceIcons.LICE_AST_NODE0_ICON 123 | else -> LiceIcons.LICE_AST_LEAF_ICON 124 | } 125 | } 126 | 127 | override fun getAlphaSortKey() = presentableText 128 | override fun getPresentableText() = cutText(element.let { o -> 129 | when (o) { 130 | is LiceFile -> LiceBundle.message("lice.file.name") 131 | is LiceFunctionCall -> o.liceCallee?.text ?: "??" 132 | is LiceSymbol -> o.text ?: "??" 133 | is LiceNull -> "()" 134 | is LiceNumber -> LiceBundle.message("lice.ast.number", o.text) 135 | is LiceString -> LiceBundle.message("lice.ast.string", o.text) 136 | else -> "??" 137 | } 138 | }, LONG_TEXT_MAX) 139 | 140 | override fun getLocationString() = "" 141 | override fun getLocationPrefix() = "" 142 | override fun getLocationSuffix() = "" 143 | override fun getChildrenBase() = element.let { o -> 144 | @Suppress("UNCHECKED_CAST") when (o) { 145 | is LiceFile -> o 146 | .children.mapNotNull { (it as? LiceElement)?.nonCommentElements } 147 | is LiceFunctionCall -> o 148 | .children.drop(1).mapNotNull { (it as? LiceElement)?.nonCommentElements } 149 | else -> emptyList() 150 | }.map(::LiceStructureElement) 151 | } 152 | } 153 | } 154 | 155 | -------------------------------------------------------------------------------- /src/org/lice/lang/action/lice-edit-actions.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.action 2 | 3 | import com.google.common.util.concurrent.UncheckedTimeoutException 4 | import com.intellij.openapi.actionSystem.* 5 | import com.intellij.openapi.application.ApplicationManager 6 | import com.intellij.openapi.editor.Editor 7 | import com.intellij.openapi.project.DumbAware 8 | import com.intellij.openapi.project.Project 9 | import com.intellij.openapi.ui.popup.Balloon 10 | import com.intellij.openapi.ui.popup.JBPopupFactory 11 | import com.intellij.openapi.util.Ref 12 | import com.intellij.ui.JBColor 13 | import com.intellij.ui.ScrollPaneFactory 14 | import com.intellij.util.ui.JBUI 15 | import icons.LiceIcons 16 | import org.lice.core.Func 17 | import org.lice.core.SymbolList 18 | import org.lice.lang.LiceBundle 19 | import org.lice.lang.LiceFileType 20 | import org.lice.lang.module.moduleSettings 21 | import org.lice.model.MetaData 22 | import org.lice.parse.Lexer 23 | import org.lice.parse.Parser 24 | import org.lice.util.LiceException 25 | import org.lice.util.className 26 | import java.awt.Dimension 27 | import java.util.concurrent.Executors 28 | import java.util.concurrent.TimeUnit 29 | import javax.swing.JLabel 30 | import javax.swing.JTextArea 31 | 32 | private class UseOfBannedFuncException(val name: String) : Throwable() 33 | class TryEvaluate { 34 | private companion object SymbolListHolder { 35 | private fun SymbolList.ban(name: String) = provideFunction(name) { throw UseOfBannedFuncException(name) } 36 | } 37 | 38 | private var textLimit = 360 39 | private var timeLimit = 1500L 40 | private var builder = StringBuilder() 41 | lateinit var prelude: Set> 42 | private val executor = Executors.newCachedThreadPool() 43 | private fun symbolList() = SymbolList().apply { 44 | prelude = variables.entries 45 | ban("getBigDecs") 46 | ban("getBigInts") 47 | ban("getDoubles") 48 | ban("getFloats") 49 | ban("getInts") 50 | ban("getLines") 51 | ban("getTokens") 52 | ban("exit") 53 | ban("extern") 54 | provideFunction("print") { it.forEach { builder.append(it) } } 55 | provideFunction("println") { it.forEach { builder.appendln(it) } } 56 | } 57 | 58 | private fun StringBuilder.insertOutputIfNonBlank() = insert(0, if (isNotBlank()) "\nOutput:\n" else "") 59 | fun tryEval(editor: Editor, text: String, project: Project?, popupWhenSuccess: Boolean): Ref? { 60 | project?.moduleSettings?.let { 61 | timeLimit = it.tryEvaluateTimeLimit 62 | textLimit = it.tryEvaluateTextLimit 63 | } 64 | if (builder.isNotBlank()) builder = StringBuilder() 65 | try { 66 | val symbolList = symbolList() 67 | val result = executor.submit { 68 | Parser 69 | .parseTokenStream(Lexer(text)) 70 | .accept(symbolList) 71 | .eval() 72 | }.get(timeLimit, TimeUnit.MILLISECONDS) 73 | if (popupWhenSuccess) { 74 | builder.insertOutputIfNonBlank() 75 | @Suppress("UNCHECKED_CAST") 76 | val resultString = (result as? Func)?.let { function -> 77 | symbolList 78 | .entries 79 | .firstOrNull { it.value == function } 80 | ?.takeUnless { it.key.run { startsWith("λ") and substring(1).all(Char::isDigit) } } 81 | ?.let { LiceBundle.message("lice.messages.try-eval.function-named", it.key) } 82 | ?: LiceBundle.message("lice.messages.try-eval.function-unnamed") 83 | } ?: "$result: ${result.className()}" 84 | builder.insert(0, LiceBundle.message("lice.messages.try-eval.result", resultString)) 85 | showPopupWindow(builder.toString(), editor, 0x0013F9, 0x000CA1) 86 | } 87 | return Ref.create(result) 88 | } catch (e: UncheckedTimeoutException) { 89 | builder.insertOutputIfNonBlank() 90 | builder.insert(0, LiceBundle.message("lice.messages.try-eval.timeout")) 91 | showPopupWindow(builder.toString(), editor, 0xEDC209, 0xC26500) 92 | } catch (original: Throwable) { 93 | val e = original.cause ?: original 94 | builder.insertOutputIfNonBlank() 95 | when (e) { 96 | is UseOfBannedFuncException -> { 97 | builder.insert(0, LiceBundle.message("lice.messages.try-eval.unsupported", e.name)) 98 | showPopupWindow(builder.toString(), editor, 0xEDC209, 0xC26500) 99 | } 100 | is LiceException -> { 101 | builder.insert(0, LiceBundle.message("lice.messages.try-eval.exception", 102 | e.javaClass.simpleName, LiceExceptionWrapper(e).show(text.split("\n")))) 103 | showPopupWindow(builder.toString(), editor, 0xE20911, 0xC20022) 104 | } 105 | else -> { 106 | builder.insert(0, LiceBundle.message("lice.messages.try-eval.exception", 107 | e.javaClass.simpleName, e.message.orEmpty())) 108 | showPopupWindow(builder.toString(), editor, 0xE20911, 0xC20022) 109 | } 110 | } 111 | } 112 | return null 113 | } 114 | 115 | fun showPopupWindow( 116 | result: String, 117 | editor: Editor, 118 | color: Int, 119 | colorDark: Int) { 120 | val relativePoint = JBPopupFactory.getInstance().guessBestPopupLocation(editor) 121 | if (result.length < textLimit) 122 | ApplicationManager.getApplication().invokeLater { 123 | JBPopupFactory 124 | .getInstance() 125 | .createHtmlTextBalloonBuilder(result, LiceIcons.LICE_BIG_ICON, JBColor(color, colorDark), null) 126 | .setFadeoutTime(8000) 127 | .setHideOnAction(true) 128 | .createBalloon() 129 | .show(relativePoint, Balloon.Position.below) 130 | } 131 | else 132 | ApplicationManager.getApplication().invokeLater { 133 | JBPopupFactory 134 | .getInstance() 135 | .createComponentPopupBuilder(JBUI.Panels.simplePanel() 136 | .addToTop(JLabel(LiceIcons.LICE_BIG_ICON)) 137 | .addToCenter(ScrollPaneFactory.createScrollPane(JTextArea(result).apply { 138 | toolTipText = LiceBundle.message("lice.messages.try-eval.overflowed-text", textLimit) 139 | lineWrap = true 140 | wrapStyleWord = true 141 | isEditable = false 142 | })) 143 | .apply { 144 | preferredSize = Dimension(500, 500) 145 | border = JBUI.Borders.empty(10, 5, 5, 5) 146 | }, null) 147 | .setRequestFocus(true) 148 | .setResizable(true) 149 | .setMovable(true) 150 | .setCancelOnClickOutside(true) 151 | .createPopup() 152 | .show(relativePoint) 153 | } 154 | } 155 | } 156 | 157 | class TryEvaluateLiceExpressionAction : 158 | AnAction(LiceBundle.message("lice.actions.try-eval.name"), 159 | LiceBundle.message("lice.actions.try-eval.description"), LiceIcons.LICE_BIG_ICON), DumbAware { 160 | private val core = TryEvaluate() 161 | override fun actionPerformed(event: AnActionEvent) { 162 | val editor = event.getData(CommonDataKeys.EDITOR) ?: return 163 | core.tryEval(editor, editor.selectionModel.selectedText ?: return, event.getData(CommonDataKeys.PROJECT), true) 164 | } 165 | 166 | override fun update(event: AnActionEvent) { 167 | event.presentation.isEnabledAndVisible = event.getData(CommonDataKeys.VIRTUAL_FILE)?.fileType == LiceFileType 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/org/lice/lang/module/LiceFacetSettingsTab.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 |
155 | -------------------------------------------------------------------------------- /src/org/lice/lang/editing/lice-annotator.kt: -------------------------------------------------------------------------------- 1 | package org.lice.lang.editing 2 | 3 | import com.intellij.lang.annotation.* 4 | import com.intellij.lang.annotation.Annotation 5 | import com.intellij.openapi.util.TextRange 6 | import com.intellij.psi.PsiElement 7 | import org.lice.core.SymbolList 8 | import org.lice.lang.LiceBundle 9 | import org.lice.lang.LiceSyntaxHighlighter 10 | import org.lice.lang.psi.* 11 | 12 | object LiceSymbols { 13 | @JvmField val defFamily = listOf("def", "deflazy", "defexpr") 14 | @JvmField val setFamily = listOf("->", "<->") 15 | @JvmField val closureFamily = listOf("lambda", "expr", "lazy") 16 | @JvmField val conditionedFamily = listOf("if", "while", "when") 17 | @JvmField val miscFamily = listOf("force|>", "|>", "null", "true", "false", "undef") 18 | const val validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@\$^&_:=<|>?.+\\-~*/%[]#{}" 19 | 20 | @JvmField val nameIntroducingFamily = defFamily + setFamily 21 | @JvmField val importantFamily = defFamily + setFamily + closureFamily + miscFamily + conditionedFamily 22 | @JvmField val allSymbols = SymbolList.preludeSymbols + SymbolList.preludeVariables 23 | 24 | fun checkName(text: PsiElement, holder: AnnotationHolder, name: String? = null) { 25 | val range = text.textRange 26 | val txt = name ?: text.text 27 | val namingMessage = LiceBundle.message("lice.lint.name-lice-style") 28 | var fix: String? = null 29 | var annotation: Annotation? = null 30 | when { 31 | '_' in txt -> { 32 | fix = txt.replace('_', '-') 33 | annotation = holder.createWeakWarningAnnotation(text, "$namingMessage $fix") 34 | } 35 | txt.startsWith("is-", true) -> { 36 | fix = "${txt.substring(3)}?" 37 | annotation = holder.createWeakWarningAnnotation(text, "$namingMessage $fix") 38 | } 39 | txt.contains("-to-", true) -> { 40 | fix = txt.replace("-to-", "->") 41 | annotation = holder.createWeakWarningAnnotation(text, "$namingMessage $fix") 42 | } 43 | txt.contains("to-", true) -> { 44 | fix = txt.replace("to-", "->") 45 | annotation = holder.createWeakWarningAnnotation(text, "$namingMessage $fix") 46 | } 47 | txt in LiceSymbols.importantFamily -> holder.createErrorAnnotation(range, 48 | LiceBundle.message("lice.lint.overwrite-std")) 49 | txt in LiceSymbols.allSymbols -> holder.createWeakWarningAnnotation(range, 50 | LiceBundle.message("lice.lint.overwrite-danger-std")) 51 | } 52 | if (text is LiceSymbol) { 53 | text.isResolved = true 54 | if (fix != null && annotation != null) annotation.registerFix(LiceReplaceWithAnotherSymbolIntention(text, 55 | LiceBundle.message("lice.lint.better"), fix)) 56 | } 57 | } 58 | } 59 | 60 | class LiceAnnotator : Annotator { 61 | override fun annotate(element: PsiElement, holder: AnnotationHolder) { 62 | when (element) { 63 | is LiceString -> { 64 | var isPrefixedByBackslash = false 65 | element.text.forEachIndexed { index, char -> 66 | isPrefixedByBackslash = if (isPrefixedByBackslash) { 67 | dealWithEscape(element, index, char, holder) 68 | false 69 | } else char == '\\' 70 | } 71 | } 72 | is LiceFunctionCall -> element.liceCallee?.let { calleeElement -> 73 | val callee = calleeElement.symbol 74 | var tryEvalPossible = true 75 | if (callee != null) when (callee.text) { 76 | "undef" -> { 77 | tryEvalPossible = false 78 | val funUndefined = checkArgs(element, holder, callee, 79 | LiceBundle.message("lice.lint.func")) ?: return@let 80 | if (funUndefined.text in LiceSymbols.allSymbols) 81 | holder.createWeakWarningAnnotation(funUndefined, LiceBundle.message("lice.lint.undef-std")) 82 | } 83 | "|>" -> { 84 | if (element.nonCommentElements.size <= 1) 85 | holder.createWeakWarningAnnotation(element, LiceBundle.message("lice.lint.replace-run-with-null")) 86 | .registerFix(LiceReplaceWithAnotherSymbolIntention(element, 87 | LiceBundle.message("lice.lint.null"), "null")) 88 | else if (element.nonCommentElements.size <= 2) 89 | holder.createWarningAnnotation(element, LiceBundle.message("lice.lint.can-unwrap")) 90 | .registerFix(LiceReplaceWithAnotherElementIntention(element, 91 | LiceBundle.message("lice.lint.inner-node"), element.nonCommentElements[1])) 92 | checkForTryEval(element, holder) 93 | } 94 | in LiceSymbols.defFamily -> { 95 | tryEvalPossible = false 96 | val funDefined = checkArgs(element, holder, callee, 97 | LiceBundle.message("lice.lint.func")) ?: return@let 98 | val symbol = funDefined.getSafeSymbol(holder, LiceBundle.message("lice.lint.func")) ?: return@let 99 | LiceSymbols.checkName(symbol, holder) 100 | holder.createInfoAnnotation(symbol, null).textAttributes = LiceSyntaxHighlighter.FUNCTION_DEFINITION 101 | if (element.nonCommentElements.size <= 2) 102 | missing(element, holder, LiceBundle.message("lice.lint.func-body")) 103 | } 104 | in LiceSymbols.setFamily -> { 105 | tryEvalPossible = false 106 | val varDefined = checkArgs(element, holder, callee, 107 | LiceBundle.message("lice.lint.var")) ?: return@let 108 | val symbol = varDefined.getSafeSymbol(holder, LiceBundle.message("lice.lint.var")) ?: return 109 | LiceSymbols.checkName(symbol, holder) 110 | holder.createInfoAnnotation(symbol, null) 111 | .textAttributes = LiceSyntaxHighlighter.VARIABLE_DEFINITION 112 | if (element.nonCommentElements.size <= 2) 113 | missing(element, holder, LiceBundle.message("lice.lint.var-value")) 114 | } 115 | in LiceSymbols.closureFamily -> { 116 | tryEvalPossible = false 117 | val elementList = element.nonCommentElements 118 | (1..elementList.size - 2).firstOrNull { checkParameter(elementList[it], holder) } 119 | if (elementList.size <= 1) 120 | missing(element, holder, LiceBundle.message("lice.lint.lambda-body")) 121 | } 122 | in LiceSymbols.conditionedFamily -> { 123 | val elementList = element.nonCommentElements 124 | if (elementList.size <= 1) missing(element, holder, LiceBundle.message("lice.lint.condition")) 125 | else if (callee.text == "if" && elementList.size > 4) holder.createWarningAnnotation( 126 | TextRange(elementList[4].textRange.startOffset, elementList.last().textRange.endOffset), 127 | LiceBundle.message("lice.lint.unreachable") 128 | ) 129 | } 130 | } 131 | if (tryEvalPossible) checkForTryEval(element, holder) 132 | } 133 | is LiceSymbol -> { 134 | if (element.text in LiceSymbols.importantFamily) 135 | holder.createInfoAnnotation(element, null).textAttributes = LiceSyntaxHighlighter.IMPORTANT_SYMBOLS 136 | if (!element.isResolved) { 137 | if (element.text in LiceSymbols.allSymbols) element.isResolved = true 138 | else holder.createInfoAnnotation(element, LiceBundle.message("lice.lint.unresolved", 139 | cutText(element.text, SHORT_TEXT_MAX))).run { 140 | textAttributes = LiceSyntaxHighlighter.UNRESOLVED_SYMBOL 141 | setNeedsUpdateOnTyping(true) 142 | } 143 | } 144 | } 145 | is LiceNull -> holder.createWeakWarningAnnotation(element, LiceBundle.message("lice.lint.replace-empty-with-null")) 146 | .registerFix(LiceReplaceWithAnotherSymbolIntention(element, LiceBundle.message("lice.lint.null"), "null")) 147 | } 148 | } 149 | 150 | private fun checkForTryEval(element: LiceFunctionCall, holder: AnnotationHolder) { 151 | if (element.isPossibleEval) holder.createInfoAnnotation(element, LiceBundle.message("lice.lint.can-eval", 152 | cutText(element.text, SHORT_TEXT_MAX))) 153 | .registerFix(LiceTryReplaceEvaluatedResultIntention(element)) 154 | } 155 | 156 | private fun LiceElement.getSafeSymbol(holder: AnnotationHolder, type: String) = symbol ?: run { 157 | holder.createErrorAnnotation(this, LiceBundle.message("lice.lint.should-be-symbol", type)) 158 | .registerFix(LiceRemovingIntention(this, LiceBundle.message("lice.lint.remove-symbol"))) 159 | null 160 | } 161 | 162 | private fun missing(element: LiceFunctionCall, holder: AnnotationHolder, type: String) { 163 | holder.createWarningAnnotation( 164 | TextRange(element.textRange.endOffset - 1, element.textRange.endOffset), 165 | LiceBundle.message("lice.lint.missing", type)) 166 | } 167 | 168 | /** 169 | * @author ice1000 170 | * @param callee just to provide an endOffset 171 | * @param holder annotation holder 172 | * @return null if unavailable 173 | */ 174 | private fun checkArgs( 175 | element: LiceFunctionCall, 176 | holder: AnnotationHolder, 177 | callee: PsiElement, 178 | type: String): LiceElement? { 179 | val elementList: List = element.nonCommentElements 180 | if (elementList.size <= 1) { 181 | holder.createWarningAnnotation( 182 | TextRange(callee.textRange.endOffset, element.textRange.endOffset), 183 | LiceBundle.message("lice.lint.missing-name", type)) 184 | return null 185 | } 186 | (2..elementList.size - 2).firstOrNull { checkParameter(elementList[it], holder) } 187 | return elementList[1] 188 | } 189 | 190 | private fun checkParameter(el: LiceElement, holder: AnnotationHolder): Boolean { 191 | val symbol = el.getSafeSymbol(holder, LiceBundle.message("lice.lint.parameter")) ?: return true 192 | symbol.isResolved = true 193 | holder.createInfoAnnotation(symbol, null).textAttributes = LiceSyntaxHighlighter.PARAMETER 194 | return false 195 | } 196 | 197 | private fun dealWithEscape(element: PsiElement, index: Int, char: Char, holder: AnnotationHolder) { 198 | val range = TextRange(element.textRange.startOffset + index - 1, element.textRange.startOffset + index + 1) 199 | if (char !in "nt\\\"bfr'") holder.createErrorAnnotation(range, LiceBundle.message("lice.lint.illegal-escape")) 200 | else holder.createInfoAnnotation(range, null).textAttributes = LiceSyntaxHighlighter.STRING_ESCAPE 201 | } 202 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------