Returning list in ANTLR for type checking, language java - list

I am working on ANLTR to support type checking. I am in trouble at some point. I will try to explain it with an example grammar, suppose that I have the following:
#members {
private java.util.HashMap<String, String> mapping = new java.util.HashMap<String, String>();
}
var_dec
: type_specifiers d=dec_list? SEMICOLON
{
mapping.put($d.ids.get(0).toString(), $type_specifiers.type_name);
System.out.println("identext = " + $d.ids.get(0).toString() + " - " + $type_specifiers.type_name);
};
type_specifiers returns [String type_name]
: 'int' { $type_name = "int";}
| 'float' {$type_name = "float"; }
;
dec_list returns [List ids]
: ( a += ID brackets*) (COMMA ( a += ID brackets* ) )*
{$ids = $a;}
;
brackets : LBRACKET (ICONST | ID) RBRACKET;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*;
LBRACKET : '[';
RBRACKET : ']';
In rule dec_list, you will see that I am returning List with ids. However, in var_dec when I try to put the first element of the list (I am using only get(0) just to see the return value from dec_list rule, I can iterate it later, that's not my point) into mapping I get a whole string like
[#4,6:6='a',<17>,1:6]
for an input
int a, b;
What I am trying to do is to get text of each ID, in this case a and b in the list of index 0 and 1, respectively.
Does anyone have any idea?

The += operator creates a List of Tokens, not just the text these Tokens match. You'll need to initialize the List in the #init{...} block of the rule and add the inner-text of the tokens yourself.
Also, you don't need to do this:
type_specifiers returns [String type_name]
: 'int' { $type_name = "int";}
| ...
;
simply access type_specifiers's text attribute from the rule you use it in and remove the returns statement, like this:
var_dec
: t=type_specifiers ... {System.out.println($t.text);}
;
type_specifiers
: 'int'
| ...
;
Try something like this:
grammar T;
var_dec
: type dec_list? ';'
{
System.out.println("type = " + $type.text);
System.out.println("ids = " + $dec_list.ids);
}
;
type
: Int
| Float
;
dec_list returns [List ids]
#init{$ids = new ArrayList();}
: a=ID {$ids.add($a.text);} (',' b=ID {$ids.add($b.text);})*
;
Int : 'int';
Float : 'float';
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*;
Space : ' ' {skip();};
which will print the following to the console:
type = int
ids = [a, b, foo]
If you run the following class:
import org.antlr.runtime.*;
public class Main {
public static void main(String[] args) throws Exception {
TLexer lexer = new TLexer(new ANTLRStringStream("int a, b, foo;"));
TParser parser = new TParser(new CommonTokenStream(lexer));
parser.var_dec();
}
}

Related

Is there type casting in VDM++?

For example, I want to cast nat to seq of char in VDM++.
In the code below, I want operation setValueOfX to return "X is {value of q}", if q is of type nat and q < 3.
class A1
instance variables
private x : nat := 0;
operations
public setValueOfX : nat ==> seq of char
setValueOfX(q) ==
(
if is_nat(q) and q < 3
then
(
x := q;
-- The following line doesn't work
-- return "X is " ^ q;
)
else
return "Invalid value! Value of x must be more than 0 and less than 3.";
);
end A1
I've tried using ^ but I got the following error:
Error[207] : Rhs of '^' is not a sequence type
act : nat
exp : ( seq1 of # | [] )
No, you can't implicitly convert values like that in VDM.
If you just want to see the result in a textural form, you could look at the IO library, which lets you "print" a mixture of types to the console. Alternatively, if you must return a string, you could specify a function that converts a nat to a decimal string, and the return "Result is" ^ nat2str(q).

How should I initialize my list of tuples

I have a function that takes a list of tuples and process it to obtain a tuple of 3 integers.
I would now like to test it with a list of the tuples type I created but I'm unable to create this list.
Here is my tuple type :
type t_votes = {valeur : string ; nombre : int };;
Here is my function :
let rec recap (l : t_votes list) : int * int * int =
let (nb_oui,nb_non,nb_blanc) = recap(tl(l)) in
if (l=[]) then
(0,0,0)
else if ((hd(l)).valeur = "oui") then
(nb_oui+(hd(l)).nombre ,nb_non,nb_blanc)
else if ((hd(l)).valeur = "non") then
(nb_oui, nb_non + (hd(l)).nombre, nb_blanc)
else if ((hd(l)).valeur = "blanc") then
(nb_oui,nb_non,nb_blanc+(hd(l)).nombre)
else
failwith("liste invalide")
;;
And here is my vain attempt at declaring a list to test my function with :
let liste_votes : t_votes list = [("oui",120);("non",18);("blanc",20);("oui",20);("non",24);("blanc",25)];;
recap(liste_votes );;
Here is what tuareg gives me :
# let liste_votes : t_votes list = [("oui",120);("non",18);("blanc",20);("oui",20);("non",24);("blanc",25)];;
Characters 34-45:
let liste_votes : t_votes list = [("oui",120);("non",18);("blanc",20);("oui",20);("non",24);("blanc",25)];;
^^^^^^^^^^^
Error: This expression has type 'a * 'b
but an expression was expected of type t_votes
To create a value of a record type (because it is a record type and not a tuple, a tuple doesn't name its arguments), the syntax is the following:
{ valeur = "Some string" ; nombre = 13 }
If this syntax is too heavy for you, a common practice is to write a builder function:
let mk_vote valeur nombre = { valeur ; nombre }
Here I'm using another piece of syntax to instantiate a record value without using the = symbol. In that case, it's the same as writing valeur = valeur and nombre = nombre.
You can then write:
let votes = [ mk_vote "oui" 120 ; mk_vote "non" 18 ; mk_vote "blanc" 20 ; mk_vote "oui" 20 ; mk_vote "non" 24 ; mk_vote "blanc" 25 ]
let mk_vote (valeur, nombre) = { valeur ; nombre }
would work as well and let you write
let votes = List.map mk_vote [("oui",120);("non",18);("blanc",20);("oui",20);("non",24);("blanc",25)]
For some vote of the record type you can access the fields with vote.valeur and vote.nombre.
You can also use pattern-matching:
match vote with
| { valeur = v ; nombre = n } => (* ... *)
You can also make a record value from another one like so:
let vote = { valeur = "Some string" ; nombre = 13 } in
let vote' = { vote with valeur = "Some other string" } in
(* ... *)
Then vote'.valeur is "Some other string" while vote'.nombre is vote.nombre,
or 13 in that case.
Finally I couldn't help but notice you were using strings to represent different kind of votes, since there seem to be only three cases, a dedicated type would be more relevant (you are using ocaml after all which lets you handle data properly).
type vote_kind =
| Yes
| No
| Blank
type t_votes = {
value : vote_kind ;
amount : int ;
}

CVC4: using quantifiers in C++ interface

I am trying to figure out how to code quantifiers in CVC4, using the C++ interface. Here is an example I am trying to get to run, but cannot.
int main() {
SmtEngine smt(&em);
smt.setLogic("AUFLIRA"); // Set the logic
Expr three = em.mkConst(Rational(3));
Expr four = em.mkConst(Rational(4));
// make the list of bound variables in CVC4
Expr bound_var = em.mkBoundVar("x_bound", em.integerType());
vector<Expr> bound_vars;
bound_vars.push_back(bound_var);
Expr bound_var_list = em.mkExpr(kind::BOUND_VAR_LIST, bound_vars);
Expr declare = em.mkExpr(kind::EQUAL, bound_var, three); //x_bound =3
Expr check = em.mkExpr(kind::EQUAL, bound_var, four); //x_bound=4
//forall x_bound, x_bound=3, the constraint I want to declare as true
Expr expr = em.mkExpr(kind::FORALL, bound_var_list, declare);
smt.assertFormula(expr);
smt.push();
// expect to be INVALID
// I want to check that given forall x_bound, x_bound = 3
// then I ask CVC4: is it true that x_bound=4, or is it false?
std::cout << "Quantifier " << smt.query(check) << std::endl;
return 0;
}
Instead, I just get an error message:
Bound variables test
Quantifier unknown (INCOMPLETE)
But I define the quantifier as forall. What did I do wrong?
EDIT (asked https://www.andrew.cmu.edu/user/liminjia/):
Syntax is wrong. We want to know if
(forall x, x=3) IMPLIES (forall x, x=4)
is true or not. But CVC4 does not if the above formula is valid or not, because SMT solvers are not full-fledged first-order logic theorem provers.
If you want to try something that works, try in CVC4 language:
QUERY (FORALL (x:INT): x =4);
And in C++, we have
// check that forall x, x=3 is INVALID
void cvc4BoundVar() {
std::cout << "Bound variables test" << std::endl;
SmtEngine smt(&em);
smt.setLogic("AUFLIRA"); // Set the logic
Expr three = em.mkConst(Rational(3));
Expr v_expr = em.mkBoundVar("x_bound", em.integerType());
vector<Expr> bound_vars;
bound_vars.push_back(v_expr);
Expr bound_var_list = em.mkExpr(kind::BOUND_VAR_LIST, bound_vars);
Expr declare = em.mkExpr(kind::EQUAL, v_expr, three); //x=3
Expr check = em.mkExpr(kind::EQUAL, v_expr, three);
Expr expr = em.mkExpr(kind::FORALL, bound_var_list, declare); //forall x, x=3
std::cout << "Quantifier " << smt.query(expr) << std::endl;
}

What are "`" in OCaml?

type t = {
dir : [ `Buy | `Sell ];
quantity : int;
price : float;
mutable cancelled : bool;
}
There is a ` before Buy and Sell, what does that mean?
Also what are the type [ | ]?
The ` and [] syntax are to define polymorphic variants. They are similar in spirit to an inline variant definition.
http://caml.inria.fr/pub/docs/manual-ocaml-4.00/manual006.html#toc36
In your case, dir can take the value `Buy or `Sell, and pattern matching works accordingly:
let x = { dir = `Buy, quantity = 5, price = 1.0, cancelled = true }
match x.dir with
| `Buy -> 1
| `Sell -> 2

How much memory consumed by my object

I want to know programmatic way to get the memory consumed by my user defined class.
Following is the declaration of the class
struct TrieNode {
typedef std::map<char, TrieNode *> ChildType;
std::string m_word;
bool m_visited;
}
I have inserted around 264061 words into this Trie. After this when i do sizeof(trieobject) it just show me 32. How do i know how much exact memory is used by such data structures.
I use
valgrind --tool=massif ./myprogram -opt arg1 arg2
ms_print massif.* | less -SR
for that. Sample output from this page
19.63^ ###
| #
| # ::
| # : :::
| :::::::::# : : ::
| : # : : : ::
| : # : : : : :::
| : # : : : : : ::
| ::::::::::: # : : : : : : :::
| : : # : : : : : : : ::
| ::::: : # : : : : : : : : ::
| ###: : : # : : : : : : : : : #
| ::# : : : # : : : : : : : : : #
| :::: # : : : # : : : : : : : : : #
| ::: : # : : : # : : : : : : : : : #
| ::: : : # : : : # : : : : : : : : : #
| :::: : : : # : : : # : : : : : : : : : #
| ::: : : : : # : : : # : : : : : : : : : #
| :::: : : : : : # : : : # : : : : : : : : : #
| ::: : : : : : : # : : : # : : : : : : : : : #
0 +----------------------------------------------------------------------->KB 0 29.48
Number of snapshots: 25
Detailed snapshots: [9, 14 (peak), 24]
The remainder of the log details the highest percentiles of memory allocations, you can specifically see what type of class takes what % of heap memory (and where the allocations originate in terms of call stack), e.g.:
--------------------------------------------------------------------------------
n time(B) total(B) useful-heap(B) extra-heap(B) stacks(B)
--------------------------------------------------------------------------------
10 10,080 10,080 10,000 80 0
11 12,088 12,088 12,000 88 0
12 16,096 16,096 16,000 96 0
13 20,104 20,104 20,000 104 0
14 20,104 20,104 20,000 104 0
99.48% (20,000B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
->49.74% (10,000B) 0x804841A: main (example.c:20)
|
->39.79% (8,000B) 0x80483C2: g (example.c:5)
| ->19.90% (4,000B) 0x80483E2: f (example.c:11)
| | ->19.90% (4,000B) 0x8048431: main (example.c:23)
| |
| ->19.90% (4,000B) 0x8048436: main (example.c:25)
|
->09.95% (2,000B) 0x80483DA: f (example.c:10)
->09.95% (2,000B) 0x8048431: main (example.c:23)
Well, this is not so easy to do. First of all m_word is a string with variable size right? Internally the std::string holds an array of chars among other things. The same stands for std::map. I guess you could get a rough estimation based on the size of the map * TrieNode but this will be just a rough estimate.
I think some code profiling with an external tool would be of more help. Hell you can even use the task manager if you are out of any tools left :).
Your "object size" is sizeof(std::string) + sizeof(bool) + m_word.capacity() + padding bytes or sizeof(trieobject) + m_word.capacity()
Here's a piece of code for GCC that I came up with that you can use in a test program where you only instantiate one object of your class and do some typical work with it. The code replaces the global operator new() and operator delete(); so it will only track allocations through ::new expressions and the standard allocator, provided that the standard allocator itself uses ::operator new() (this is the case for GCC).
Since we need to track the pointers and their allocations, we need a separate map for that, which of course cannot use the standard allocator itself; GCC's malloc-allocator comes to the rescue.
We use a statically initialized global to make the memory tracker print its data after main returns.
#include <unordered_map>
#include <string>
#include <iostream>
#include <ext/malloc_allocator.h>
struct Memtrack
{
typedef std::unordered_map<void*, std::size_t, std::hash<void*>,
std::equal_to<void*>, __gnu_cxx::malloc_allocator<void*>> AllocMap;
static int memtrack;
static int memmax;
static AllocMap allocs;
Memtrack() { std::cout << "starting tracker: cur = " << memtrack << ", max = " << memmax << ".\n"; }
~Memtrack() { std::cout << "ending tracker: cur = " << memtrack << ", max = " << memmax << ".\n"; }
static void track_new(std::size_t n, void * p)
{
memtrack += n;
if (memmax < memtrack) memmax = memtrack;
allocs[p] = n;
std::cout << "... allocating " << n << " bytes...\n";
}
static void track_delete(void * p)
{
const int n = int(allocs[p]);
memtrack -= n;
std::cout << "... freeing " << n << " bytes...\n";
}
} m;
int Memtrack::memtrack = 0;
int Memtrack::memmax = 0;
Memtrack::AllocMap Memtrack::allocs;
void * operator new(std::size_t n) throw(std::bad_alloc)
{
void * const p = std::malloc(n);
Memtrack::track_new(n, p);
return p;
}
void operator delete(void * p) throw()
{
Memtrack::track_delete(p);
std::free(p);
}
int main()
{
std::cout << "Beginning of main.\n";
std::unordered_map<std::string, int> m; // this piece of code
m["hello"] = 4; // is a typical test for working
m["world"] = 7; // with dynamic allocations
std::cout << "End of main.\n";
}
Some typical output:
starting tracker: cur = 0, max = 0.
Beginning of main.
... allocating 48 bytes...
... allocating 12 bytes...
... allocating 12 bytes...
End of main.
... freeing 12 bytes...
... freeing 12 bytes...
... freeing 48 bytes...
ending tracker: cur = 0, max = 72.
Trivial. If you have some time (which might be the case, if you are only interested in the size for debugging/optimising purposes). This approach might be unsuited for production code!
#include <malloc.h>
template <typename T> int objSize(T const* obj) {
// instead of uordblks, you may be interested in 'arena', you decide!
int oldSize = mallinfo().uordblks;
T* dummy = new T(*obj);
int newSize = mallinfo().uordblks;
delete dummy;
return newSize - oldSize;
}