### CLI Execution Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation.md Provides an example of how to build the project and run the CLI command to generate MiniLogo commands from a test logo file. ```bash npm run build ./bin/cli generate test.logo ``` -------------------------------- ### Initialize MonacoEditorLanguageClientWrapper Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Demonstrates how to create an instance of MonacoEditorLanguageClientWrapper and start it with a generated user configuration. This involves getting the HTML element, language ID, code, worker, and Monarch grammar. ```typescript // create a wrapper instance const wrapper = new MonacoEditorLanguageClientWrapper(); // start up with a user config await wrapper.start(createUserConfig({ htmlElement: document.getElementById("monaco-editor-root")!, languageId: 'minilogo', code: getMainCode(), worker: getWorker(), monarchGrammar: getMonarchGrammar() })); ``` -------------------------------- ### Langium Language Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/workflow/scaffold.md A simple example demonstrating the usage of 'person' and 'Hello' entities in a Langium DSL, as defined in the generated 'hello-world' extension. ```text person Alice Hello Alice! person Bob Hello Bob! ``` -------------------------------- ### MiniLogo Example Program Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation.md An example of a MiniLogo program that defines and calls a 'test' function, including pen control and movement commands. ```minilogo def test() { pen(down) move(10,10) pen(up) } test() ``` -------------------------------- ### MiniLogo Input Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation.md An example MiniLogo program that defines a 'test' function to draw lines. ```minilogo def test() { pen(down) move(10,10) pen(up) } test() ``` -------------------------------- ### Hello-World Example Syntax Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/workflow/resolve_cross_references.md Illustrates the input syntax for the Hello-World example, demonstrating the use of 'person' declarations and 'Hello' greetings with cross-references to person names. ```text person John person Jane Hello John! Hello Jane! ``` -------------------------------- ### Install Yeoman and Langium Generator Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/workflow/install.md Installs Yeoman and the Langium extension generator globally using npm. This is a prerequisite for Langium development. ```bash npm i -g yo generator-langium ``` -------------------------------- ### Install esbuild Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/code-bundling.md Installs esbuild as a development dependency for bundling your Langium project. ```bash npm i --save-dev esbuild ``` -------------------------------- ### Installing esbuild Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/building_an_extension/_index.md Command to install esbuild as a development dependency, which is used for bundling the extension's code. ```bash npm i --save-dev esbuild ``` -------------------------------- ### Build and Serve Commands Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Demonstrates the command-line instructions to first build the web assets for the Langium project and then start the local development server. ```bash npm run build:web npm run serve ``` -------------------------------- ### MiniLogo Program Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/customizing_cli.md A simple MiniLogo program demonstrating basic commands like 'pen' and 'move'. ```minilogo def test() { pen(down) move(10,10) pen(up) } test() ``` -------------------------------- ### VSCode API Editor Configuration Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md An example of an editorAppConfig using the 'vscodeApi' type, suitable for TextMate grammars. This configuration would be used instead of the 'classic' configuration when TextMate grammars are employed. ```json editorAppConfig: { $type: 'vscodeApi', languageId: id, useDiffEditor: false, code: config.code, ... } ``` -------------------------------- ### Generated JSON Output Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation.md The expected JSON output generated from the example MiniLogo program, representing drawing commands. ```json [ { "cmd": "penDown" }, { "cmd": "move", "x": 10, "y": 10 }, { "cmd": "penUp" } ] ``` -------------------------------- ### Package.json Scripts for Monaco Setup Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Defines npm scripts for preparing public assets and building the web application, including copying Monaco editor worker files. ```json { "prepare:public": "node scripts/prepare-public.mjs", "build:web": "npm run build && npm run prepare:public && npm run build:worker && node scripts/copy-monaco-assets.mjs" } ``` -------------------------------- ### Generate UserConfig for Langium Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md A utility function to generate a UserConfig for a Langium example based on a provided ClassicConfig. It sets up URLs for config and grammar, and generates the Langium config, including editor and language client configurations. ```typescript /** * Generates a valid UserConfig for a given Langium example * * @param config An extended or classic editor config to generate a UserConfig from * @returns A completed UserConfig */ function createUserConfig(config: ClassicConfig): UserConfig { // setup urls for config & grammar const id = config.languageId; // generate langium config return { htmlElement: config.htmlElement, wrapperConfig: { editorAppConfig: { $type: 'classic', languageId: id, useDiffEditor: false, code: config.code, theme: 'vs-dark', languageDef: config.monarchGrammar }, serviceConfig: { enableModelService: true, configureConfigurationService: { defaultWorkspaceUri: '/tmp/' }, enableKeybindingsService: true, enableLanguagesService: true, debugLogging: false } }, languageClientConfig: { options: { $type: 'WorkerDirect', worker: config.worker as Worker, name: `${id}-language-server-worker` } } }; } ``` -------------------------------- ### Setup and Event Listeners for Playground Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/playground/_index.html Initializes the playground environment by setting up Monaco editor, handling share button functionality, and managing the AST view toggle. It also loads grammar and content from URL parameters. ```javascript import { addMonacoStyles, setupPlayground, share, overlay, getPlaygroundState, MonacoEditorLanguageClientWrapper } from "./libs/worker/common.js"; import { buildWorkerDefinition } from "../libs/monaco-editor-workers/index.js"; addMonacoStyles('monaco-styles-helper'); buildWorkerDefinition( "../libs/monaco-editor-workers/workers", new URL("", window.location.href).href, false ); // on doc load addEventListener('load', function() { // get a handle to our various interactive buttons const copiedHint = document.getElementById('copiedHint'); const shareButton = document.getElementById('shareButton'); const grammarRoot = document.getElementById('grammar-root'); const contentRoot = document.getElementById('content-root'); // register a listener for the share button shareButton.onclick = () => { // retrieve the current playground state (grammar + content/program) const playgroundState = getPlaygroundState(); share(playgroundState.grammar, playgroundState.content); // update the display to indicate that the text has been shared shareButton.src = '/assets/checkmark.svg'; copiedHint.style.display = 'block'; // reset again after a second... setTimeout(() => { shareButton.src = '/assets/share.svg'; copiedHint.style.display = 'none'; }, 1000); }; const treeButton = document.getElementById('treeButton'); const grid = document.getElementById('grid'); const key = 'display-ast'; if(localStorage.getItem(key) === 'yes') { grid.classList.toggle('without-tree'); } treeButton.onclick = () => { const shown = !grid.classList.toggle('without-tree'); localStorage.setItem(key, shown ? 'yes' : 'no'); const resizeEvent = new Event('resize'); window.dispatchEvent(resizeEvent); }; const url = new URL(window.location.toString()); const grammar = url.searchParams.get('grammar'); const content = url.searchParams.get('content'); setupPlayground( grammarRoot, contentRoot, grammar, content, overlay ); }); ``` -------------------------------- ### Langium Grammar - Original Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/multiple-languages.md The original Langium grammar for the hello-world example before splitting into dependent languages. ```langium grammar MultipleLanguages entry Model: (persons+=Person | greetings+=Greeting)*; Person: 'person' name=ID; Greeting: 'Hello' person=[Person:ID] '!'; hidden terminal WS: /\s+/; terminal ID: /[_a-zA-Z][\w_]*/; terminal INT returns number: /[0-9]+ લઈને; terminal STRING: /"(\\.|[^"\\])*"|'(\\.|[^'\\])*'/; hidden terminal ML_COMMENT: /\/\*[\s\S]*?\*\//; hidden terminal SL_COMMENT: /\/\/[^\n\r]*/; ``` -------------------------------- ### Install Graphology Packages Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/validation/dependency-loops.md Installs the necessary graphology packages for graph data structures and algorithms like strongly connected components and topological sort. ```bash npm install graphology graphology-components graphology-dag ``` -------------------------------- ### TypeScript Setup for Langium and Monaco Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Configures Langium's language client wrapper and Monaco editor workers using TypeScript. It includes setting up worker definitions and applying necessary styles. ```typescript import { MonacoEditorLanguageClientWrapper, UserConfig } from "monaco-editor-wrapper/bundle"; import { buildWorkerDefinition } from "monaco-editor-workers"; import { addMonacoStyles } from 'monaco-editor-wrapper/styles'; /** * Setup Monaco's own workers and also incorporate the necessary styles for the monaco-editor */ function setup() { buildWorkerDefinition( './monaco-editor-workers/workers', new URL('', window.location.href).href, false ); addMonacoStyles('monaco-editor-styles'); } // The following section describes the instantiation of the language client wrapper, // which is a crucial part of integrating Langium with Monaco. // Previous versions of the monaco-editor-wrapper package (before 2.0.0) required manual property setting. // However, as of version 3.1.0, the constructor for MonacoEditorLanguageClientWrapper accepts a configuration object. // This configuration object allows for more granular control over all properties. // Example of instantiation (details on configuration object properties would follow): // const userConfig: UserConfig = { // // ... configuration properties ... // }; // const languageClient = new MonacoEditorLanguageClientWrapper(userConfig); ``` -------------------------------- ### Langium Service Customization Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/configuration-services.md Demonstrates how to customize Langium services by overriding default implementations or registering new services within a language-specific module file. This leverages the Dependency Injection pattern for flexible architecture. ```typescript import { LangiumServices } from 'langium'; import { CustomArithmeticsServices } from './arithmetics-module'; // Assuming arithmetics-module.ts exists export function createArithmeticsServices(context: DefaultSharedRootContext): Provider { const shared = createDefaultSharedServices(context); const arithmetics = new CustomArithmeticsServices(shared); return { get: () => arithmetics }; } // Example of a custom service implementation (e.g., CustomReferenceFinder) class CustomReferenceFinder extends ReferenceFinder { // Override or extend methods as needed } // Example of a custom module export class CustomArithmeticsServices extends DefaultLangiumServices { constructor(context: DefaultSharedRootContext) { super(context); } // Override the reference finder service override getReferenceFinder(): ReferenceFinder { return new CustomReferenceFinder(); } // Register a new service (example) // override getMyCustomService(): MyCustomService { // return new MyCustomService(); // } } ``` -------------------------------- ### Define Builtin Library Content Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/builtin-library.md Defines the source code for a builtin library using a template literal. This example uses a simple 'hello world' DSL. ```ts export const builtinHelloWorld = ` person Jane person John `.trimLeft(); ``` -------------------------------- ### Custom HelloWorld Scope Provider Implementation Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/workflow/resolve_cross_references.md An example implementation of a custom ScopeProvider for a 'Hello World' language. It demonstrates how to provide a scope for 'person' references within 'greeting' elements by collecting all 'person' nodes from the document. ```typescript import { ReferenceInfo, Scope, ScopeProvider, AstUtils, LangiumCoreServices, AstNodeDescriptionProvider, MapScope, EMPTY_SCOPE } from "langium"; import { isGreeting, isModel } from "./generated/ast.js"; export class HelloWorldScopeProvider implements ScopeProvider { private astNodeDescriptionProvider: AstNodeDescriptionProvider; constructor(services: LangiumCoreServices) { //get some helper services this.astNodeDescriptionProvider = services.workspace.AstNodeDescriptionProvider; } getScope(context: ReferenceInfo): Scope { //make sure which cross-reference you are handling right now if(isGreeting(context.container) && context.property === 'person') { //Success! We are handling the cross-reference of a greeting to a person! //get the root node of the document const model = AstUtils.getContainerOfType(context.container, isModel)!; //select all persons from this document const persons = model.persons; //transform them into node descriptions const descriptions = persons.map(p => this.astNodeDescriptionProvider.createDescription(p, p.name)); //create the scope return new MapScope(descriptions); } return EMPTY_SCOPE; } } ``` -------------------------------- ### Langium Negated Token Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines the 'NONO' terminal rule to match a word that does not start with 'no', using a negated lookahead. ```langium terminal NONO: (!'no')('a'..'z'|'A'..'Z')+; ``` -------------------------------- ### Langium Terminal Group Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines a terminal rule 'FLIGHT_NUMBER' that must start with two capital letters followed by three or four digits. ```langium terminal FLIGHT_NUMBER: ('A'..'Z')('A'..'Z')('0'..'9')('0'..'9')('0'..'9')('0'...'9')?; ``` -------------------------------- ### Browser Entry Point for Langium Language Server Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Sets up a Langium language server to run in a browser environment using `vscode-languageserver/browser.js` and an `EmptyFileSystem`. It establishes communication via `BrowserMessageReader` and `BrowserMessageWriter`. ```ts import { startLanguageServer, EmptyFileSystem } from 'langium'; import { BrowserMessageReader, BrowserMessageWriter, createConnection } from 'vscode-languageserver/browser.js'; // your services & module name may differ based on your language's name import { createMiniLogoServices } from './minilogo-module.js'; declare const self: DedicatedWorkerGlobalScope; /* browser specific setup code */ const messageReader = new BrowserMessageReader(self); const messageWriter = new BrowserMessageWriter(self); const connection = createConnection(messageReader, messageWriter); // Inject the shared services and language-specific services const { shared, MiniLogo } = createMiniLogoServices({connection, ...EmptyFileSystem }); // Start the language server with the shared services startLanguageServer(shared); ``` -------------------------------- ### Customizing Scope Precomputation in Domainmodel Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/document-lifecycle.md Example of customizing scope precomputation in Langium's Domainmodel example, exposing entities within a package declaration using their qualified names. ```typescript // Link to the customization in the Langium repository: // https://github.com/eclipse-langium/langium/blob/main/examples/domainmodel/src/language-server/domain-model-scope.ts ``` -------------------------------- ### Langium Generator API Setup (TypeScript) Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation.md Sets up the main generator function 'generateCommands' which takes a Model, file path, and destination, returning the generated file path. This function serves as the entry point for processing MiniLogo programs for generation. ```typescript import { Model } from '../language/generated/ast.ts'; export function generateCommands(mode: Model, filePath: string, destination: string | undefined): string { // ... } ``` -------------------------------- ### package.json Script for Building Browser Worker Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Defines an npm script (`build:worker`) using `esbuild` to create a minified, IIFE-formatted bundle of the browser language server entry point, outputting it to a file suitable for web workers. ```json { ... "build:worker": "esbuild --minify ./out/language-server/main-browser.js --bundle --format=iife --outfile=./public/minilogo-server-worker.js" } ``` -------------------------------- ### Prepare Public Assets Script (prepare-public.mjs) Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md A Node.js script using esbuild and shelljs to create a public directory, copy static CSS and HTML files, and bundle a TypeScript file into JavaScript. ```javascript import * as esbuild from 'esbuild' import shell from 'shelljs' // setup & copy over css & html to public shell.mkdir('-p', './public'); shell.cp('-fr', './src/static/*.css', './public/'); shell.cp('-fr', './src/static/*.html', './public'); // bundle minilogo.ts, and also copy to public await esbuild.build({ entryPoints: ['./src/static/minilogo.ts'], minify: true, sourcemap: true, bundle: true, outfile: './public/minilogo.js', }); ``` -------------------------------- ### Lexer Output for Python Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/lexing/indentation-sensitive-languages.md The sequence of tokens generated by the lexer for the provided Python code example, illustrating how INDENT, DEDENT, and other terminals are recognized. ```text if, BOOLEAN, INDENT, return, BOOLEAN, DEDENT, else, INDENT, if, BOOLEAN, INDENT, return, BOOLEAN, DEDENT, DEDENT ``` -------------------------------- ### Python Example with Ignored Indentation Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/lexing/indentation-sensitive-languages.md A Python code example showing a list definition where indentation between the opening bracket `[` and closing bracket `]` should be ignored by the parser. ```py x = [ 1, 2 ] ``` -------------------------------- ### package.json Script for Serving Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Adds a 'serve' script to the package.json file, which is used to invoke the compiled Node.js server application. This script assumes the server code is compiled to './out/web/app.js'. ```json { ... "serve": "node ./out/web/app.js" } ``` -------------------------------- ### Python Code Example for Langium Grammar Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/lexing/indentation-sensitive-languages.md An example Python code snippet that conforms to the defined Langium grammar, demonstrating the structure of if-else statements and return statements. ```python if true: return false else: if true: return true ``` -------------------------------- ### Lexical Scoping Example in TypeScript Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/scoping/_index.md Demonstrates lexical scoping where variables declared within a block are only accessible within that block. This example shows how 'x' is accessible globally, while 'y' is local to the 'if' block. ```ts let x = 42; x = 3; // References the `x` defined in the previous line if (condition) { let y = 42; } y = 3; // Cannot link, `y` isn't in any of the available scopes ``` -------------------------------- ### Page Description and Rendering Logic Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/layouts/langium/list.html This Go template code describes how pages with lists of items, like the showcase, are structured and rendered. It iterates through pages, checking for draft status, and displays their associated image, title, description, and external links. ```go {{/\* Describes pages w/ lists of items, like the showcase *//*}} {{ define "main" }} {{ .Content }} {{range where .Pages.ByWeight ".Params.draft" false}} {{ if .Params.url }} [{{ else if .Params.externalUrl }}]({{.Params.url}}) [{{ end }} ![]({{.Params.img}}) {{.Title}} {{ if .Params.externalUrl }} ![](/assets/external_link.svg) {{ end }} -------------------------------------------------------------------------------- {{.Params.description}} ]({{.Params.externalUrl}}) {{end}} {{ end }} ``` -------------------------------- ### HTML Structure for Langium and Monaco Integration Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Provides the basic HTML structure for a page that integrates Langium with the Monaco editor. It includes placeholders for CSS, the editor, a canvas, and status messages. ```html MiniLogo in Langium

