plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


86286be — pyrossh 2024-02-07T11:45:38+05:30
cleanup

Generated files not shown: package-lock.json

.eslintrc.json DELETED
@@ -1,10 +0,0 @@
1
- {
2
- "root": true,
3
- "parser": "@typescript-eslint/parser",
4
- "parserOptions": {
5
- "ecmaVersion": 6,
6
- "sourceType": "module"
7
- },
8
- "plugins": ["@typescript-eslint"],
9
- "rules": {}
10
- }
.vscode/extensions.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
3
- // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
4
-
5
- // List of extensions which should be recommended for users of this workspace.
6
- "recommendations": [
7
- "langium.langium-vscode"
8
- ]
9
- }
.vscode/launch.json DELETED
@@ -1,36 +0,0 @@
1
- // A launch configuration that launches the extension inside a new window
2
- // Use IntelliSense to learn about possible attributes.
3
- // Hover to view descriptions of existing attributes.
4
- // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
- {
6
- "version": "0.2.0",
7
- "configurations": [
8
- {
9
- "name": "Run Extension",
10
- "type": "extensionHost",
11
- "request": "launch",
12
- "args": [
13
- "${workspaceFolder}/example",
14
- "--extensionDevelopmentPath=${workspaceFolder}"
15
- ],
16
- "sourceMaps": true,
17
- "outFiles": [
18
- "${workspaceFolder}/out/**/*.js"
19
- ]
20
- },
21
- {
22
- "name": "Attach to Language Server",
23
- "type": "node",
24
- "port": 6009,
25
- "request": "attach",
26
- "skipFiles": [
27
- "<node_internals>/**"
28
- ],
29
- "sourceMaps": true,
30
- "outFiles": [
31
- "${workspaceFolder}/out/**/*.js",
32
- "${workspaceFolder}/node_modules/langium"
33
- ]
34
- }
35
- ]
36
- }
.vscode/tasks.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- // See https://go.microsoft.com/fwlink/?LinkId=733558
3
- // for the documentation about the tasks.json format
4
- "version": "2.0.0",
5
- "tasks": [
6
- {
7
- "label": "Build palm",
8
- "command": "npm run langium:generate && npm run build",
9
- "type": "shell",
10
- "group": {
11
- "kind": "build",
12
- "isDefault": true
13
- },
14
- "detail": "Langium: Generate grammar and build the palm language",
15
- "icon": {
16
- "color": "terminal.ansiGreen",
17
- "id": "server-process"
18
- }
19
- }
20
- ]
21
- }
.vscodeignore DELETED
@@ -1,4 +0,0 @@
1
- .vscode/**
2
- .vscode-test/**
3
- .gitignore
4
- langium-quickstart.md
bin/cli.js DELETED
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import main from '../out/cli/main.js';
4
- main();
esbuild.mjs DELETED
@@ -1,54 +0,0 @@
1
- //@ts-check
2
- import * as esbuild from 'esbuild';
3
-
4
- const watch = process.argv.includes('--watch');
5
- const minify = process.argv.includes('--minify');
6
-
7
- const success = watch ? 'Watch build succeeded' : 'Build succeeded';
8
-
9
- function getTime() {
10
- const date = new Date();
11
- return `[${`${padZeroes(date.getHours())}:${padZeroes(date.getMinutes())}:${padZeroes(date.getSeconds())}`}] `;
12
- }
13
-
14
- function padZeroes(i) {
15
- return i.toString().padStart(2, '0');
16
- }
17
-
18
- const plugins = [{
19
- name: 'watch-plugin',
20
- setup(build) {
21
- build.onEnd(result => {
22
- if (result.errors.length === 0) {
23
- console.log(getTime() + success);
24
- }
25
- });
26
- },
27
- }];
28
-
29
- const ctx = await esbuild.context({
30
- // Entry points for the vscode extension and the language server
31
- entryPoints: ['src/extension/main.ts', 'src/language/main.ts'],
32
- outdir: 'out',
33
- bundle: true,
34
- target: "ES2017",
35
- // VSCode's extension host is still using cjs, so we need to transform the code
36
- format: 'cjs',
37
- // To prevent confusing node, we explicitly use the `.cjs` extension
38
- outExtension: {
39
- '.js': '.cjs'
40
- },
41
- loader: { '.ts': 'ts' },
42
- external: ['vscode'],
43
- platform: 'node',
44
- sourcemap: !minify,
45
- minify,
46
- plugins
47
- });
48
-
49
- if (watch) {
50
- await ctx.watch();
51
- } else {
52
- await ctx.rebuild();
53
- ctx.dispose();
54
- }
index.html DELETED
@@ -1,22 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
-
4
- <head>
5
- <meta charset="UTF-8" />
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <title>Langium Web</title>
8
- <link href="./static/styles.css" rel="stylesheet"/>
9
- </head>
10
-
11
- <body>
12
- <div style="padding: 5px">
13
- <h1>Palm in Langium</h1>
14
- Please select which grammar definition you want to use with monaco-editor:
15
- <br>
16
- <a href="./static/monacoClassic.html">Palm + Monarch (Classic monaco-editor config)</a>
17
- <br>
18
- <a href="./static/monacoExtended.html">Palm + Textmate (Extended Vscode Extension Config)</a>
19
- </div>
20
- </body>
21
-
22
- </html>
langium-config.json DELETED
@@ -1,15 +0,0 @@
1
- {
2
- "projectName": "Palm",
3
- "languages": [{
4
- "id": "palm",
5
- "grammar": "src/language/palm.langium",
6
- "fileExtensions": [".palm"],
7
- "textMate": {
8
- "out": "syntaxes/palm.tmLanguage.json"
9
- },
10
- "monarch": {
11
- "out": "syntaxes/palm.monarch.ts"
12
- }
13
- }],
14
- "out": "src/language/generated"
15
- }
langium-quickstart.md DELETED
@@ -1,40 +0,0 @@
1
- # Welcome to your Langium VS Code Extension
2
-
3
- ## What's in the folder
4
-
5
- This folder contains all necessary files for your language extension.
6
- * `package.json` - the manifest file in which you declare your language support.
7
- * `language-configuration.json` - the language configuration used in the VS Code editor, defining the tokens that are used for comments and brackets.
8
- * `src/extension/main.ts` - the main code of the extension, which is responsible for launching a language server and client.
9
- * `src/language/palm.langium` - the grammar definition of your language.
10
- * `src/language/main.ts` - the entry point of the language server process.
11
- * `src/language/palm-module.ts` - the dependency injection module of your language implementation. Use this to register overridden and added services.
12
- * `src/language/palm-validator.ts` - an example validator. You should change it to reflect the semantics of your language.
13
- * `src/cli/main.ts` - the entry point of the command line interface (CLI) of your language.
14
- * `src/cli/generator.ts` - the code generator used by the CLI to write output files from DSL documents.
15
- * `src/cli/cli-util.ts` - utility code for the CLI.
16
-
17
- ## Get up and running straight away
18
-
19
- * Run `npm run langium:generate` to generate TypeScript code from the grammar definition.
20
- * Run `npm run build` to compile all TypeScript code.
21
- * Press `F5` to open a new window with your extension loaded.
22
- * Create a new file with a file name suffix matching your language.
23
- * Verify that syntax highlighting, validation, completion etc. are working as expected.
24
- * Run `node ./bin/cli` to see options for the CLI; `node ./bin/cli generate <file>` generates code for a given DSL file.
25
-
26
- ## Make changes
27
-
28
- * Run `npm run watch` to have the TypeScript compiler run automatically after every change of the source files.
29
- * Run `npm run langium:watch` to have the Langium generator run automatically after every change of the grammar declaration.
30
- * You can relaunch the extension from the debug toolbar after making changes to the files listed above.
31
- * You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes.
32
-
33
- ## Install your extension
34
-
35
- * To start using your extension with VS Code, copy it into the `<user home>/.vscode/extensions` folder and restart Code.
36
- * To share your extension with the world, read the [VS Code documentation](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) about publishing an extension.
37
-
38
- ## To Go Further
39
-
40
- Documentation about the Langium framework is available at https://langium.org
language-configuration.json DELETED
@@ -1,30 +0,0 @@
1
- {
2
- "comments": {
3
- // symbol used for single line comment. Remove this entry if your language does not support line comments
4
- "lineComment": "//",
5
- // symbols used for start and end a block comment. Remove this entry if your language does not support block comments
6
- "blockComment": [ "/*", "*/" ]
7
- },
8
- // symbols used as brackets
9
- "brackets": [
10
- ["{", "}"],
11
- ["[", "]"],
12
- ["(", ")"]
13
- ],
14
- // symbols that are auto closed when typing
15
- "autoClosingPairs": [
16
- ["{", "}"],
17
- ["[", "]"],
18
- ["(", ")"],
19
- ["\"", "\""],
20
- ["'", "'"]
21
- ],
22
- // symbols that can be used to surround a selection
23
- "surroundingPairs": [
24
- ["{", "}"],
25
- ["[", "]"],
26
- ["(", ")"],
27
- ["\"", "\""],
28
- ["'", "'"]
29
- ]
30
- }
package.json DELETED
@@ -1,87 +0,0 @@
1
- {
2
- "name": "palm-lang",
3
- "description": "Please enter a brief description here",
4
- "version": "0.0.1",
5
- "files": [
6
- "bin"
7
- ],
8
- "type": "module",
9
- "scripts": {
10
- "build": "tsc -b tsconfig.json && node esbuild.mjs",
11
- "watch": "concurrently -n tsc,esbuild -c blue,yellow \"tsc -b tsconfig.json --watch\" \"node esbuild.mjs --watch\"",
12
- "lint": "eslint src --ext ts",
13
- "langium:generate": "langium generate",
14
- "langium:watch": "langium generate --watch",
15
- "vscode:prepublish": "npm run build && npm run lint",
16
- "prepare:static": "node ./scripts/prepare.js",
17
- "build:web": "npm run build && npm run prepare:static && npm run build:monarch && npm run build:worker && npm run build:bundle",
18
- "build:monarch": "tsc -b tsconfig.monarch.json",
19
- "build:bundle": "vite --config ./vite.bundle.config.ts build",
20
- "build:worker": "esbuild --minify ./out/language/main-browser.js --bundle --format=iife --outfile=./static/worker/palm-server-worker.js",
21
- "dev": "vite",
22
- "dev:debug": "vite --debug --force",
23
- "serve": "npm run dev"
24
- },
25
- "dependencies": {
26
- "langium": "~2.1.0",
27
- "vscode-languageclient": "~9.0.1",
28
- "vscode-languageserver": "~9.0.1",
29
- "chalk": "~5.3.0",
30
- "commander": "~11.0.0",
31
- "@codingame/monaco-vscode-editor-service-override": "~1.83.2",
32
- "@codingame/monaco-vscode-keybindings-service-override": "~1.83.2",
33
- "monaco-editor-workers": "~0.44.0",
34
- "monaco-editor-wrapper": "~3.3.0",
35
- "monaco-languageclient": "~6.6.0",
36
- "vscode": "npm:@codingame/monaco-vscode-api@>=1.83.2 <1.84.0"
37
- },
38
- "devDependencies": {
39
- "@types/node": "~16.18.41",
40
- "@typescript-eslint/parser": "~6.4.1",
41
- "@typescript-eslint/eslint-plugin": "~6.4.1",
42
- "eslint": "~8.47.0",
43
- "langium-cli": "~2.1.0",
44
- "typescript": "~5.1.6",
45
- "@types/vscode": "~1.67.0",
46
- "concurrently": "~8.2.1",
47
- "esbuild": "~0.19.2",
48
- "vite": "~4.4.11"
49
- },
50
- "displayName": "palm-lang",
51
- "engines": {
52
- "vscode": "^1.67.0",
53
- "node": ">=16.0.0"
54
- },
55
- "categories": [
56
- "Programming Languages"
57
- ],
58
- "contributes": {
59
- "languages": [
60
- {
61
- "id": "palm",
62
- "aliases": [
63
- "Palm",
64
- "palm"
65
- ],
66
- "extensions": [
67
- ".palm"
68
- ],
69
- "configuration": "./language-configuration.json"
70
- }
71
- ],
72
- "grammars": [
73
- {
74
- "language": "palm",
75
- "scopeName": "source.palm",
76
- "path": "syntaxes/palm.tmLanguage.json"
77
- }
78
- ]
79
- },
80
- "activationEvents": [
81
- "onLanguage:palm"
82
- ],
83
- "main": "./out/extension/main.cjs",
84
- "bin": {
85
- "palm-cli": "./bin/cli.js"
86
- }
87
- }
example/fn.mi → readme.md RENAMED
File without changes
scripts/bundle.js DELETED
@@ -1,21 +0,0 @@
1
- import getEditorServiceOverride from '@codingame/monaco-vscode-editor-service-override';
2
- import getKeybindingsServiceOverride from '@codingame/monaco-vscode-keybindings-service-override';
3
- import { useOpenEditorStub } from 'monaco-languageclient';
4
- import { MonacoEditorLanguageClientWrapper } from 'monaco-editor-wrapper';
5
- import { addMonacoStyles } from 'monaco-editor-wrapper/styles';
6
-
7
- export const defineUserServices = () => {
8
- return {
9
- userServices: {
10
- ...getEditorServiceOverride(useOpenEditorStub),
11
- ...getKeybindingsServiceOverride()
12
- },
13
- debugLogging: true
14
- }
15
- };
16
- export {
17
- getEditorServiceOverride,
18
- getKeybindingsServiceOverride,
19
- addMonacoStyles,
20
- MonacoEditorLanguageClientWrapper
21
- }
scripts/prepare.js DELETED
@@ -1,20 +0,0 @@
1
- import { cp, existsSync, mkdirSync } from "node:fs";
2
-
3
- if (!existsSync('./syntaxes')) {
4
- mkdirSync('./syntaxes');
5
- }
6
- if (!existsSync('./static/worker')) {
7
- mkdirSync('./static/worker');
8
- }
9
-
10
- if (!existsSync('./static/monaco-editor-workers/workers')) {
11
- mkdirSync('./static/monaco-editor-workers/workers', { recursive: true });
12
- }
13
- const logError = (err) => {
14
- if (err) {
15
- console.error(err);
16
- }
17
- };
18
- cp('./node_modules/monaco-editor-workers/dist/index.js', './static/monaco-editor-workers/index.js', logError);
19
- cp('./node_modules/monaco-editor-workers/dist/workers/editorWorker-es.js', './static/monaco-editor-workers/workers/editorWorker-es.js', logError);
20
- cp('./node_modules/monaco-editor-workers/dist/workers/editorWorker-iife.js', './static/monaco-editor-workers/workers/editorWorker-iife.js', logError);
src/cli/cli-util.ts DELETED
@@ -1,51 +0,0 @@
1
- import type { AstNode, LangiumDocument, LangiumServices } from 'langium';
2
- import chalk from 'chalk';
3
- import * as path from 'node:path';
4
- import * as fs from 'node:fs';
5
- import { URI } from 'langium';
6
-
7
- export async function extractDocument(fileName: string, services: LangiumServices): Promise<LangiumDocument> {
8
- const extensions = services.LanguageMetaData.fileExtensions;
9
- if (!extensions.includes(path.extname(fileName))) {
10
- console.error(chalk.yellow(`Please choose a file with one of these extensions: ${extensions}.`));
11
- process.exit(1);
12
- }
13
-
14
- if (!fs.existsSync(fileName)) {
15
- console.error(chalk.red(`File ${fileName} does not exist.`));
16
- process.exit(1);
17
- }
18
-
19
- const document = services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI.file(path.resolve(fileName)));
20
- await services.shared.workspace.DocumentBuilder.build([document], { validation: true });
21
-
22
- const validationErrors = (document.diagnostics ?? []).filter(e => e.severity === 1);
23
- if (validationErrors.length > 0) {
24
- console.error(chalk.red('There are validation errors:'));
25
- for (const validationError of validationErrors) {
26
- console.error(chalk.red(
27
- `line ${validationError.range.start.line + 1}: ${validationError.message} [${document.textDocument.getText(validationError.range)}]`
28
- ));
29
- }
30
- process.exit(1);
31
- }
32
-
33
- return document;
34
- }
35
-
36
- export async function extractAstNode<T extends AstNode>(fileName: string, services: LangiumServices): Promise<T> {
37
- return (await extractDocument(fileName, services)).parseResult?.value as T;
38
- }
39
-
40
- interface FilePathData {
41
- destination: string,
42
- name: string
43
- }
44
-
45
- export function extractDestinationAndName(filePath: string, destination: string | undefined): FilePathData {
46
- filePath = path.basename(filePath, path.extname(filePath)).replace(/[.-]/g, '');
47
- return {
48
- destination: destination ?? path.join(path.dirname(filePath), 'generated'),
49
- name: path.basename(filePath)
50
- };
51
- }
src/cli/generator.ts DELETED
@@ -1,20 +0,0 @@
1
- import type { Program } from '../language/generated/ast.js';
2
- import * as fs from 'node:fs';
3
- import { CompositeGeneratorNode, NL, toString } from 'langium';
4
- import * as path from 'node:path';
5
- import { extractDestinationAndName } from './cli-util.js';
6
-
7
- export function generateJavaScript(model: Program, filePath: string, destination: string | undefined): string {
8
- const data = extractDestinationAndName(filePath, destination);
9
- const generatedFilePath = `${path.join(data.destination, data.name)}.js`;
10
-
11
- const fileNode = new CompositeGeneratorNode();
12
- fileNode.append('"use strict";', NL, NL);
13
- // model.greetings.forEach(greeting => fileNode.append(`console.log('Hello, ${greeting.person.ref?.name}!');`, NL));
14
-
15
- if (!fs.existsSync(data.destination)) {
16
- fs.mkdirSync(data.destination, { recursive: true });
17
- }
18
- fs.writeFileSync(generatedFilePath, toString(fileNode));
19
- return generatedFilePath;
20
- }
src/cli/main.ts DELETED
@@ -1,42 +0,0 @@
1
- import type { Program } from '../language/generated/ast.js';
2
- import chalk from 'chalk';
3
- import { Command } from 'commander';
4
- import { PalmLanguageMetaData } from '../language/generated/module.js';
5
- import { createPalmServices } from '../language/palm-module.js';
6
- import { extractAstNode } from './cli-util.js';
7
- import { generateJavaScript } from './generator.js';
8
- import { NodeFileSystem } from 'langium/node';
9
- import * as url from 'node:url';
10
- import * as fs from 'node:fs/promises';
11
- import * as path from 'node:path';
12
- const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
13
-
14
- const packagePath = path.resolve(__dirname, '..', '..', 'package.json');
15
- const packageContent = await fs.readFile(packagePath, 'utf-8');
16
-
17
- export const generateAction = async (fileName: string, opts: GenerateOptions): Promise<void> => {
18
- const services = createPalmServices(NodeFileSystem).Palm;
19
- const model = await extractAstNode<Program>(fileName, services);
20
- const generatedFilePath = generateJavaScript(model, fileName, opts.destination);
21
- console.log(chalk.green(`JavaScript code generated successfully: ${generatedFilePath}`));
22
- };
23
-
24
- export type GenerateOptions = {
25
- destination?: string;
26
- }
27
-
28
- export default function (): void {
29
- const program = new Command();
30
-
31
- program.version(JSON.parse(packageContent).version);
32
-
33
- const fileExtensions = PalmLanguageMetaData.fileExtensions.join(', ');
34
- program
35
- .command('generate')
36
- .argument('<file>', `source file (possible file extensions: ${fileExtensions})`)
37
- .option('-d, --destination <dir>', 'destination directory of generating')
38
- .description('generates JavaScript code that prints "Hello, {name}!" for each greeting in a source file')
39
- .action(generateAction);
40
-
41
- program.parse(process.argv);
42
- }
src/extension/main.ts DELETED
@@ -1,58 +0,0 @@
1
- import type { LanguageClientOptions, ServerOptions} from 'vscode-languageclient/node.js';
2
- import * as vscode from 'vscode';
3
- import * as path from 'node:path';
4
- import { LanguageClient, TransportKind } from 'vscode-languageclient/node.js';
5
-
6
- let client: LanguageClient;
7
-
8
- // This function is called when the extension is activated.
9
- export function activate(context: vscode.ExtensionContext): void {
10
- client = startLanguageClient(context);
11
- }
12
-
13
- // This function is called when the extension is deactivated.
14
- export function deactivate(): Thenable<void> | undefined {
15
- if (client) {
16
- return client.stop();
17
- }
18
- return undefined;
19
- }
20
-
21
- function startLanguageClient(context: vscode.ExtensionContext): LanguageClient {
22
- const serverModule = context.asAbsolutePath(path.join('out', 'language', 'main.cjs'));
23
- // The debug options for the server
24
- // --inspect=6009: runs the server in Node's Inspector mode so VS Code can attach to the server for debugging.
25
- // By setting `process.env.DEBUG_BREAK` to a truthy value, the language server will wait until a debugger is attached.
26
- const debugOptions = { execArgv: ['--nolazy', `--inspect${process.env.DEBUG_BREAK ? '-brk' : ''}=${process.env.DEBUG_SOCKET || '6009'}`] };
27
-
28
- // If the extension is launched in debug mode then the debug server options are used
29
- // Otherwise the run options are used
30
- const serverOptions: ServerOptions = {
31
- run: { module: serverModule, transport: TransportKind.ipc },
32
- debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
33
- };
34
-
35
- const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*.palm');
36
- context.subscriptions.push(fileSystemWatcher);
37
-
38
- // Options to control the language client
39
- const clientOptions: LanguageClientOptions = {
40
- documentSelector: [{ scheme: 'file', language: 'palm' }],
41
- synchronize: {
42
- // Notify the server about file changes to files contained in the workspace
43
- fileEvents: fileSystemWatcher
44
- }
45
- };
46
-
47
- // Create the language client and start the client.
48
- const client = new LanguageClient(
49
- 'palm',
50
- 'Palm',
51
- serverOptions,
52
- clientOptions
53
- );
54
-
55
- // Start the client. This will also launch the server
56
- client.start();
57
- return client;
58
- }
src/language/main-browser.ts DELETED
@@ -1,14 +0,0 @@
1
- import { EmptyFileSystem, startLanguageServer } from 'langium';
2
- import { BrowserMessageReader, BrowserMessageWriter, createConnection } from 'vscode-languageserver/browser.js';
3
- import { createPalmServices } from './palm-module.js';
4
-
5
- declare const self: DedicatedWorkerGlobalScope;
6
-
7
- const messageReader = new BrowserMessageReader(self);
8
- const messageWriter = new BrowserMessageWriter(self);
9
-
10
- const connection = createConnection(messageReader, messageWriter);
11
-
12
- const { shared } = createPalmServices({ connection, ...EmptyFileSystem });
13
-
14
- startLanguageServer(shared);
src/language/main.ts DELETED
@@ -1,13 +0,0 @@
1
- import { startLanguageServer } from 'langium';
2
- import { NodeFileSystem } from 'langium/node';
3
- import { createConnection, ProposedFeatures } from 'vscode-languageserver/node.js';
4
- import { createPalmServices } from './palm-module.js';
5
-
6
- // Create a connection to the client
7
- const connection = createConnection(ProposedFeatures.all);
8
-
9
- // Inject the shared services and language-specific services
10
- const { shared } = createPalmServices({ connection, ...NodeFileSystem });
11
-
12
- // Start the language server with the shared services
13
- startLanguageServer(shared);
src/language/palm-module.ts DELETED
@@ -1,63 +0,0 @@
1
- import type { DefaultSharedModuleContext, LangiumServices, LangiumSharedServices, Module, PartialLangiumServices } from 'langium';
2
- import { createDefaultModule, createDefaultSharedModule, inject } from 'langium';
3
- import { PalmGeneratedModule, PalmGeneratedSharedModule } from './generated/module.js';
4
- import { PalmValidator, registerValidationChecks } from './palm-validator.js';
5
-
6
- /**
7
- * Declaration of custom services - add your own service classes here.
8
- */
9
- export type PalmAddedServices = {
10
- validation: {
11
- PalmValidator: PalmValidator
12
- }
13
- }
14
-
15
- /**
16
- * Union of Langium default services and your custom services - use this as constructor parameter
17
- * of custom service classes.
18
- */
19
- export type PalmServices = LangiumServices & PalmAddedServices
20
-
21
- /**
22
- * Dependency injection module that overrides Langium default services and contributes the
23
- * declared custom services. The Langium defaults can be partially specified to override only
24
- * selected services, while the custom services must be fully specified.
25
- */
26
- export const PalmModule: Module<PalmServices, PartialLangiumServices & PalmAddedServices> = {
27
- validation: {
28
- PalmValidator: () => new PalmValidator()
29
- }
30
- };
31
-
32
- /**
33
- * Create the full set of services required by Langium.
34
- *
35
- * First inject the shared services by merging two modules:
36
- * - Langium default shared services
37
- * - Services generated by langium-cli
38
- *
39
- * Then inject the language-specific services by merging three modules:
40
- * - Langium default language-specific services
41
- * - Services generated by langium-cli
42
- * - Services specified in this file
43
- *
44
- * @param context Optional module context with the LSP connection
45
- * @returns An object wrapping the shared services and the language-specific services
46
- */
47
- export function createPalmServices(context: DefaultSharedModuleContext): {
48
- shared: LangiumSharedServices,
49
- Palm: PalmServices
50
- } {
51
- const shared = inject(
52
- createDefaultSharedModule(context),
53
- PalmGeneratedSharedModule
54
- );
55
- const Palm = inject(
56
- createDefaultModule({ shared }),
57
- PalmGeneratedModule,
58
- PalmModule
59
- );
60
- shared.ServiceRegistry.register(Palm);
61
- registerValidationChecks(Palm);
62
- return { shared, Palm };
63
- }
src/language/palm-validator.ts DELETED
@@ -1,32 +0,0 @@
1
- import type { ValidationAcceptor, ValidationChecks } from "langium";
2
- import type { PalmAstType, Type } from "./generated/ast.js";
3
- import type { PalmServices } from "./palm-module.js";
4
-
5
- /**
6
- * Register custom validation checks.
7
- */
8
- export function registerValidationChecks(services: PalmServices) {
9
- const registry = services.validation.ValidationRegistry;
10
- const validator = services.validation.PalmValidator;
11
- const checks: ValidationChecks<PalmAstType> = {
12
- Type: validator.checkPersonStartsWithCapital,
13
- };
14
- registry.register(checks, validator);
15
- }
16
-
17
- /**
18
- * Implementation of custom validations.
19
- */
20
- export class PalmValidator {
21
- checkPersonStartsWithCapital(t: Type, accept: ValidationAcceptor): void {
22
- if (t.name) {
23
- const firstChar = t.name.substring(0, 1);
24
- if (firstChar.toUpperCase() !== firstChar) {
25
- accept("warning", "Person name should start with a capital.", {
26
- node: t,
27
- property: "name",
28
- });
29
- }
30
- }
31
- }
32
- }
src/language/palm.langium DELETED
@@ -1,111 +0,0 @@
1
- grammar Palm
2
-
3
- entry Program:
4
- Module (types+=Type | functions+=FunctionDefinition<false, false>)*;
5
-
6
- Module:
7
- 'module' name=ID;
8
-
9
- Type:
10
- Primitive | Enum | Struct; //Trait | Entity | Extension;
11
-
12
- Primitive:
13
- 'primitive' name=ID '{'
14
- (methods+=FunctionDefinition<true, false>)*
15
- '}';
16
-
17
- Enum:
18
- 'enum' name=ID Generics '{'
19
- (fields+=EnumField)*
20
- (methods+=FunctionDefinition<true, false>)*
21
- '}';
22
-
23
- EnumField:
24
- name=ID ('(' (params+=Param (',' params+=Param)*)? ')')?;
25
-
26
- // Trait:
27
- // 'trait' name=ID Generics '{'
28
- // (methods+=FunctionDefinition<true, true>)*
29
- // '}';
30
-
31
- // Extension:
32
- // 'extension' name=ID 'on' type=[Entity] '{'
33
- // (methods+=FunctionDefinition<true, false>)*
34
- // '}';
35
-
36
- Struct:
37
- 'struct' name=ID Generics
38
- (fields+=Field)*
39
- (methods+=FunctionDefinition<true, false>)*
40
- ;
41
-
42
- Field:
43
- WS WS 'val' names+=ID ':' type=[Type:ID] NL;
44
-
45
- fragment Generics:
46
- ('<' generics+=GENERIC_ID (',' generics+=GENERIC_ID)* '>')?;
47
-
48
- QualifiedName returns string:
49
- ID ('.' ID)*;
50
-
51
- type AbstractDefinition = FunctionDefinition | Param;
52
-
53
- FunctionDefinition<isMethod, isTrait>:
54
- (<isMethod> static?='static')?
55
- 'fn' name=ID '(' (params+=Param (',' params+=Param)*)? ')' (returns+=ReturnType (',' returns+=ReturnType)*)? (<!isTrait> Block);
56
-
57
- ParamType:
58
- type=[Type] (nilable?='?')?;
59
-
60
- Param:
61
- name=ID ':' type=ParamType;
62
-
63
- fragment Block:
64
- '{' body+=Stmt* '}';
65
-
66
- ReturnType:
67
- type=[Type] (nilable?='?')? (throws?='!')?;
68
-
69
- Stmt: Assignment | FnCall;
70
-
71
- Assignment:
72
- 'const' name=ID '=' rhs=(FnCall|STRING|INT|NUMBER);
73
-
74
- FnCall:
75
- fnName=[FunctionDefinition:ID] '(' (args+=Expression (',' args+=Expression)*)? ')';
76
-
77
- Expression:
78
- Addition;
79
-
80
- Addition infers Expression:
81
- Multiplication ({infer BinaryExpression.left=current} operator=('+' | '-') right=Multiplication)*;
82
-
83
- Multiplication infers Expression:
84
- Exponentiation ({infer BinaryExpression.left=current} operator=('*' | '/') right=Exponentiation)*;
85
-
86
- Exponentiation infers Expression:
87
- Modulo ({infer BinaryExpression.left=current} operator='^' right=Modulo)*;
88
-
89
- Modulo infers Expression:
90
- PrimaryExpression ({infer BinaryExpression.left=current} operator='%' right=PrimaryExpression)*;
91
-
92
- PrimaryExpression infers Expression:
93
- '(' Expression ')' |
94
- {infer NumberLiteral} value=NUMBER |
95
- {infer StringLiteral} value=STRING |
96
- {infer ReferenceLiteral} value=[Param:QualifiedName] ('(' args+=Expression (',' args+=Expression)* ')')?;
97
- // {infer FunctionCall} func=[FunctionDefinition:ID] ('(' args+=Expression (',' args+=Expression)* ')')?;
98
-
99
- terminal ID: /[_a-zA-Z][\w_]*/;
100
- terminal GENERIC_ID: /(a|b|c)/;
101
- terminal VAR_ID: /[_a-z][\w_]*/;
102
- terminal INT returns number: /[0-9]+/;
103
- terminal STRING: /"(\\.|[^"\\])*"|'(\\.|[^'\\])*'/;
104
- terminal HEX: /#(\d|[a-fA-F])+/;
105
- terminal NUMBER returns number: /[0-9]+(\.[0-9]*)?[a-z]*/;
106
- terminal WS: /\s/;
107
- terminal NL: /\n/;
108
-
109
- // hidden terminal WS: /\s+/;
110
- hidden terminal ML_COMMENT: /\/\*[\s\S]*?\*\//;
111
- hidden terminal SL_COMMENT: /\/\/[^\n\r]*/;
{public → static}/index.html RENAMED
File without changes
{public → static}/llama.png RENAMED
File without changes
static/monacoClassic.html DELETED
@@ -1,28 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset='utf-8'>
5
- <!-- Page & Monaco styling -->
6
- <link href="styles.css" rel="stylesheet"/>
7
- <title>Palm in Langium</title>
8
- </head>
9
- <body>
10
- <h1>Palm in Langium</h1>
11
- <div class="wrapper">
12
- <b>Monaco-Editor + Monarch</b>
13
- <!-- Monaco Root -->
14
- <div id="monaco-editor-root"></div>
15
- </div>
16
- <footer>
17
- <p style="font-style:italic">Powered by</p>
18
- <img width="125" src="https://langium.org/assets/langium_logo_w_nib.svg" alt="Langium">
19
- </footer>
20
- <!-- Monaco Configuration -->
21
- <script type="module">
22
- import { executeClassic } from './setupClassic.js';
23
-
24
- // keep a reference to a promise for when the editor is finished starting, we'll use this to setup the canvas on load
25
- const startingPromise = executeClassic(document.getElementById('monaco-editor-root'));
26
- </script>
27
- </body>
28
- </html>
static/monacoExtended.html DELETED
@@ -1,28 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset='utf-8'>
5
- <!-- Page & Monaco styling -->
6
- <link href="styles.css" rel="stylesheet"/>
7
- <title>Palm in Langium</title>
8
- </head>
9
- <body>
10
- <h1>Palm in Langium</h1>
11
- <div class="wrapper">
12
- <b>Monaco-Editor + Textmate</b>
13
- <!-- Monaco Root -->
14
- <div id="monaco-editor-root"></div>
15
- </div>
16
- <footer>
17
- <p style="font-style:italic">Powered by</p>
18
- <img width="125" src="https://langium.org/assets/langium_logo_w_nib.svg" alt="Langium">
19
- </footer>
20
- <!-- Monaco Configuration -->
21
- <script type="module">
22
- import { executeExtended } from './setupExtended.js';
23
-
24
- // keep a reference to a promise for when the editor is finished starting, we'll use this to setup the canvas on load
25
- const startingPromise = executeExtended(document.getElementById('monaco-editor-root'));
26
- </script>
27
- </body>
28
- </html>
static/setup.js DELETED
@@ -1,18 +0,0 @@
1
- import { buildWorkerDefinition } from "./monaco-editor-workers/index.js";
2
- buildWorkerDefinition('./monaco-editor-workers/workers', new URL('', window.location.href).href, false);
3
-
4
- export const configureWorker = () => {
5
- const workerURL = new URL('./worker/palm-server-worker.js', import.meta.url);
6
- console.log(`Using the following worker URL: ${workerURL.href}`);
7
- const lsWorker = new Worker(workerURL.href, {
8
- type: 'classic',
9
- name: 'Palm Language Server'
10
- });
11
-
12
- return {
13
- options: {
14
- $type: 'WorkerDirect',
15
- worker: lsWorker
16
- }
17
- }
18
- };
static/setupClassic.js DELETED
@@ -1,32 +0,0 @@
1
- import { addMonacoStyles, defineUserServices, MonacoEditorLanguageClientWrapper } from './bundle/index.js';
2
- import monarchSyntax from "../syntaxes/palm.monarch.js";
3
- import { configureWorker } from './setup.js';
4
-
5
- addMonacoStyles('monaco-editor-styles');
6
-
7
- export const setupConfigClassic = () => {
8
- return {
9
- wrapperConfig: {
10
- serviceConfig: defineUserServices(),
11
- editorAppConfig: {
12
- $type: 'classic',
13
- languageId: 'palm',
14
- code: `// Palm is running in the web!`,
15
- useDiffEditor: false,
16
- languageExtensionConfig: { id: 'langium' },
17
- languageDef: monarchSyntax,
18
- editorOptions: {
19
- 'semanticHighlighting.enabled': true,
20
- theme: 'vs-dark'
21
- }
22
- }
23
- },
24
- languageClientConfig: configureWorker()
25
- };
26
- };
27
-
28
- export const executeClassic = async (htmlElement) => {
29
- const userConfig = setupConfigClassic();
30
- const wrapper = new MonacoEditorLanguageClientWrapper();
31
- await wrapper.start(userConfig, htmlElement);
32
- };
static/setupExtended.js DELETED
@@ -1,62 +0,0 @@
1
- import { addMonacoStyles, defineUserServices, MonacoEditorLanguageClientWrapper } from './bundle/index.js';
2
- import { configureWorker } from './setup.js';
3
-
4
- addMonacoStyles('monaco-editor-styles');
5
-
6
- export const setupConfigExtended = () => {
7
- const extensionFilesOrContents = new Map();
8
- const languageConfigUrl = new URL('../language-configuration.json', window.location.href);
9
- const textmateConfigUrl = new URL('../syntaxes/palm.tmLanguage.json', window.location.href);
10
- extensionFilesOrContents.set('/language-configuration.json', languageConfigUrl);
11
- extensionFilesOrContents.set('/palm-grammar.json', textmateConfigUrl);
12
-
13
- return {
14
- wrapperConfig: {
15
- serviceConfig: defineUserServices(),
16
- editorAppConfig: {
17
- $type: 'extended',
18
- languageId: 'palm',
19
- code: `// Palm is running in the web!`,
20
- useDiffEditor: false,
21
- extensions: [{
22
- config: {
23
- name: 'palm-web',
24
- publisher: 'generator-langium',
25
- version: '1.0.0',
26
- engines: {
27
- vscode: '*'
28
- },
29
- contributes: {
30
- languages: [{
31
- id: 'palm',
32
- extensions: [
33
- '.palm'
34
- ],
35
- configuration: './language-configuration.json'
36
- }],
37
- grammars: [{
38
- language: 'palm',
39
- scopeName: 'source.palm',
40
- path: './palm-grammar.json'
41
- }]
42
- }
43
- },
44
- filesOrContents: extensionFilesOrContents,
45
- }],
46
- userConfiguration: {
47
- json: JSON.stringify({
48
- 'workbench.colorTheme': 'Default Dark Modern',
49
- 'editor.semanticHighlighting.enabled': true
50
- })
51
- }
52
- }
53
- },
54
- languageClientConfig: configureWorker()
55
- };
56
- };
57
-
58
- export const executeExtended = async (htmlElement) => {
59
- const userConfig = setupConfigExtended();
60
- const wrapper = new MonacoEditorLanguageClientWrapper();
61
- await wrapper.start(userConfig, htmlElement);
62
- };
static/styles.css DELETED
@@ -1,28 +0,0 @@
1
- html,body {
2
- background: rgb(33,33,33);
3
- font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
4
- color: white;
5
- margin: 0;
6
- }
7
- h1 {
8
- text-align: center;
9
- }
10
- footer {
11
- text-align: center;
12
- color: #444;
13
- font-size: 1.2rem;
14
- margin-bottom: 0.5rem;
15
- }
16
- a:link {
17
- color: gray;
18
- }
19
- a:visited {
20
- color: lightskyblue;
21
- }
22
- /* for monaco */
23
- .wrapper {
24
- padding: 0 5%;
25
- }
26
- #monaco-editor-root {
27
- height: calc(100vh - 7.5rem - 70px);
28
- }
{example/std → std}/bool.mi RENAMED
File without changes
{example/std → std}/http.mi RENAMED
File without changes
{example/std → std}/list.mi RENAMED
File without changes
{example/std → std}/map.mi RENAMED
File without changes
{example/std → std}/math.mi RENAMED
File without changes
{example/std → std}/ranges.mi RENAMED
File without changes
{example/std → std}/str.mi RENAMED
File without changes
tsconfig.json DELETED
@@ -1,24 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2017",
4
- "module": "Node16",
5
- "lib": ["ESNext", "DOM", "WebWorker"],
6
- "sourceMap": true,
7
- "outDir": "out",
8
- "strict": true,
9
- "noUnusedLocals": true,
10
- "noImplicitReturns": true,
11
- "noImplicitOverride": true,
12
- "moduleResolution": "Node16",
13
- "esModuleInterop": true,
14
- "skipLibCheck": true,
15
- "forceConsistentCasingInFileNames": true,
16
- "rootDir": "src"
17
- },
18
- "include": [
19
- "src/**/*.ts"
20
- ],
21
- "exclude": [
22
- "node_modules"
23
- ]
24
- }
tsconfig.monarch.json DELETED
@@ -1,20 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2017",
4
- "module": "ESNext",
5
- "sourceMap": true,
6
- "outDir": "syntaxes",
7
- "strict": true,
8
- "noUnusedLocals": true,
9
- "noImplicitReturns": true,
10
- "noImplicitOverride": true,
11
- "moduleResolution": "node",
12
- "esModuleInterop": true,
13
- "skipLibCheck": true,
14
- "forceConsistentCasingInFileNames": true
15
- },
16
- "include": [
17
- "syntaxes/palm.monarch.ts"
18
- ],
19
- "exclude": ["out", "node_modules"]
20
- }
vite.bundle.config.ts DELETED
@@ -1,26 +0,0 @@
1
- import { defineConfig } from 'vite';
2
- import path from 'node:path';
3
-
4
- export default defineConfig({
5
- build: {
6
- lib: {
7
- entry: path.resolve(__dirname, 'scripts', 'bundle.js'),
8
- name: 'monaco-bundle',
9
- fileName: () => 'index.js',
10
- formats: ['es']
11
- },
12
- outDir: 'static/bundle',
13
- assetsDir: 'static/bundle/assets',
14
- emptyOutDir: true,
15
- rollupOptions: {
16
- output: {
17
- name: 'monaco-bundle',
18
- exports: 'named',
19
- sourcemap: true,
20
- assetFileNames: (assetInfo) => {
21
- return `assets/${assetInfo.name}`;
22
- }
23
- }
24
- }
25
- }
26
- });