verification tool for a less file's syntax

Searching for a tool to validate a specific less file at the syntax level. The issue lies in the validator not recognizing dependencies or detecting declared mixins.

Many existing less processors do not work due to missing dependencies that cannot be provided during this stage of the process.

An npm package would be the ideal solution for my needs.

Answer №1

After much consideration, I finally opted to utilize antlr4

Here are the steps I followed:

  • install antlr on the computer or include it in the deployment process
  • obtain the grammar for your language (some of it may already be completed)
  • acquire the npm package needed to process the grammar
  • Integrate it into your application

The setup includes these commands:

$ cd /usr/local/lib
$ sudo curl -O http://www.antlr.org/download/antlr-4.5-complete.jar
$ export CLASSPATH=".:/usr/local/lib/antlr-4.5-complete.jar:$CLASSPATH"
$ alias antlr4='java -jar /usr/local/lib/antlr-4.5-complete.jar'
$ alias grun='java org.antlr.v4.runtime.misc.TestRig

This information is sourced directly from the webpage.

You can now obtain the grammar from https://github.com/antlr/grammars-v4

At this stage, you can generate the JavaScript version of your grammar

In my scenario, I established a directory, downloaded the files, and implemented all my tests within it:

antlr4 -Dlanguage=JavaScript LessParser.g4
antlr4 -Dlanguage=JavaScript LessLexer.g4

This process generates a JavaScript file that you will need, but the antlr library is required to use these files in your node program.

npm link antlr4

Now, the coding begins:

var antlr4 = require('antlr4/index');
var MyGrammarLexer = require('./LessLexer.js');
var MyGrammarParser = require('./LessParser.js');
var input = "html{ .hey(); color: @light-blue; background:#333}";
var chars = new antlr4.InputStream(input);
var lexer = new MyGrammarLexer.LessLexer(chars);
var tokens  = new antlr4.CommonTokenStream(lexer);
var parser = new MyGrammarParser.LessParser(tokens);
parser.buildParseTrees = true;

var ErrorListener = antlr4.error.ErrorListener;
function CustomErrorListener() {
   ErrorListener.call(this);
   return this;
}

CustomErrorListener.prototype = Object.create(ErrorListener.prototype);
CustomErrorListener.prototype.constructor = CustomErrorListener;
CustomErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {
    throw ('throw a simple exception');
};

parser.addErrorListener(new CustomErrorListener());

try{
  var tree = parser.stylesheet();
} catch (e){
  console.log('I catch you!!!')
}

The crucial elements in this code are the functions lessLexer, lessParser, and parser.stylesheet(); These differ for each grammar. The last one is where you specify the point in the grammar that needs validation. In my case, I utilized the file LessParser.g4, which outlines various nodes in the grammar definition:

parser grammar LessParser;

options { tokenVocab=LessLexer; }

stylesheet
  : statement*
  ;

statement
  : importDeclaration
  | ruleset
  | variableDeclaration ';'
  | mixinDefinition
  ;

variableName
  : AT variableName
  | AT Identifier
  ;

commandStatement
  : (expression+) mathStatement?
  ;

mathCharacter
  : TIMES | PLUS | DIV | MINUS | PERC
  ;

With this information, you can validate strings like a stylesheet, statement, variableName...

Lastly, the Error Validation aspect is noteworthy, as I used it to halt validation at the first error encountered. While my implementation is basic, there is potential for further enhancements in this area

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Watch for changes in a nested collection in Angular using $scope.$watch

Within my Angular application, there is a checkbox list that is dynamically generated using nested ng-repeat loops. Here is an example of the code: <div ng-repeat="type in boundaryPartners"> <div class="row"> <div class="col-xs- ...

The method firebaseApp.auth does not exist in user authentication using Firebase

Implementing user authentication with Firebase in my React webapp has been a challenge due to issues with the firebaseAuth.app() function. Despite trying various solutions such as reinstalling firebase dependencies, updating imports to SDK 9 syntax, and ad ...

Issues with Firebase-admin preventing writing to the database are occurring without any error messages being displayed

Issues with Firebase admin writing to the database. The database is instantiated as follows: var db = admin.database(); A reference to the desired table is then set up: var systemsRef = db.ref("systems/"); A function is created to check if a 'sys ...