MiniLogo in Langium


``` -------------------------------- ### Test HelloWorld Service with Sample Data Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/performance/caches.md Provides a sample .hello file content to test the HelloWorld service, demonstrating the expected input format and potential validation warnings. ```plaintext person Wonderwoman person Spiderman person Homer //warning: unknown publisher!! person Obelix ``` -------------------------------- ### Build and Serve MiniLogo Web Application Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation_in_the_web.md Commands to build the MiniLogo project for the web and serve it locally. Assumes the generator script is executed by `build:web`. ```bash npm run build:web npm run serve ``` -------------------------------- ### Langium Until Token Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines the 'ML_COMMENT' terminal rule to consume characters from '/*' until '*/'. ```langium terminal ML_COMMENT: '/*' -> '*/'; ``` -------------------------------- ### Langium Wildcard Token Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines the 'HASHTAG' terminal rule to match a '#' followed by one or more characters. ```langium terminal HASHTAG: '#'.+; ``` -------------------------------- ### TypeScript Scoping Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/introduction/features.md Illustrates variable scoping in TypeScript, highlighting how references are resolved within different scopes. ```typescript let x = 42; x = 3; // References the `x` defined in the previous line if (something) { let y = 42; } y = 3; // Cannot link, `y` isn't in any of the available scopes ``` -------------------------------- ### Build Assets with Gulp Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/themes/hugo-geekdoc/README.md This snippet demonstrates how to install npm packages and run the default gulp pipeline to build necessary assets for the Geekdoc Hugo theme. This is required if you want to use the theme from a cloned branch instead of a release tarball. ```Shell # install required packages from package.json npm install # run gulp pipeline to build required assets npx gulp default ``` -------------------------------- ### Langium Terminal Rule Call Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines the 'DOUBLE' terminal rule by calling the 'INT' terminal rule. ```langium terminal DOUBLE returns number: INT '.' INT; ``` -------------------------------- ### Langium Terminal Fragments Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines terminal fragments 'CAPITAL_LETTER' and 'SMALL_LETTER' and uses them in the 'NAME' terminal rule. ```langium terminal fragment CAPITAL_LETTER: ('A'..'Z'); terminal fragment SMALL_LETTER: ('a'..'z'); terminal NAME: CAPITAL_LETTER SMALL_LETTER+; ``` -------------------------------- ### MiniLogo Language Server Worker Initialization Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Sets up the initialization of the language server worker for MiniLogo, specifying the worker script URL. ```ts /** * Creates & returns a fresh worker using the MiniLogo language server */ function getWorker() { const workerURL = new URL('minilogo-server-worker.js', window.location.href); // ... rest of the worker setup } ``` -------------------------------- ### Formatting DomainModel Root Node Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/formatting.md Example of formatting the root DomainModel node, realigning its elements using Formatting.noIndent. ```ts if (ast.isDomainmodel(node)) { // Create a new node formatter const formatter = this.getNodeFormatter(node); // Select a formatting region which contains all children const nodes = formatter.nodes(...node.elements); // Prepend all these nodes with no indent nodes.prepend(Formatting.noIndent()); } ``` -------------------------------- ### Build and Run Langium CLI Commands Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/customizing_cli.md Commands to generate language artifacts and build the project, enabling CLI usage. ```bash npm run langium:generate npm run build ``` -------------------------------- ### Registering Model Validation Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/validation.md Example of registering a validation function for 'Model' nodes using Langium's ValidationChecks. ```typescript import { Model } from './generated/ast'; ... const checks: ValidationChecks = { Model: (m: Model, accept: ValidationAcceptor) => { // and validate the model 'm' here } }; ``` -------------------------------- ### Langium Character Range Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines the 'INT' terminal rule to match one or more digits using a character range. ```langium terminal INT returns number: ('0'..'9')+; ``` -------------------------------- ### ExpressJS Server for Langium Assets Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md A simplified server implementation using the Express.js framework to serve static files from the './public' directory. This approach is more concise and relies on the Express middleware for static file serving. ```javascript /** * Simple express app for serving generated examples */ import express from 'express'; const app = express(); const port = 3000; app.use(express.static('./public')); app.listen(port, () => { console.log(`Server for MiniLogo assets listening on http://localhost:${port}`); }); ``` -------------------------------- ### Langium Grammar Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/introduction/features.md Defines a simple 'Person' rule in Langium grammar, demonstrating keyword usage and semantic assignment to an ID. ```langium Person: 'person' // keyword name=ID // semantic assignment ; ``` -------------------------------- ### Register generateAction in CLI Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation.md Connects the `generateCommands` function to the CLI by modifying the `generateAction` endpoint. It creates Langium services, extracts the AST node, calls `generateCommands`, and logs a success message with the generated file path. ```ts export const generateAction = async (fileName: string, opts: GenerateOptions): Promise => { const services = createHelloWorldServices(NodeFileSystem).HelloWorld; const model = await extractAstNode(fileName, services); // now with 'generateCommands' instead const generatedFilePath = generateCommands(model, fileName, opts.destination); console.log(chalk.green(`MiniLogo commands generated successfully: ${generatedFilePath}`)); }; ``` -------------------------------- ### Open Project in VS Code Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/workflow/scaffold.md Command to open the newly generated Langium project directory in Visual Studio Code. ```bash code hello-world ``` -------------------------------- ### Plain Text Person Definitions Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/scoping/file-based.md Defines several 'Person' entities, with some marked for export. This serves as the source file for the import example. ```plain export person Homer export person Marge person Bart person Lisa export person Maggy ``` -------------------------------- ### C++ Qualified Name Scoping Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/scoping/qualified-name.md Demonstrates how to call a function within a namespace using its qualified name in C++. ```cpp namespace Langium { void getDocumentation(); } void main() { // Should call the `getDocumentation` function defined in the `Langium` namespace Langium::getDocumentation(); } ``` -------------------------------- ### CSS Styling for Langium and Monaco Page Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Defines the CSS styles for the static page, including layout for the Monaco editor and canvas, general page styling, and responsive adjustments. ```css html,body { background: rgb(33,33,33); font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; color: white; /* for monaco */ margin: 0; padding: 0; width: 100%; height: 100%; } h1 { text-align: center; } #minilogo-canvas { display: block; margin: 8px auto; text-align: center; } #page-wrapper { display: flex; max-width: 2000px; margin: 4px auto; padding: 4px; min-height: 75vh; justify-content: center; } #page-wrapper .half { display: flex; width: 40vw; } .build { display: block; margin: 8px auto; width: 300px; height: 30px; background: none; border: 2px #fff solid; color: #fff; transition: 0.3s; font-size: 1.2rem; border-radius: 4px; } .build:hover { border-color: #6cf; color: #6cf; cursor: pointer; } .build:active { color: #fff; border-color: #fff; } footer { text-align: center; color: #444; font-size: 1.2rem; margin-bottom: 16px; } @media(max-width: 1000px) { #page-wrapper { display: block; } #page-wrapper .half { display: block; width: auto; } #minilogo-canvas { margin-top: 32px; } #page-wrapper { min-height: auto; } } /* for monaco */ .wrapper { display: flex; flex-direction: column; height: 100%; width: 100%; } #monaco-editor-root { flex-grow: 1; } #status-msg { color: red; } ``` -------------------------------- ### Langium Terminal Alternatives Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Defines the 'STRING' terminal rule using alternatives to match sequences enclosed in double or single quotes. ```langium terminal STRING: '"' !('"')* '"' | "'" !("'")* "'"; ``` -------------------------------- ### Langium + Monaco Editor Integration Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md This section details the integration of Langium with the Monaco editor for web applications. It highlights the technologies required and the general approach to setting up a Langium language for a web-based environment. ```markdown ## Technologies You'll Need - [Langium](https://www.npmjs.com/package/langium) 2.0.2 - [Monaco Editor Wrapper](https://www.npmjs.com/package/monaco-editor-wrapper) 3.1.0 - [ESBuild](https://www.npmjs.com/package/esbuild) 0.18.20 or greater ## Getting your Language Setup for the Web To begin, you're going to need a Langium-based language to work with. We have already written [MiniLogo](https://github.com/TypeFox/langium-minilogo) in Langium as an example for deploying a language in the web. However, if you've been following along with these tutorials so far, you should be ready to move your own language into a web-based context. Per usual, we'll be using MiniLogo as the motivating example here. ``` -------------------------------- ### Comment Out Generator Logic (TypeScript) Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/customizing_cli.md Example of commenting out generator function contents in `src/cli/generator.ts` to resolve TypeScript errors during CLI development. ```typescript // Comment out or remove the generator function's contents // return ""; // Comment/remove imports to make Typescript happy. ``` -------------------------------- ### Package.json Configuration for Extension Icon Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/building_an_extension/_index.md Configuration within package.json to specify the extension's icon. The 'icon' property should point to the relative path of the icon image file. ```json { "name": "minilogo", "displayName": "minilogo", "icon": "icon.png", "publisher": "TypeFox", ... } ``` -------------------------------- ### Initialize Canvas and Context Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/generation_in_the_web.md Gets a handle on the HTML canvas element and its 2D rendering context. Throws an error if the canvas or context cannot be found. ```ts const canvas : HTMLCanvasElement | null = document.getElementById('minilogo-canvas') as HTMLCanvasElement | null; if (!canvas) { throw new Error('Unable to find canvas element!'); } const context = canvas.getContext('2d'); if (!context) { throw new Error('Unable to get canvas context!'); } ``` -------------------------------- ### Plaintext Dependency Resolution Example Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/validation/dependency-loops.md Shows a simple dependency graph represented in plaintext, illustrating the order in which elements can be processed without loops. ```plaintext A -> B -> C A -> C C -> D //resolution: A, B, C, D ``` -------------------------------- ### Registering File System Provider Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/recipes/builtin-library.md Activates the extension by registering the DslLibraryFileSystemProvider. This function is typically called on extension activation. ```typescript export function activate(context: vscode.ExtensionContext) { DslLibraryFileSystemProvider.register(context); } ``` -------------------------------- ### Minilogo For Loop Syntax Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/writing_a_grammar.md Defines the parser rule for a 'for' loop in Minilogo, including a variable, start and end expressions, and a block of statements. ```langium For: 'for' var=Param '=' e1=Expr 'to' e2=Expr Block; ``` -------------------------------- ### Langium Configuration for Monarch Output Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/minilogo/langium_and_monaco.md Specifies the output path for the generated Monarch grammar file in the `langium-config.json` configuration. ```json { "textMate": { "out": "syntaxes/minilogo.tmLanguage.json" }, "monarch": { "out": "syntaxes/minilogo.monarch.ts" } } ``` -------------------------------- ### Langium Development Workflow Diagram Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/learn/workflow/_index.md Visual representation of the Langium language development process, showing the sequence of steps from installation to artifact generation and advanced topics. ```mermaid flowchart TD A(["1. Install Yeoman"]); B(["2. Scaffold a Langium project"]); C(["3. Write the grammar"]); D(["4. Generate the AST"]); E(["5. Resolve cross-references"]); F(["6. Create validations"]); G(["7. Generate artifacts"]); H(["Find advanced topics"]); A --> B --> C --> D --> E --> F --> G ~~~ H; G -- for each additional
grammar change --> C; click A "/docs/learn/workflow/install" click B "/docs/learn/workflow/scaffold" click C "/docs/learn/workflow/write_grammar" click D "/docs/learn/workflow/generate_ast" click E "/docs/learn/workflow/resolve_cross_references" click F "/docs/learn/workflow/create_validations" click G "/docs/learn/workflow/generate_everything" click H "/docs/recipes" ``` -------------------------------- ### Langium Website HTML Structure and Partials Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/layouts/playground/baseof.html Illustrates the HTML structure of the Langium website, including the use of partials for headers, footers, and scripts, and placeholders for content like grammar, content, and syntax trees. ```html {{ partial "langium-head" . }} {{ partial "langium-header" . }} Grammar Content ![](/assets/tree.svg "Toggle syntax tree view") ![](/assets/share.svg "Copy URL to this grammar and content") Link was copied! Loading... Syntax tree {{ block "main" . }} {{ end }} {{ partial "langium-footer" . }} {{ partial "langium-mobile-menu" . }} {{ partial "langium-scripts" . }} ``` -------------------------------- ### Langium Cross-References Source: https://github.com/eclipse-langium/langium-website/blob/main/hugo/content/docs/reference/grammar-language.md Demonstrates how to declare and use cross-references in Langium grammars, allowing elements to reference other objects by a token. Includes examples of successful and failed resolution. ```langium property=[Type:TOKEN] Person: 'person' name=ID; Greeting: 'Hello' person=[Person:ID] '!'; ``` ```langium person Bob Hello Bob ! ``` ```langium person Bob Hello Sara ! ```