foreach loop syntax in tcl with error of foreach: Words not parenthesized - foreach

Error--> foreach: Words not parenthesized
How to fix the error? for below coding:
foreach name ( abc ) {
}

What is giving you the error? A linter program?
Parentheses do not function as a way to group an argument. In Tcl, this is done with curly braces or double quotes.
foreach name { abc } {
}

Related

Peg parser - support for escape characters

I'm working on a Peg parser. Among other structures, it needs to parse a tag directive. A tag can contain any character. If you want the tag to include a curly brace } you can escape it with a backslash. If you need a literal backslash, that should also be escaped. I tried to implement this inspired by the Peg grammer for JSON: https://github.com/pegjs/pegjs/blob/master/examples/json.pegjs
There are two problems:
an escaped backslash results in two backslash characters instead of one. Example input:
{ some characters but escape with a \\ }
the parser breaks on an escaped curly \}. Example input:
{ some characters but escape \} with a \\ }
The relevant grammer is:
Tag
= "{" _ tagContent:$(TagChar+) _ "}" {
return { type: "tag", content: tagContent }
}
TagChar
= [^\}\r\n]
/ Escape
sequence:(
"\\" { return {type: "char", char: "\\"}; }
/ "}" { return {type: "char", char: "\x7d"}; }
)
{ return sequence; }
_ "whitespace"
= [ \t\n\r]*
Escape
= "\\"
You can easily test grammar and test input with the online PegJS sandbox: https://pegjs.org/online
I hope somebody has an idea to resolve this.
These errors are both basically typos.
The first problem is the character class in your regular expression for tag characters. In a character class, \ continues to be an escape character, so [^\}\r\n] matches any character other than } (written with an unnecessary backslash escape), carriage return or newline. \ is such a character, so it's matched by the character class, and Escape is never tried.
Since your pattern for tag characters doesn't succeed in recognising \ as an Escape, the tag { \\ } is parsed as four characters (space, backslash, backslash, space) and the tag { \} } is parsed as terminating on the first }, creating a syntax error.
So you should fix the character class to [^}\\\r\n] (I put the closing brace first in order to make it easier to read the falling timber. The order is irrelevant.)
Once you do that, you'll find that the parser still returns the string with the backslashes intact. That's because of the $ in your Tag pattern: "{" _ tagContent:$(TagChar+) _ "}". According to the documentation, the meaning of the $ operator is: (emphasis added)
$ expression
Try to match the expression. If the match succeeds, return the matched text instead of the match result.
For reference, the correct grammer is as follows:
Tag
= "{" _ tagContent:TagChar+ _ "}" {
return { type: "tag", content: tagContent.map(c => c.char || c).join('') }
}
TagChar
= [^}\\\r\n]
/ Escape
sequence:(
"\\" { return {type: "char", char: "\\"}; }
/ "}" { return {type: "char", char: "\x7d"}; }
)
{ return sequence; }
_ "whitespace"
= [ \t\n\r]*
Escape
= "\\"
When using the following input:
{ some characters but escape \} with a \\ }
it will return:
{
"type": "tag",
"content": "some characters but escape } with a \ "
}

dart function - arrow syntax confliction

