Integrating new features into the bison/jison calculator programming language

Looking to enhance the functionality of the Jison calculator example by introducing some basic functions. As someone new to parsing and bison/jison, here's a glimpse of my progress so far:

/* lexical grammar */
%lex

%{
  var funcs = {
    pow: function(a, b) { return Math.pow(a, b); },
    test: function(a) { return a*2; }
  }
%}

%%

\s+                   /* skipping whitespace */
[0-9]+("."[0-9]+)?\b  return 'NUMBER'
[a-zA-Z]+             return 'NAME'
","                   return ','
"*"                   return '*'
"("                   return '('
")"                   return ')'
<<EOF>>               return 'EOF'
.                     return 'INVALID'

/lex

%start expressions

%% /* language grammar */
expressions
    : e EOF
      { return $1; }
    ;

expression_list
    : expression_list ',' e
    | e
    ;

e
    : e '*' e
        {$$ = $1*$3;}
    | '(' e ')'
        {$$ = $2;}
    | NUMBER
        {$$ = Number(yytext);}
    | NAME '(' expression_list ')'
        {$$ = funcs[$NAME]($expression_list);}
    ;

Encountering an issue where functions are only receiving a single argument. For instance:

test(2) -> 4
pow(2,3) -> null

Upon console.log of arguments for pow, it seems that b is not properly defined. The question remains why the full expression list isn't being parsed before passing it to the function?

Answer №1

The provided code implements the requested functionality. Key points to note:

  1. The expression_list rules now generate a list of values for use with the called functions.

  2. The list created by expression_list is passed to apply, becoming the arguments for the function (undefined is used as the first argument to set the value of this to undefined).

  3. A console.log statement has been included in the actions for expression to display information when running the resulting parser from the command line.

  4. The definition of funcs has been moved to the beginning to resolve placement issues that occurred in the final file during jison compilation.

Below is the updated code:

%{var funcs = {
    pow: function(a, b) { return Math.pow(a, b); },
    test: function(a) { return a*2; }
  }
%}

/* lexical grammar */
%lex

%%

\s+                   /* skip whitespace */
[0-9]+("."[0-9]+)?\b  return 'NUMBER'
[a-zA-Z]+             return 'NAME'
","                   return ','
"*"                   return '*'
"("                   return '('
")"                   return ')'
<<EOF>>               return 'EOF'
.                     return 'INVALID'

/lex

%start expressions

%% /* language grammar */
expressions
    : e EOF
      { console.log($1); return $1; }
    ;

expression_list
    : expression_list ',' e
      { $$ = $1.concat([$3]); }
    | e
      { $$ = [$1]; }
    ;

e
    : e '*' e
        {$$ = $1*$3;}
    | '(' e ')'
        {$$ = $2;}
    | NUMBER
        {$$ = Number(yytext);}
    | NAME '(' expression_list ')'
        {$$ = funcs[$NAME].apply(undefined, $expression_list);}
    ;

Answer №2

In order to trigger the first production for expression_list, an action is required. The current default action simply duplicates $1 into $$, resulting in the added value being disregarded.

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

What is the best way to dynamically render classes based on conditions in a table using React Bootstrap?

I am looking for a way to dynamically change the color of a class based on the transaction data in a table. import React from "react"; import Table from "react-bootstrap/Table"; import "./TableComponent.css"; const TableComponent = ({ Movement }) =&g ...

React: Enhancing the URL with a File Name

Has anyone encountered the issue where index.css is showing up as the :id in axios requests? I recently configured a proxy in React to deploy to Heroku with the setting "proxy": "http://localhost:3001/". However, after setting up the p ...

Continuously animate a series of CSS properties

Here's the code snippet I'm working with: @keyframes ball1 { 0% { transform: translateX(0px); opacity: 0%; } 50% { opacity: 100%; } 100% { transform: translateX(120px); opacity: 0%; } } @keyframes ball2 { 0 ...

Locate elements with Jquery after displaying HTML content

I am encountering an issue with the code snippet below: tblBody = $('#tbody'); tblBody.html(rowsStr.join('')); var lines = tblBody.find("tr"); The array rowsStr contains strings that create tr and td tags. Sometimes, when I use tblB ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

Retrieve the name of the selected item in the antd dropdown component

I am facing an issue where I cannot retrieve the name of the select component in Ant Design to use the handleInputChange function on its onChange event. As a workaround, I decided to update the state directly in the onChange event by adding it to an obje ...

gulp-watch does not monitor files that are newly created or deleted

Currently working on a task: gulp.task('assetsInject', function () { gulp.src(paths.index) .pipe(plugins.inject( gulp.src(paths.scripts, {read: false}), { addRootSlash: false } ...

Here's a guide on passing a test case that involves using enzyme's shallow method with the contains function when testing a React component with an event

I'm struggling to pass a test that uses .contain when the react component contains an event handler. Here is an example: Foo.js const Foo = React.createClass({ render () { return ( <p onClick={() => {}}>I am not ...

Tips for recognizing when Vuetify's v-autocomplete has reached the final scrolled item

I am working with a Vuetify v-autocomplete component and I need to implement a feature where I can detect when the user reaches the last item while scrolling, in order to load more items without the user having to manually type for search: // component.vue ...

display only the offspring of jquery

I'm encountering an issue: I've used classes on a div for simplicity, and I want to display a hidden div after a click, but only on that specific div. The problem is, it shows on all divs instead of just the one being clicked. I've tried dif ...

Using react-router to fetch data from the server side

I have successfully implemented React-router server-side rendering in my express app using the following code snippet: app.use((req, res) => { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { console.log(renderProps) ...

Issue with jQuery AJAX request not working as expected

I'm currently utilizing Rapid API to store my users' emails and passwords. Upon clicking, my send function should trigger, however, it seems that the program is not progressing through the AJAX call. I'm at a loss on how to proceed. Any ass ...

How to create a see-through background using three.js

I am new to working with three.js and recently came across a codepen that caught my attention. However, I am facing difficulties while trying to change the background color. After exploring various questions related to this issue, I attempted to add { alp ...

What is causing the consistent error message "unable to read property 'logged' of undefined"?

Here is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie- ...

Lifetime of local variables in Javascript

Although I am adept in C and C++, Javascript is a new realm for me. Currently, I am delving into three.js but finding it challenging to grasp this particular concept: var camera, scene, renderer, control; init(); function init() { scene = new THREE. ...

Uninstalling an Element Using jQuery

There is a requirement to dynamically insert city names into the input field with the ID citiesList. If the value of the input field is empty and the user clicks on the cancel button, then the input should be deleted. However, upon clicking the edit but ...

The functionality of res.send is not working correctly

Attempting to send a response from my express application to the front-end in order to display an alert. Here is what I have attempted in my app: if (info.messageId) { res.redirect('back'); res.send({ success: true }); } ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

Exploring the functionality of a Vue component designed solely through a template

I currently have a basic Vue application set up: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'& ...

What is the best way to choose an SVG with a title using Cypress?

In my Cypress script, I am looking to click on an element within a div that has the name "name1", description "description1", and title "title1". Below is the HTML structure: <div data-testid="table-body" role="rowgroup"> < ...