Endless asynchronous loops with setInterval()

My nodejs application requires multiple infinite loops that call asynchronous functions. I was contemplating the following approach: async function process1() { ...perform some asynchronous tasks... } async function process2() { ...perform some as ...

Creating a seamless REST API using Node.js and the Tedious library: A comprehensive guide

I am facing an issue with retrieving SQL data in my Express API. The page is continuously loading and showing a blank screen, however I can see the SQL data response in the console. Here is my index.js code : var Connection = require("tedious"). ...

Modify the limit for asynchronous mapping with mapLimit

Can the limit parameter in async.mapLimit be modified after the function has already been invoked? I'm developing an HTTP loader and would like to decrease the limit if there are more frequent occurrences of HTTP errors. https://github.com/caolan/as ...

Introducing Material UI Onepirate: Troubleshooting the Mysterious ENOENT Issue at Launch

Upon attempting to launch the 'Material UI Onepirate' template with 'pnpm start', I encountered an error indicating that the 'BUILD_ID' file was missing. Despite installing all necessary pnpm dependencies, the issue persisted. ...

Importance of Security in ExpressJS' req and res Object ParametersSecurity is

In my express app, I wanted to ensure that the current user is logged in by implementing a global variable called current_user. To achieve this, I added a middleware: app.use(require('./controller/user').auth_user); In the user.js file, I creat ...

Encountered an ENOTFOUND localhost error while attempting to run a Vue project

I've set up a new nuxt project and when I attempt to run it using the npm run dev or yarn dev command, I encounter this error: build [================== ] 91%Error: getaddrinfo ENOTFOUND localhost at errnoException (dns.js:50:10) at Get ...

Modifying the color of a div based on a specified value using JavaScript

<div id="navigation"> Add your text here </div> <input type="text" id="newColor"><button onclick="modifyColor()">Update</button> <script> function modifyColor(){ var chosenColor = document.getElementB ...

In Vue.js, utilize a contenteditable div to dynamically add an HTML element and bind it with v-model

Below is the HTML code I have written. <div id="app"> <button @click="renderHtml">Click to append html</button> <div class="flex"> <div class="message" @input="fakeVmodel" v-html="html" contenteditable="true">< ...

numerous requests being made to servers during the setup of a basic node server

problem: Upon visiting http://localhost:3000/, I am noticing 3 sets of console logs instead of the expected 2. desired outcome: I should only see two console.logs displayed: First middleware Second middleware The issue lies within my server.js and app.js ...

Having trouble with the installation of Cypress using NPM? Receive the error message "spawn C:Program ENOENT"?

Struggling with this error for an entire day, unable to find a solution online. I have two laptops side by side - one where Node.js and Cypress are installed without issues, and the other throwing errors. I've tried everything from reinstalling, chang ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

The req.session object in express-session remains empty for each request, even after it has been initialized

I am facing an issue where even after logging in, I am unable to access the protected route because the middleware is checking for a user session before allowing access to that route. Express-session Below is the session middleware code: app.use(session({ ...

"Encountering a 404 error while attempting to forward to an HTML

I've been encountering an issue while trying to transition from a JSX page to an HTML page. Every time I attempt to do so, I receive a 404 error stating that the page doesn't exist. It's puzzling because it is clearly present in my files and ...

Error in Node: resolve-url-loader - CSS resolution error

Trying to set up a React project as the development server on my Surface has been causing issues, unlike when I run the same configuration on my PC. Despite trying to replicate the same conditions, the problem persists. The error message received is: ./s ...

The rendering of the component is experiencing issues when using react-router

function App() { return ( //Following BEM naming convention <div className="app"> <div className="app__body"> <Sidebar /> <Chat /> <Router> <Routes> ...

The Javascript function must be executed with each page reload

Currently, I am analyzing an asp.net 2 web application that is in my care (even though I did not create it). There seems to be an issue with certain functionalities not working consistently when the page loads, particularly if using Firefox 3 within a vir ...

Unable to launch React Native project

Error: Module Not Found Cannot find module 'C:\Users\Admin\AppData\Local\npm-cache\_npx\7930a8670f922cdb\node_modules\@babel\parser\lib\index.js'. Please make sure that your package.jso ...