1. There is confliction on Dart Language tour
In Functions section, it says
The => expr syntax is a shorthand for { return expr; }.
Note: Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression.
But in the Anonymous functions section, it says
If the function contains only one statement, you can shorten it using arrow notation
Does it mean I can use statement which is not an expression (such as if statement) in anonymous functions?
var fun = () => return 3; // However, this doesn't work.
var gun = () {
return 3; // this works.
}
Or am I confusing concept of expression and statement? I thought
expression : can be evaluated to a value ( 2 + 3 , print('') also falls into an expression )
statement : code that can be executed. all expressions can be statement. if statement and return statement are examples of statement which is not expression.
2. Is this expression or statement
void foo() => true; // this works.
void goo() {
return true; // this doesn't work.
}
void hoo() {
true; // this works.
}
If true is understood as expression, then it will mean return true and I believe it should not work because foo's return type is void.
Then does it mean true in foo is understood as a statement? But this conclusion contradicts with dart language tour. (They are top-level named functions). Also, this means we can use statement with arrow syntax.
I use VSCode and Dart from flutter: 1.22.5. I tell code that works from code that doesn't work based on VSCode error message.
Because this is my first question, I apologize for my short English and ill-formed question.
It must be an expression. The text is misleading.
For the second part, the error you see with
void foo() {
return 0;
}
and not with
void bar() => 0;
is a special case for => in functions returning void. Normally, you can't return a value from a function with return type void, so no return exp;, only return;.
(There are exceptions if exp has type void, null or dynamic, but yours doesn't).
Because people like the short-hand notation of void foo() => anything; so much, you are allowed to do that no matter what the type of anything is. That's why there is a distinction between void foo() { return 0; } and void foo() => 0;. They still mean the same thing, but the type-based error of the former is deliberately suppressed in the latter.
I'm guessing that the author of that section under Anonymous functions was a bit confused. File an issue against it, and get it corrected!
Yeah, even in their example they use a print() function, which they might be confusing as a print "statement", which it clearly is not.

PEG grammar to suppress execution in if command

I want to create a grammar parsing some commands. Most is working flawless but the "if(condition,then-value,else-value)" is not working together with "out" command to show some value.
It works fine in case the output-command is outside the if-command:
out(if(1,42,43))
→ output and return 42 as expected OK
But at the moment the output-command is inside then- and else-part (which is required to be more intuitive) it fails:
if(1,out(42),out(43))
→ still return only 42 as expected OK, but the output function is called twice with 42 and 43
I'm working under C with the peg/leg parser generator here
The problem is also reproducible with PEG.js online parser generator here when using the following very much simplified grammar:
Expression
= Int
/ "if(" cond:Expression "," ok:Expression "," nok:Expression ")" { return cond?ok:nok; }
/ "out(" num:Expression ")" { window.alert(num); return num;}
Int = [0-9]+ { return parseInt(text(), 10); }
The "window.alert()" is only a placeholder for the needed output function, but for this problem it acts the same.
It looks like the scanner have to match the full if-command with then-
and else-value until the closing bracket ")". So it matches both out-commands and they both execute the defined function - which is not what I expect.
Is there a way in peg/leg to match some characters but suppress execution of the according function under some circumstances?
(I've already experimented with "&" predicate element without success)
(Maybe left-recursion vs. right-recursion could help here, but used peg/leg-generator seems to only supports right-recursion)
Is there a way in peg/leg to match some characters but suppress execution of the according function under some circumstances?
I'm not familiar with the tools in question, but it would surprise me if this were possible. And even if it were, you'd run into a similar problem when implementing loops: now you'd need to execute the action multiple times.
What you need is for your actions to not directly execute the code, but return something that can be used to execute it.
The usual way that interpreters work is that the parser produces some sort of representation of the source code (such as bytecode or an AST), which is then executed as a separate step.
The simplest (but perhaps not cleanest) way to make your parser work without changing too much would be to just wrap all your actions in 0-argument functions. You could then call the functions returned by the sub-expressions if and only if you want them to be executed. And to implement loops, you could then simply call the functions multiple times.
An solution could be using a predicate expression "& {expression}" (not to be confused by predicate element "& element")
Expression
  = Function
  
Function
  = Int
  / "if(" IfCond "," ok:Function "," nok:FunctionDisabled ")" { return ok; }
  / "if(" FunctionDisabled "," ok:FunctionDisabled "," nok:Function ")" { return nok; }
  / "out(" num:Function ")" { window.alert("Out:"+num); return num;}
 
FunctionDisabled
  = Int
/ "if(" IfCond "," ok:FunctionDisabled "," nok:FunctionDisabled ")" { return ok; }
  / "if(" FunctionDisabled "," ok:FunctionDisabled "," nok:FunctionDisabled ")" { return nok; }
/ "out(" num:FunctionDisabled ")" { return num;}
IfCond
  = cond:FunctionDisabled   &{ return cond; }
                   
Int = [0-9]+ { return parseInt(text(), 10); }
The idea is to define the out() twice, once really doing something and a second time disabled without output.
The condition of the if-command is evaluated using the code inside {}, so if the condition is false, the whole expression match failes.
Visible drawback is the redundant definition of the if-command for then and else and recursive disabled

Dart lambda/shortland function confusion

I'm still pretty new to Dart and the syntax of => (fat arrow) still confuses me (I come from C# background).
So in C# fat arrow ( => ) says: goes to so for example:
Action<string> action1 = (str) => { System.Diagnostic.Debug.WriteLine("Parameter received: " + str.ToString()); }
action1("Some parameter");
means: whatever send as parameter to action1 (if it could be casted to string) goes to inner scope (in our case it just printed in Debug.WriteLine()
but in Dart it's something different.... (?)
for example in Future.then
ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then(
(str) => { print("Class was loaded with info: $str"),
onError: (exp) => { print("Error occurred in class loading. Error is: $exp"); }
);
Dart editor warn me that the first and second print is: Expected string literal for map entry key. I think in C# way that str it just name for parameter that will be filled by internal callback that Future.then uses to call onValue or onError
What I'm doing wrong ?
You need to choose either block syntax or single expression syntax, but not both.
You can't combine => with {}.
Your two options are as follows using your example:
ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then(
(str) => print("Class was loaded with info: $str"),
onErrro: (exp) => print("Error occurred in class loading. Error is: $exp")
);
or
ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then(
(str) { print("Class was loaded with info: $str"); },
onErrro: (exp) { print("Error occurred in class loading. Error is: $exp"); }
);
In both cases, it is just a way to express an anonymous function.
Normally if you want to just run a single expression, you use the => syntax for cleaner and more to the point code. Example:
someFunction.then( (String str) => print(str) );
or you can use a block syntax with curly braces to do more work, or a single expression.
someFunction.then( (String str) {
str = str + "Hello World";
print(str);
});
but you can't combine them since then you are making 2 function creation syntaxes and it breaks.
In Dart => xxx is just a syntaxic sugar to avoid { return xxx; }. Thus the two following functions are equivalent :
var a = (String s) => s;
var b = (String s) { return s; } ;
You can also use => on method definitions :
String myFunc(String s) => s;
String myFunc(String s) {
return s;
}
That syntax works well in a language like javascript and also c# where it supports (param1, param2, …, paramN) => { statements } with statement being separated with semi colon. In dart, the fat arrow only supports expression which is shorthand for { return expr; }.
That explains your Error. Your code with the curly brace (exp) => { print("Error occurred in class loading. Error is: $exp"); } means you are returning a map, so it expects to see something like (param) => {"key": "value"} where key is a string literal.

Flex use constants Container

i have to program a compiler with flex.
But i don't like the given code and want to make my self.
lexfile.l:
{%
typedef enum { EQ=0, NE, PLUS, MINUS, SEMICOLON } punctuationType;
typedef enum { PRINT=100, WHILE, IDENT } keywordType;
%}
%%
"!=" { return NEQ; }
"=" { return EQ; }
"+" { return PLUS; }
"-" { return MINUS; }
";" { return SEMICOLON; }
%%
Is there a better solution?
I have searched for a solution but the other solution is to define the Constants.
#define EQ 0
#define NE 1
...
Output Example:
Operator EQ
Operator NE
The Question is only, if there is a better type instead the Enum
Whatever you return has to be understood by the compiler. If you're using yacc, you don't get the choice: you have to abide by whatever %token generates, which are defined for you in y.tab.h.: you don't have to do anything at all.
On the other hand there's no need to have either names or flex rules for the single-char special characters: you can just return yytext[0] for all of them and use the corresponding literals in the .y file.
You don't really give enough details for further comment.

Resources