How to initiate a variable from the Grammar in Bison? - c++

let's imagine we have this grammar
start:
expressions;
expressions:
expressions expression
| expression
;
expression:
expression NAME value { float $2 = $3;}
| NAME value { float $1 = $2;}
;
value:
INT '.' INT
;
and for this grammar we apply this input
a 2.0
b 3.0
this should be interpreted by our grammar like this ( float a = 2.0 ; float b = 3.0; )
my aim is really to declare some variable with a name and with a constructor do some thing like myClass NAME(value); and value is a float.
the problems are I don't know how to get the whole value of a grammatical bloc like value in my exemple and how to make a declaration of variable name that will change in each line with in input file and wont have some generic float a = $1;
I already have my flex tokeniser working which will give me NAME and VALUE

You can't use strings in place of variable names in C++. What you should do instead is to define a map from strings to floats and then do something like the_map[$2] = $3; instead of float $2 = $3;.
On an unrelated note, you need to add an action to value that makes it produce a float value (or make your lexer generate a single token for floats and use that). Otherwise $3 doesn't have a proper value when you use it in expression's action.

Related

Matlab regex ${numberFun($4)} - Undefined function 'numberFun' for input arguments of type 'char'

I read that in Matlab it is possible to include a function call inside a regex transformation like this $1double$2[${doubleTextNumber($4)}], assuming 1, 2, 3 to be some regex groups, and 4 to be a purely numeric group. The exact thing I want to do is to catch all arrays consisting of the type creal_T, replace the type with double and double the length of the array.
codeText = "typedef struct {
double tolRob;
creal_T Mt2o[704];
creal_T Ho2o[704];
creal_T Ht2t[704];
creal_T Zo2t[704];
creal_T Ztd[64];
} testType;"
So, I want the struct above to become:
typedef struct {
double tolRob;
double Mt2o[1408];
double Ho2o[1408];
double Ht2t[1408];
double Zo2t[1408];
double Ztd[128];
} SpdEstType;
In Matlab I have made a function to convert a number to text and double it:
function [doubleValue] = doubleTextNumber(inputNumber)
doubleValue = string(str2double(inputNumber)*2.0);
end
I also have a regex that I expect would find the number in each declaration and feed it to the function:
resultString = regexprep(
codeText,
'(?m)^(\W*)creal_T(\s*\w*)(\[([^\]]*\d+)\])',
"$1double$2[${doubleTextNumber($4)}]");
However, as I run this peace of code, Matlab gives me the following error msg:
Error using regexprep
Evaluation of 'doubleTextNumber($4)' failed:
Undefined function 'doubleTextNumber' for input arguments of type 'char'.
As far as I understand, I have made the method do conversion from char, and expect it also to accept this value from my regex. I have tested that it works when I input '704' or "704" directly, and also that the regex works appart from this insertion.
Why does not Matlab find the function from my regex? (they are in the same m file)
It looks like I had 3 issues with my original approach:
In order for regexprep() to recognize my function, it had to be moved to its own m-file. Simply calling a method from inside the same file did not work.
I was using https://regex101.com/ to edit the search expression, but even though it seemed to be selecting the number inside the brackets, group 4 did not get populated by regexprep() in Matlab. A new version did work, and populated group 3 with the numbers I wanted: (?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]
I also added more conversion options to my multiplication method in case the input was a combination of numbers and char arrays.
The final version of my regex call becomes:
resultString = regexprep(
codeText,
'(?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]',
"$1double$2[${multiplyTextNumbers($3,2)}]");
where multiplyTextNumbers() is defined in its own m file as
function [productText] = multiplyTextNumbers(inputFactorText1,inputFactorText2)
%MULTIPLY This method takes numbers as input, and acepts either string,
%char or double or any combination of the three. Returns a string with the
%resulting product.
if (isstring(inputFactorText1) || ischar(inputFactorText1))
inputFactor1 = str2double(inputFactorText1);
else
inputFactor1 = inputFactorText1;
end
if (isstring(inputFactorText2) || ischar(inputFactorText2))
inputFactor2 = str2double(inputFactorText2);
else
inputFactor2 = inputFactorText2;
end
productText = sprintf('%d',inputFactor1*inputFactor2);
end
Hope this can be helpefull to others facing similar issues.

Differences with CFscript calling value methods

