Why does this no syntax error nested class program produce garbage output, and how do I fix it? - g++

The following code includes a complete description of the problem as a TODO.
Included are cut/pasteable command lines to compile the code (without error).
Child instances contain their own name, and the initializer should copy it.
Child instances also contain a pointer to their Parent this instance.
Neither of these should print garbage.
Child also uses its Parent instance pointer to print the parent name.
This name is initialized by the Parent ctor, and so should not print as garbage.
I even ran it through clang with -fsyntax-only, without reported warning/error.
I must be missing something. Help would be appreciated.
////////////////////////////////////////////////////////////////////////////////
//
// ##### ## ##### ###### # # ##### #### ##### #####
// # # # # # # # ## # # # # # # # #
// # # # # # # ##### # # # # # # # # #
// ##### ###### ##### # # # # # ### # ##### #####
// # # # # # # # ## # ### # # # #
// # # # # # ###### # # # ### #### # #
////////////////////////////////////////////////////////////////////////////////
// A class having access to all nested class instances and vice versa
// 0. presence by name in a set
// 1. by name in a map
// 2. by index in a vector
// 3. by name to index in a map
// and nested classes have access to parent and to each other through parent.
////////////////////////////////////////////////////////////////////////////////
// TODO produce the following instead of garbage output.
// Compile and expected output:
// $ g++ --std=c++17 -Wall -pedantic -o parent parent.cpp
// $ ./parent
// P:A
// P:B
// $
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
using namespace std;
// Utility function for when things go wrong.
template<class... Args> void panic(Args... args) {
cerr << "parent panic: ";
(cerr << ... << args) << "\n";
exit(1);
}
class Parent { public: //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
class Child { public: //cccccccccccccccccccccccccccccccccccccccccccccccccccc
Child(Parent* p, const string& n) : parent(p), name(n) {} // Child ctor
~Child() {} // Child dtor
void operator()(){ cout<<parent->name<<':'<<name<<endl; } // Child ftor
Parent* parent; // Child Parent ptr
const string& name; // Child name
}; //ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
Parent(const string& name) : name(name) {} // Parent ctor
~Parent() {} // Parent dtor
void operator()() { for(auto child: vcci) { child(); } } // Parent ftor
void operator+=(const vector<string>& names) {
for(auto name : names) {
if (used.find(name) != used.end()) panic(name, " re-used,");
used.insert(name); // Fast search
size_t vcN = vcci.size(); // Index for next name
vcci.emplace_back(this, name); // construct child into vector
Child* back = &(vcci[vcN]); // Address of child to store
mptr[name] = back; // Store address of child
mint[name] = vcN; // map name to index
}
}
string name; // name of parent
set<string> used; // fast lookup of name for duplicates
vector<Child> vcci; // vector of emplaced Child instances
map<string, Child*> mptr; // name lookup of Child pointer
map<string, size_t> mint; // index of name
}; //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
//eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
void experiment() {
vector<string> AB = { "A", "B" }; // Names to use as Child names
Parent parent("P"); // Named parent
parent += AB; // Produce named Child instances
parent(); // Execute parent ftor
}
//mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
int main(int argc, char** argv) {
experiment();
return 0;
}

With for(auto name : names) ..., name is a local variable that's a copy of the string from the vector. That variable is created and destroyed on each iteration of the loop. Then you create Child instances with name as an argument - they store a reference to that variable in their name member. Soon afterwards, the variable is destroyed and all those references become dangling.
By the time the program actually tries to use Child::name members, the strings are long gone, and the references are long dangling. Any attempt to use them exhibits undefined behavior, by way of accessing an object after its lifetime has ended.

const string& name; // Child name
This was the offending line.
It had to be a string, not a string reference.
Simple programmer error.
Thanks for reviewing and pointing me in a good direction.

Related

confusion about lists contained in an aggregate, maybe context problem?

Rakudo version 2020.01
I was writing some throw-away code and did not bother to implement a class, just used a Hash as work-alike. I found some surprising behaviour with lists.
class Q1 {}
class R1 {
has Str $.some-str is required;
has #.some-list is required;
}
my $r1 = R1.new(
some-str => '…',
some-list => (Q1.new, Q1.new, Q1.new)
);
# hash as poor man's class
my $r2 = {
some-str => '…',
some-list => (Q1.new, Q1.new, Q1.new)
};
multi sub frob(R1 $r1) {
for #`(Array) $r1.some-list -> $elem {
$elem.raku.say;
}
}
multi sub frob(Hash $r2) {
for #`(List) $r2<some-list> -> $elem {
$elem.raku.say;
}
}
frob $r1;
# OK.
# Q1.new
# Q1.new
# Q1.new
frob $r2;
# got:
# (Q1.new, Q1.new, Q1.new)
# expected:
# Q1.new
# Q1.new
# Q1.new
frob(Hash …) works as expected when I call .flat or .list on the list (even though it is already a list‽).
I tried to make a minimal test case, but this works identical AFAICT.
for [Q1.new, Q1.new, Q1.new] -> $elem {
$elem.raku.say;
}
for (Q1.new, Q1.new, Q1.new) -> $elem {
$elem.raku.say;
}
I have read the documentation on List and Scalar several times, but I still cannot make sense out of my observation. Why do I have to special treat the list in the Hash, but not in the class?
for doesn't loop over itemized values.
When you place something in a scalar container it gets itemized.
sub foo ( $v ) { # itemized
for $v { .say }
}
sub bar ( \v ) {
for v { .say }
}
foo (1,2,3);
# (1 2 3)
bar (1,2,3);
# 1
# 2
# 3
An element in a Hash is also a scalar container.
my %h = 'foo' => 'bar';
say %h<foo>.VAR.^name;
# Scalar
So if you place a list into a Hash, it will get itemized.
my %h;
my \list = (1,2,3);
%h<list> = list;
say list.VAR.^name;
# List
say %h<list>.VAR.^name;
# Scalar
So if you want to loop over the values you have to de-itemize it.
%h<list>[]
%h<list><>
%h<list>.list
%h<list>.self
#(%h<list>)
given %h<list> -> #list { … }
my #list := %h<list>;
(my # := %h<list>) # inline version of previous example
You could avoid this scalar container by binding instead.
%h<list> := list;
(This prevents the = operator from working on that hash element.)
If you noticed that in the class object you defined it with an # not $
class R1 {
has Str $.some-str is required;
has #.some-list is required;
}
If you changed it to an $ and mark it rw it will work like the Hash example
class R2 {
has Str $.some-str is required;
has List $.some-list is required is rw;
}
my $r2 = R2.new(
some-str => '…',
some-list => (1,2,3),
);
for $r2.some-list { .say }
# (1 2 3)
It has to be a $ variable or it won't be in a Scalar container.
It also has to be marked rw so that the accessor returns the actual Scalar container rather than the de-itemized value.
This has nothing to do with [] versus (). This has to do with the difference between $ (indicating an item) and % (indicating an Associative):
sub a(%h) { dd %h } # a sub taking an Associative
sub b(Hash $h) { dd $h } # a sub taking an item of type Hash
a { a => 42 }; # Hash % = {:a(42)}
b { a => 42 }; # ${:a(42)}
In the "b" case, what is received is an item. If you try to iterate over that, you will get 1 iteration, for that item. Whereas in the "a" case, you've indicated that it is something Associative that you want (with the % sigil).
Perhaps a clearer example:
my $a = (1,2,3);
for $a { dd $_ } # List $a = $(1, 2, 3)␤
Since $a is an item, you get one iteration. You can indicate that you want to iterate on the underlying thing, by adding .list:
for $a.list { dd $_ } # 1␤2␤3␤
Or, if you want to get more linenoisy, prefix a #:
for #$a { dd $_ } # 1␤2␤3␤
Not strictly an answer, but an observation: in Raku, it pays to use classes rather than hashes, contrary to Perl:
my %h = a => 42, b => 666;
for ^10000000 { my $a = %h<a> }
say now - INIT now; # 0.4434793
Using classes and objects:
class A { has $.a; has $.b }
my $h = A.new(a => 42, b => 666);
for ^10000000 { my $a = $h.a }
say now - INIT now; # 0.368659
Not only is using classes faster, it also prevents you from making typos in initialization if you add the is required trait:
class A { has $.a is required; has $.b is required }
A.new(a => 42, B => 666);
# The attribute '$!b' is required, but you did not provide a value for it.
And it prevents you from making typos when accessing it:
my $a = A.new(a => 42, b => 666);
$a.bb;
# No such method 'bb' for invocant of type 'A'. Did you mean 'b'?

Antlr 4: Is getting this form of output possible?

Within the context of scanning, what do i need to override, extend, listen to, visit to be able to print out this form of informative output when my text is being scanned?
-- Example output only ---------
DEBUG ... current mode: DEFAULT_MODE
DEBUG ... matching text '#' on rule SHARP ; pushing and switching to DIRECTIVE_MODE
DEBUG ... matching text 'IF" on rule IF ; pushing and switching to IF_MODE
DEBUG ... matching text ' ' on rule WS; skipping
DEBUG ... no match for text %
DEBUG ... no match for text &
DEBUG ... mathcing text '\r\n' on rule EOL; popping mode; current mode: DIRECTIVE_MODE
...
thanks
The solution was a lot simpler than I thought.
You just need to subclass the generated Lexer and override methods such as popMode(), pushMode() to get the printout you want. If you do this you should also override emit() methods as well to get properly sequential and contextual information.
Here's an example in C#:
class ExtendedLexer : MyGeneratedLexer
{
public ExtendedLexer(ICharStream input)
: base(input) { }
public override int PopMode()
{
Console.WriteLine($"Mode is being popped: Line: {Line} Column:{Column} ModeName: {ModeNames[ModeStack.Peek()]}");
return base.PopMode();
}
public override void PushMode(int m)
{
Console.WriteLine($"Mode is being pushed: Line: {Line} Column:{Column} ModeName: {ModeNames[m]}");
base.PushMode(m);
}
public override void Emit(IToken t)
{
Console.WriteLine($"[#{t.TokenIndex},{t.StartIndex}:{t.StopIndex}, <{Vocabulary.GetSymbolicName(t.Type)}> = '{t.Text}']");
base.Emit(t);
}
}
And the output would be something like:
Mode is being pushed: Line: 4 Column:3 ModeName: IF_MODE
[#-1,163:165, <IF> = '#IF']
Mode is being pushed: Line: 4 Column:4 ModeName: CONDITION_MODE
[#-1,166:166, <LPAREN> = '(']
[#-1,167:189, <EXP> = '#setStartDateAndEndDate']
Mode is being popped: Line: 4 Column:28 ModeName: IF_MODE
[#-1,190:190, <RPAREN> = ')']

What is the purpose of # in antlr grammar

I have a statement in an ANTLR4 grammar like:
expression : DEFAULT #primitive_expression
;
I don't know what is the meaning of # here.
They're alternative labels:
Alternative Labels
As we saw in Section 7.4, Labeling Rule Alternatives for Precise Event Methods, we can get more precise parse-tree listener events by labeling the outermost alternatives of a rule using the # operator. All alternatives within a rule must be labeled, or none of them. Here are two rules with labeled alternatives.
grammar T;
stat: 'return' e ';' # Return
| 'break' ';' # Break
;
e : e '*' e # Mult
| e '+' e # Add
| INT # Int
;
Alternative labels do not have to be at the end of the line and there does not have to be a space after the # symbol. ANTLR generates a rule context class definition for each label. For example, here is the listener that ANTLR generates:
public interface AListener extends ParseTreeListener {
void enterReturn(AParser.ReturnContext ctx);
void exitReturn(AParser.ReturnContext ctx);
void enterBreak(AParser.BreakContext ctx);
void exitBreak(AParser.BreakContext ctx);
void enterMult(AParser.MultContext ctx);
void exitMult(AParser.MultContext ctx);
void enterAdd(AParser.AddContext ctx);
void exitAdd(AParser.AddContext ctx);
void enterInt(AParser.IntContext ctx);
void exitInt(AParser.IntContext ctx);
}
From: https://github.com/antlr/antlr4/blob/master/doc/parser-rules.md#alternative-labels

Singleton implementation on perl6

I looked at the following code on Rosetta code http://rosettacode.org/wiki/Singleton#Perl_6
which implements Singleton in Perl6
class Singleton {
has Int $.x is rw;
# We create a lexical variable in the class block that holds our single instance.
my Singleton $instance = Singleton.bless; # You can add initialization arguments here.
method new {!!!} # Singleton.new dies.
method instance { $instance; }
}
my $a=Singleton.bless(x => 1);
my $b=Singleton.bless(x=> 2);
say $a.x;
say $b.x;
#result
# 1
# 2
but it seems using this implementation i can create tow instances of the same class using bless see example above ,
is there an option to prevent the implemention to only one instance of the same class ?
Perl prides itself on providing many ways to do things leaving you to pick the one that suits your tastes and the application at hand. I say that to highlight that this is one simple but solid, hopefully self-explanatory way - I'm not putting it forward as "the best" because that depends on your circumstances.
#!/usr/bin/env perl6
class Scoreboard {
has Str $.home-team ;
has Str $.away-team ;
has Int $.home-score = 0 ;
has Int $.away-score = 0 ;
my Scoreboard $instance;
method new(*%named) {
return $instance //= self.bless(|%named) ;
}
multi method goal($team where * eq $!home-team, Int :$points = 6) {
$!home-score += $points
}
multi method goal($team where * eq $!away-team, Int :$points = 6) {
$!away-score += $points
}
method Str {
"At this vital stage of the game " ~
do given $!home-score <=> $!away-score {
when More {
"$!home-team are leading $!away-team, $!home-score points to $!away-score"
}
when Less {
"$!home-team are behind $!away-team, $!home-score points to $!away-score"
}
default {
"the scores are level! $!home-score apeice!"
}
}
}
}
my $home-team = "The Rabid Rabbits";
my $away-team = "The Turquoise Turtles"; # Go them turtles!
my $scoreboard = Scoreboard.new( :$home-team , :$away-team );
$scoreboard.goal($home-team, :4points) ;
say "$scoreboard";
$scoreboard.goal($away-team) ;
say "$scoreboard";
my $evil_second_scoreboard = Scoreboard.new;
$evil_second_scoreboard.goal($home-team, :2points) ;
say "$evil_second_scoreboard";
This produces;
At this vital stage of the game The Rabid Rabbits are leading The Turquoise Turtles, 4 points to 0
At this vital stage of the game The Rabid Rabbits are behind The Turquoise Turtles, 4 points to 6
At this vital stage of the game the scores are level! 6 apeice!
This overrides the default new (normally supplied by class Mu) and keep a reference to ourself (ie this object) in private class data. For private class data, we use a lexically scoped scalar declared with my. The // is the operator form of .defined. So, on the first run, we call bless which allocates the object and initialize the attributes, and then assign it to $instance. In subsequent calls to new, $instance is defined and is immediately returned.
If you want to prevent someone calling bless directly, you can add;
method bless(|) {
nextsame unless $instance;
fail "bless called on singleton Scoreboard"
}
which will ensure that only the first call will work.

gnokii: API error?

I have issues with the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gnokii.h>
#define CONFIG_FILE "config"
struct gn_statemachine *state;
void terminate(void) {
gn_lib_phone_close(state);
gn_lib_phoneprofile_free(&state);
gn_lib_library_free();
}
int main() {
gn_data data;
gn_error error;
gn_sms_folder_list folderlist;
atexit(terminate);
if((error = gn_lib_phoneprofile_load(CONFIG_FILE,&state))
!= GN_ERR_NONE)
{
fprintf(stderr,"%s\n",gn_error_print(error));
exit(1);
}
memset(&folderlist,0,sizeof(gn_sms_folder_list));
gn_data_clear(&data);
data.sms_folder_list = &folderlist;
error = gn_sm_functions(GN_OP_GetSMSFolders, &data, state);
printf("ada %d sms dun\n",folderlist.number);
return 0;
}
I'm compiling it with gcc -o main main.c -lgnokii, but when it's executed it generates errors when looking for config file:
# ./gnokiitest
No phone_config section in the config file.
Either global or given phone section cannot be found.
Segmentation fault
because I included the config file within one folder of main output:
$ cat config
[global]
connection = bluetooth
port = 24:22:AB:AB:C1:F8
model = AT
rfcomm_channel = 2
Whats wrong then?
For starters, the following will cause issues:
if((error = gn_lib_phoneprofile_load(CONFIG_FILE,&state))
state variable is not initialized here. That will cause random pointer being passed and most likely segfault.
Next, the first argument to gn_lib_phoneprofile_load() is not the config file name, but the phone section in the config where the connection details are provided. Given that you pass config as this parameter you'd need:
[phone_config]
connection = bluetooth
port = 24:22:AB:AB:C1:F8
model = AT
rfcomm_channel = 2
but placed in the standard gnokii config file location. To use different location use:
gn_lib_phoneprofile_load_from_file(CONFIG_FILE, NULL, &state);
Second argument is the phone section name. If NULL, then [global] would be used.
Additionally gn_lib_phoneprofile_load() just reads the config file. You need to run gn_lib_phone_open() to initialize the connection.
Finally, there is similar code already written, no need to reinvent the wheel: http://git.savannah.gnu.org/cgit/gnokii/gnokii-extras.git/tree/snippets/sms/sms_status.c