I'm working with ColdFusion and CFScript. At the moment I've no problems, but noticed that I can call values in 3 ways:
Value
'Value'
'#Value#'
What are the differences between them? Thanks in advance!
Value
CF searches for a variable called Value (case insensitive) starting with the VARIABLES scope and then progressing through other scopes (like URL and FORM), stopping at the first variable found.
'Value'
A literal string with the characters V, a, l, u and e.
'#Value#'
A string where Value will be evaluated (CF evalautes stuff between #). If the variable Value (case insensitive) is a so called simple value, the variable will be cast to a string. Otherwise, an exception is thrown since non-simple (ie complex ) values are not automatically cast as strings. This is basically equivalent to '' & Value & '' (string concatenation).
Value = 'Hello World !!';
writeOutput(Value);
>> Hello World !!
writeOutput('Value');
>> Value
writeOutput('#Value#');
>> Hello World !!
writeOutput( evaluate('Value') );
>> Hello World !!

Integer in rules for parser definition - Ocaml

I am running into a problem when compiling the following rule for my parser:
%%
expr:
| expr ASN expr { Asn ($1, $2) }
This is an assignment rule that takes an integer, then the assignment (equal sign) and an expression, as defined in my AST:
type expr =
Asn of int * expr
Of course, the compiler is complaining because I am defining "expr ASN expr", and the first argument should be an integer, not an expression. However, I have not been able to figure out the syntax to specify this.
If somebody could lead me in the right direction, I would really appreciate it.
Thanks!
You don't supply enough details to give a good answer. What do you mean by an integer? I'll assume you mean an integer literal.
Assuming your lexical definitions have a token named INT that represents an integer literal, you might want something like this.
expr:
| INT ASN expr { Asn ($1, $2) }
Probably what you want is the assignment as:
type expr = Asn of var * int
and then define expr in the parser as:
expr:
| VAR ASN INT { Asn ($1, $2) }
in the lexer you should have defined VAR as string and INT as integer literal too, just as examples:
| [a-zA-z]+ { VAR($1) }
| [0-9]+ as i { INT(int_of_string i) }

Yacc - productions for matching functions

I am writing a compiler with Yacc and having trouble figuring out how to write productions to match a function. In my language, functions are defined like this:
function foo(a, b, c);
I created lex patterns to match the word function to FUNC, and any C style name to NAME.
Ideally, I would want something like this:
FUNC NAME OBRACKET NAME (COMMA NAME)* CBRACKET
Which would allow some unknown number of pairs of COMMA NAME in between NAME and CBRACKET.
Additionally, how would I know how many it found?
You might try something like this:
funcdecl: FUNC NAME OBRACKET arglist CBRACKET SEMI
;
arglist: nonemptyarglist
|
;
nonemptyarglist: nonemptyarglist COMMA NAME
| NAME
;
I'd suggest using the grammar to build a syntax tree for your language and then doing whatever you need to the syntax tree after parsing has finished. Bison and yacc have features that make this rather simple; look up %union and %type in the info page.
After a little experimentation, I found this to work quite well:
int argCount;
int args[128];
arglist: nonemptyarglist
|
;
nonemptyarglist: nonemptyarglist COMMA singleArgList
| singleArgList
{
};
singleArgList:
REGISTER
{
args[argCount++] = $1;
};

Capitalizing variable name in C program using regular expressions

I need to find a variable in a C program and need to convert its 1st letter to upper case. For example:
int sum;
sum = 50;
I need to find sum and I should convert it to Sum. How can I achieve this using regular expressions (find and replace)?
This can't be done with a regex. You need a C language parser for that, otherwise how would you know what is a variable, what is a keyword, what is a function name, what is a word inside a string or a comment...
.Net's Regex replace support what you want to do (if you can come up with the regular expression you need). The ReplaceCC function at the bottom is invoked to provide the replacement value.
static void Main(string[] args)
{
string sInput, sRegex;
// The string to search.
sInput = #"int sum;
sum = 1;";
// A very simple regular expression.
sRegex = "sum";
Regex r = new Regex(sRegex);
MyClass c = new MyClass();
// Assign the replace method to the MatchEvaluator delegate.
MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceCC);
// Write out the original string.
Console.WriteLine(sInput);
// Replace matched characters using the delegate method.
sInput = r.Replace(sInput, myEvaluator);
// Write out the modified string.
Console.WriteLine(sInput);
}
public string ReplaceCC(Match m)
{
return m.Value[0].ToUpper () + m.Value.Substring (1);
}