Search Results

Search found 458 results on 19 pages for 'grammar'.

Page 8/19 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Java static source analysis/parsing (possibly with antlr), what is a good tool to do this?

    - by Berlin Brown
    I need to perform static source analysis on Java code. Ideally, I want the system to work out of the box without much modification from me. For example, I have used Antlr in the past, but I spent a lot of time building grammar files and still didn't get what I wanted. I want to be able to parse a java file and have return the character position of say: Character position start and end of a Java block comment Character position start and end of a Java class file Character position start and end of a Java method declaration, signature, and implementation. It looks like Antlr will do that, but I have yet to finish a grammar that actually gives me the positions of the code I need. Does anyone have that complete Antlr grammar and Java code to give the character positions of the parts in the Java source.

    Read the article

  • Haskell's cabal dependency problem with happy

    - by wirrbel
    I have problems installing ghc-mod on my linux machine. cabal worries about "happy" not being available in versione = 1.17: $ cabal install ghc-mod Resolving dependencies... [1 of 1] Compiling Main ( /tmp/haskell-src-exts-1.14.0-1357/haskell-src-exts-1.14.0/Setup.hs, /tmp/haskell-src-exts-1.14.0-1357/haskell-src-exts-1.14.0/dist/setup/Main.o ) Linking /tmp/haskell-src-exts-1.14.0-1357/haskell-src-exts-1.14.0/dist/setup/setup ... Configuring haskell-src-exts-1.14.0... setup: The program happy version =1.17 is required but it could not be found. Failed to install haskell-src-exts-1.14.0 cabal: Error: some packages failed to install: ghc-mod-3.1.3 depends on haskell-src-exts-1.14.0 which failed to install. haskell-src-exts-1.14.0 failed during the configure step. The exception was: ExitFailure 1 hlint-1.8.53 depends on haskell-src-exts-1.14.0 which failed to install. However, it even is installed in v. 1.19, as you can see here: $ cabal install happy Resolving dependencies... [1 of 1] Compiling Main ( /tmp/happy-1.19.0-1124/happy-1.19.0/Setup.lhs, /tmp/happy-1.19.0-1124/happy-1.19.0/dist/setup/Main.o ) Linking /tmp/happy-1.19.0-1124/happy-1.19.0/dist/setup/setup ... Configuring happy-1.19.0... Building happy-1.19.0... Preprocessing executable 'happy' for happy-1.19.0... [ 1 of 18] Compiling NameSet ( src/NameSet.hs, dist/build/happy/happy-tmp/NameSet.o ) [ 2 of 18] Compiling Target ( src/Target.lhs, dist/build/happy/happy-tmp/Target.o ) [ 3 of 18] Compiling AbsSyn ( src/AbsSyn.lhs, dist/build/happy/happy-tmp/AbsSyn.o ) [ 4 of 18] Compiling ParamRules ( src/ParamRules.hs, dist/build/happy/happy-tmp/ParamRules.o ) [ 5 of 18] Compiling GenUtils ( src/GenUtils.lhs, dist/build/happy/happy-tmp/GenUtils.o ) [ 6 of 18] Compiling ParseMonad ( src/ParseMonad.lhs, dist/build/happy/happy-tmp/ParseMonad.o ) [ 7 of 18] Compiling Lexer ( src/Lexer.lhs, dist/build/happy/happy-tmp/Lexer.o ) [ 8 of 18] Compiling Parser ( dist/build/happy/happy-tmp/Parser.hs, dist/build/happy/happy-tmp/Parser.o ) [ 9 of 18] Compiling AttrGrammar ( src/AttrGrammar.lhs, dist/build/happy/happy-tmp/AttrGrammar.o ) [10 of 18] Compiling AttrGrammarParser ( dist/build/happy/happy-tmp/AttrGrammarParser.hs, dist/build/happy/happy-tmp/AttrGrammarParser.o ) [11 of 18] Compiling Grammar ( src/Grammar.lhs, dist/build/happy/happy-tmp/Grammar.o ) [12 of 18] Compiling First ( src/First.lhs, dist/build/happy/happy-tmp/First.o ) [13 of 18] Compiling LALR ( src/LALR.lhs, dist/build/happy/happy-tmp/LALR.o ) [14 of 18] Compiling Paths_happy ( dist/build/autogen/Paths_happy.hs, dist/build/happy/happy-tmp/Paths_happy.o ) [15 of 18] Compiling ProduceCode ( src/ProduceCode.lhs, dist/build/happy/happy-tmp/ProduceCode.o ) [16 of 18] Compiling ProduceGLRCode ( src/ProduceGLRCode.lhs, dist/build/happy/happy-tmp/ProduceGLRCode.o ) [17 of 18] Compiling Info ( src/Info.lhs, dist/build/happy/happy-tmp/Info.o ) [18 of 18] Compiling Main ( src/Main.lhs, dist/build/happy/happy-tmp/Main.o ) Linking dist/build/happy/happy ... Installing executable(s) in /home/hope/.cabal/bin Installed happy-1.19.0 Any ideas? cabal-install version 1.16.0.2 using version 1.16.0 of the Cabal library

    Read the article

  • Where can I get material for learning EBNF?

    - by yesraaj
    Extended Backus–Naur Form: EBNF I'm very new to parsing concepts. Where can I get sufficiently easy to read and follow material for writing a grammar for the boost::spirit library, which uses a grammar similar to EBNF? Currently I am looking into EBNF from Wikipedia.

    Read the article

  • Creating AST for shared and local variables

    - by Rizwan Abbasi
    Here is my grammar grammar simulator; options { language = Java; output = AST; ASTLabelType=CommonTree; } //imaginary tokens tokens{ SHARED; LOCALS; BOOL; RANGE; ARRAY; } parse : declaration+ ; declaration :variables ; variables : locals ; locals : (bool | range | array) ; bool :ID 'in' '[' ID ',' ID ']' ('init' ID)? -> ^(BOOL ID ID ID ID?) ; range : ID 'in' '[' INT '..' INT ']' ('init' INT)? -> ^(RANGE ID INT INT INT?) ; array :ID 'in' 'array' 'of' '[' INT '..' INT ']' ('init' INT)? -> ^(ARRAY ID INT INT INT?) ; ID : (('a'..'z' | 'A'..'Z'|'_')('a'..'z' | 'A'..'Z'|'0'..'9'|'_'))* ; INT : ('0'..'9')+ ; WHITESPACE : ('\t' | ' ' | '\r' | '\n' | '\u000C')+ {$channel = HIDDEN;} ; INPUT flag in [down, up] init down pc in [0..7] init 0 CA in array of [0..5] init 0 AST It is having a small problem. Variables (bool, range or array) can be of two abstract types 1. locals (each object will have it's own variable) 2. shared (think of static in java, same for all object) Now the requirements are changed. I want the user to input like this NEW INPUT domains: upDown [up,down] possibleStates [0-7] booleans [true,false] locals: pc in possibleStates init 0 flag in upDown init down flag1 in upDown init down map in array of booleans init false shared: pcs in possibleStates init 0 flag in upDown init down flag1 in upDown init down maps in array of booleans init false Again, all the variables can be of two types (of any domain sepecified) 1. Local 2. Shared In Domains: upDown [up,down] possibleStates [0-7] upDown, up, down and possibleStates are of type ID (ID is defined in my above grammar), 0 and 7 are of type INT Can any body help me how to convert my current grammar to meet new specifications.

    Read the article

  • What is the easiest way to generate a Valid x:Name?

    - by just in case
    I am generating some Xaml based on some other source of input. In some cases I am generating x:Name values but they have invalid characters. I found this article on MSDN: XamlName Grammar Which describes the grammar of a x:Name tag but doesn't tell me how to actually apply this. Clearly there is some code to validate this name at runtime but what is the easiest way to actually fix up a string with invalid characters?

    Read the article

  • ANTLR AST rules fail with RewriteEmptyStreamException

    - by Barry Brown
    I have a simple grammar: grammar sample; options { output = AST; } assignment : IDENT ':=' expr ';' ; expr : factor ('*' factor)* ; factor : primary ('+' primary)* ; primary : NUM | '(' expr ')' ; IDENT : ('a'..'z')+ ; NUM : ('0'..'9')+ ; WS : (' '|'\n'|'\t'|'\r')+ {$channel=HIDDEN;} ; Now I want to add some rewrite rules to generate an AST. From what I've read online and in the Language Patterns book, I should be able to modify the grammar like this: assignment : IDENT ':=' expr ';' -> ^(':=' IDENT expr) ; expr : factor ('*' factor)* -> ^('*' factor+) ; factor : primary ('+' primary)* -> ^('+' primary+) ; primary : NUM | '(' expr ')' -> ^(expr) ; But it does not work. Although it compiles fine, when I run the parser I get a RewriteEmptyStreamException error. Here's where things get weird. If I define the pseudo tokens ADD and MULT and use them instead of the tree node literals, it works without error. tokens { ADD; MULT; } expr : factor ('*' factor)* -> ^(MULT factor+) ; factor : primary ('+' primary)* -> ^(ADD primary+) ; Alternatively, if I use the node suffix notation, it also appears to work fine: expr : factor ('*'^ factor)* ; factor : primary ('+'^ primary)* ; Is this discrepancy in behavior a bug?

    Read the article

  • What was Tim Sweeney thinking? (How does this C++ parser work?)

    - by Frank Krueger
    Tim Sweeney of Epic MegaGames is the lead developer for Unreal and a programming language geek. Many years ago posted the following screen shot to VoodooExtreme: As a C++ programmer and Sweeney fan, I was captivated by this. It shows generic C++ code that implements some kind of scripting language where that language itself seems to be generic in the sense that it can define its own grammar. Mr. Sweeney never explained himself. :-) It's rare to see this level of template programming, but you do see it from time to time when people want to push the compiler to generate great code or because they want to create generic code (for example, Modern C++ Design). Tim seems to be using it to create a grammar in Parser.cpp - you can see what look like prioritized binary operators. If that is the case, then why does Test.ae look like it's also defining a grammar? Obviously this is a puzzle that needs to be solved. Victory goes to the answer with a working version of this code, or the most plausible explanation, or to Tim Sweeney himself if he posts an answer. :-)

    Read the article

  • Extracting URIs from RDF web page in Java using Jena Library

    - by Prannoy Mittal
    I have written following code for extratcting URIs from a web page with content type application/rdf-xml for Linked Data application. public static void test(String url) { try { Model read = ModelFactory.createDefaultModel().read(url); System.out.println("to go"); StmtIterator si; si = read.listStatements(); System.out.println("to go"); while(si.hasNext()) { Statement s=si.nextStatement(); Resource r=s.getSubject(); Property p=s.getPredicate(); RDFNode o=s.getObject(); System.out.println(r.getURI()); System.out.println(p.getURI()); System.out.println(o.asResource().getURI()); } } catch(JenaException | NoSuchElementException c) { } } But above code is not extracting all URIs. It provides only few of the URIs. Please guide me where i Went wrong?? hey Rafeel For Eq: for XML File : <?xml version="1.0"?> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:ex="http://example.org/stuff/1.0/"> <rdf:Description rdf:about="http://www.w3.org/TR/rdf-syntax-grammar" dc:title="RDF/XML Syntax Specification (Revised)"> <ex:editor> <rdf:Description ex:fullName="Dave Beckett"> <ex:homePage rdf:resource="http://purl.org/net/dajobe/" /> </rdf:Description> </ex:editor> </rdf:Description> </rdf:RDF> The output is : Subject URI is http://www.w3.org/TR/rdf-syntax-grammar Predicate URI is http://example.org/stuff/1.0/editor Object URI is null Subject URI is http://www.w3.org/TR/rdf-syntax-grammar Predicate URI is http://purl.org/dc/elements/1.1/title Website is read

    Read the article

  • Treetop basic parsing and regular expression usage

    - by ucint
    I'm developing a script using the ruby Treetop library and having issues working with its syntax for regex's. First off, many regular expressions that work in other settings dont work the same in treetop. This is my grammar: (myline.treetop) grammar MyLine rule line string whitespace condition end rule string [\S]* end rule whitespace [\s]* end rule condition "new" / "old" / "used" end end This is my usage: (usage.rb) require 'rubygems' require 'treetop' require 'polyglot' require 'myline' parser = MyLineParser.new p parser.parse("randomstring new") This should find the word new for sure and it does! Now I wont to extend it so that it can find new if the input string becomes "randomstring anotherstring new yetanother andanother" and possibly have any number of strings followed by whitespace (tab included) before and after the regex for rule condition. In other words, if I pass it any sentence with the word "new" etc in it, it should be able to match it. So let's say I change my grammar to: rule line string whitespace condition whitespace string end Then, it should be able to find a match for: p parser.parse("randomstring new anotherstring") So, what do I have to do to allow the string whitespace to be repeated before and after condition? If I try to write this: rule line (string whitespace)* condition (whitespace string)* end , it goes in an infinite loop. If i replace the above () with [], it returns nil In general, regex's return a match when i use the above, but treetop regex's dont. Does anyone have any tips/points on how to go about this? Plus, since there isn't much documentation for treetop and the examples are either too trivial or too complex, is there anyone who knows a more thorough documentation/guide for treetop?

    Read the article

  • How to embed XBase expressions in an Xtext DSL

    - by Marcus Mathioudakis
    I am writing a simple little DSL for specifying constraints on messages, and Have been trying without success for a while to embed XBase expressions into the language. The Grammar looks like this: grammar org.xtext.businessrules.BusinessRules with org.eclipse.xtext.xbase.Xbase //import "http://www.eclipse.org/xtext/xbase/Xbase" as xbase import "http://www.eclipse.org/xtext/common/JavaVMTypes" as jvmTypes generate businessRules "http://www.xtext.org/businessrules/BusinessRules" Start: rules+=Constraint*; Constraint: {Constraint} 'FOR' 'PAYLOAD' payload=PAYLOAD 'ELEMENT' element=ID 'CONSTRAINED BY' constraint=XExpression; PAYLOAD: "SimulationSessionEvents" |"stacons" |"any" ; Range: 'above' min=INT ('below' max=INT)? |'below' max=INT ('above' min=INT)? ; When trying to parse a file such as: FOR PAYLOAD SimulationSessionEvents ELEMENT matrix CONSTRAINED BY ... I can't get it to work for ... = any kind of Arithmetic expression, although it works for ...= loop or if expression, or even just a number. As soon as I do something like '-5' or '4-5' it says Couldn't resolve reference to JvmIdentifiableElement '-', even though the Xbase.xtext Grammar looks like it allows these expressions. I don't think I'm missing any Jars, as it doesn't complain when I run the mwe workflow, but only when trying to parse the input file. Any help would be much appreciated.

    Read the article

  • Memory not being returned after function python call

    - by Dan
    I've got a function which does a parse of a sentence by building up a big chart. For some reason, Python holds on to whatever memory was allocated during that function call. That is, I do best = translate(sentence, grammar) and somehow my memory goes up and stays up. Here is the function: from string import join from heapq import nsmallest, heappush def translate(f, g): words = f.split() chart = {} for col in range(len(words)): for row in reversed(range(0,col+1)): # get rules for this subspan rules = g[join(words[row:col+1], ' ')] # ensure there's at least one rule on the diagonal if not rules and row==col: rules=[(0.0, join(words[row:col+1]))] # pick up rules below & to the left for k in range(row,col): if (row,k) and (k+1,col) in chart: for (w1, e1) in chart[row, k]: for (w2, e2) in chart[k+1,col]: heappush(rules, (w1+w2, e1+' '+e2)) # add all rules to chart chart[row,col] = nsmallest(MAX_TRANSLATIONS, rules) (w, best) = chart[0, len(words)-1][0] return best EDIT: Using Python 2.7 on OS X. The grammar g is just a dictionary from strings to heaps, e.g.: g['et'] [(1.05, 'and'), (6.92, ', and'), (9.95, 'and ,'), (11.17, 'and to')] EDIT: If you want to run the code, try the sentence "Cela est difficile" with the following grammar: >>> g['cela'] [(8.28, 'this'), (11.21, 'it'), (11.57, 'that'), (15.26, 'this ,')] >>> g['est'] [(2.69, 'is'), (10.21, 'is ,'), (11.15, 'has'), (11.28, ', is')] >>> g['difficile'] [(2.01, 'difficult'), (10.08, 'hard'), (10.19, 'difficult ,'), (10.57, 'a difficult')]

    Read the article

  • sudoers - simple explanation requested

    - by Redsandro
    Everytime I want to be able to run something that requires me to be a sudoer too many times, I need to google for the formatting of /etc/sudoers to remind me again what exactly is the proper way to write it. Now I see different writing styles in my sudoers file, which is the consequence of different google results over the months. I've also noticed that the second example (below) seems to work in XFCE, but not in Cinnamon (Gnome 3). This could be totally unrelated, but nontheless I'd like to know once and for all, what is the correct grammar of the sudoer line, and what is the difference between the given examples? redsandro ALL=NOPASSWD:/path/to/command redsandro ALL=(ALL) NOPASSWD:/path/to/command redsandro ALL=(ALL:ALL) NOPASSWD:/path/to/command Also, what are all the ALL's for? One user, one command, yet I need to use the ALL keyword up to three times? Am I doing this wrong? Of course, omitting NOPASSWD: makes you enter your password before you are permitted to run the command, but one point of confusion is the usage of = and :, for the final command that is the subject of the line can be prepended by either =, :, , or ), confusing grammar for similar semantics.

    Read the article

  • How to implement string matching based on a pattern

    - by Vincent Rischmann
    I was asked to build a tool that can identify if a string match a pattern. Example: {1:20} stuff t(x) {a,b,c} would match: 1 stuff tx a 20 stuff t c It is a sort of regex but with a different syntax Parentheses indicate an optional value {1:20} is a interval; I will have to check if the token is a number and if it is between 1 and 20 {a,b,c} is just an enumeration; it can be either a or b or c Right now I implemented this with a regex, and the interval stuff was a pain to do. On my own time I tried implementing some kind of matcher by hand, but it turns out it's not that easy to do. By experimenting I ended up with a function that generates a state table from the pattern and a state machine. It worked well until I tried to implement the optional value, and I got stuck and how to generate the state table. After that I searched how I could do this, and that led me to stuff like LL parser, LALR parser, recursive-descent parser, context-free grammars, etc. I never studied any of this so it's hard to know what is relevant here, but I think this is what I need: A grammar A parser which generates states from the grammar and a pattern A state machine to see if a string match the states So my first question is: Is this right ? And second question, what do you recommend I read/study to be able to implement this ?

    Read the article

  • Delphi Speech recognition delphi

    - by XBasic3000
    I need create a programatic equivalent using delphi language... or could someone post a link on how to do grammars in peech recogniton using the delphi. sorry for my english... XML Grammar Sample(s): <GRAMMAR> <!-- Create a simple "hello world" rule --> <RULE NAME="HelloWorld" TOPLEVEL="ACTIVE"> <P>hello world</P> </RULE> <!-- Create a more advanced "hello world" rule that changes the display form. When the user says "hello world" the display text will be "Hiya there!" --> <RULE NAME="HelloWorld_Disp" TOPLEVEL="ACTIVE"> <P DISP="Hiya there!">hello world</P> </RULE> <!-- Create a rule that changes the pronunciation and the display form of the phrase. When the user says "eh" the display text will be "I don't understand?". Note the user didn't say "huh". The pronunciation for "what" is specific to this phrase tag and is not changed for the user or application lexicon, or even other instances of "what" in the grammar --> <RULE NAME="Question_Pron" TOPLEVEL="ACTIVE"> <P DISP="I don't understand" PRON="eh">what</P> </RULE> <!-- Create a rule demonstrating repetition --> <!-- the rule will only be recognized if the user says "hey diddle diddle" --> <RULE NAME="NurseryRhyme" TOPLEVEL="ACTIVE"> <P>hey</P> <P MIN="2" MAX="2">diddle</P> </RULE> <!-- Create a list with variable phrase weights --> <!-- If the user says similar phrases, the recognizer will use the weights to pick a match --> <RULE NAME="UseWeights" TOPLEVEL="ACTIVE"> <LIST> <!-- Note the higher likelihood that the user is expected to say "recognizer speech" --> <P WEIGHT=".95">recognize speech</P> <P WEIGHT=".05">wreck a nice beach</P> </LIST> </RULE> <!-- Create a phrase with an attached semantic property --> <!-- Speaking "one two three" will return three different unique semantic properties, with different names, and different values --> <RULE NAME="UseProps" TOPLEVEL="ACTIVE"> <!-- named property, without value --> <P PROPNAME="NOVALUE">one</P> <!-- named property, with numeric value --> <P PROPNAME="NUMBER" VAL="2">two</P> <!-- named property, with string value --> <P PROPNAME="STRING" VALSTR="three">three</P> </RULE> </GRAMMAR> **Programmatic Equivalent:** To add a phrase to a rule, SAPI provides an API called ISpGrammarBuilder::AddWordTransition. The application developer can add the sentences as follows: SPSTATEHANDLE hsHelloWorld; // Create new top-level rule called "HelloWorld" hr = cpRecoGrammar->GetRule(L"HelloWorld", NULL, SPRAF_TopLevel | SPRAF_Active, TRUE, &hsHelloWorld); // Check hr // Add the command words "hello world" // Note that the lexical delimiter is " ", a space character. // By using a space delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hello world", L" ", SPWT_LEXICAL, NULL, NULL); // Check hr // Add the command words "hiya there" // Note that the lexical delimiter is "|", a pipe character. // By using a pipe delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hiya|there", L"|", SPWT_LEXICAL, NULL, NULL); // Check hr // save/commit changes hr = cpRecoGrammar->Commit(NULL); // Check hr

    Read the article

  • Removing Left Recursion in ANTLR

    - by prosseek
    As is explained in http://stackoverflow.com/questions/2652060/removing-left-recursion , there are two ways to remove the left recursion. Modify the original grammar to remove the left recursion using some procedure Write the grammar originally not to have the left recursion What people normally use for removing (not having) the left recursion with ANTLR? I've used flex/bison for parser, but I need to use ANTLR. The only thing I'm concerned about using ANTLR (or LL parser in genearal) is left recursion removal. In practical sense, how serious of removing left recursion in ANTLR? Is this a showstopper in using ANTLR? Or, nobody cares about it in ANTLR community? I like the idea of AST generation of ANTLR. In terms of getting AST quick and easy way, which method (out of the 2 removing left recursion methods) is preferable?

    Read the article

  • Improving ANTLR DSL parse-error messages

    - by Dan Fabulich
    I'm working on a domain-specific language (DSL) for non-programmers. Non-programmers make a lot of grammar mistakes: they misspell keywords, they don't close parentheses, they don't terminate blocks, etc. I'm using ANTLR to generate my parser; it provides a nifty mechanism for handling RecognitionExceptions to improve error handling. But I'm finding it pretty hard to develop good error-handling code for my DSL. At this point, I'm considering ways to simplify the language to make it easier for me to provide users with high-quality error messages, but I'm not really sure how to go about this. I think I want to reduce the ambiguity of errors somehow, but I'm not sure how to implement that idea in a grammar. In what ways can I simplify my language to improve parse-error messages for my users? EDIT: Updated to clarify that I'm interested in ways to simplify my language, not just ANTLR error-handling tips in general. (Though, thanks for those!)

    Read the article

  • SAPI Speech recognition delphi

    - by XBasic3000
    I need create a programatic equivalent using delphi language... or could someone post a link on how to do grammars in peech recogniton using the delphi. sorry for my english... **Programmatic Equivalent C#:** Ref: http://msdn.microsoft.com/en-us/library/ms723634(v=VS.85).aspx To add a phrase to a rule, SAPI provides an API called ISpGrammarBuilder::AddWordTransition. The application developer can add the sentences as follows: SPSTATEHANDLE hsHelloWorld; // Create new top-level rule called "HelloWorld" hr = cpRecoGrammar->GetRule(L"HelloWorld", NULL, SPRAF_TopLevel | SPRAF_Active, TRUE, &hsHelloWorld); // Check hr // Add the command words "hello world" // Note that the lexical delimiter is " ", a space character. // By using a space delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hello world", L" ", SPWT_LEXICAL, NULL, NULL); // Check hr // Add the command words "hiya there" // Note that the lexical delimiter is "|", a pipe character. // By using a pipe delimiter, the entire phrase can be added // in one method call hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL, L"hiya|there", L"|", SPWT_LEXICAL, NULL, NULL); // Check hr // save/commit changes hr = cpRecoGrammar->Commit(NULL); // Check hr XML Grammar Sample(s): <GRAMMAR> <!-- Create a simple "hello world" rule --> <RULE NAME="HelloWorld" TOPLEVEL="ACTIVE"> <P>hello world</P> </RULE> <!-- Create a more advanced "hello world" rule that changes the display form. When the user says "hello world" the display text will be "Hiya there!" --> <RULE NAME="HelloWorld_Disp" TOPLEVEL="ACTIVE"> <P DISP="Hiya there!">hello world</P> </RULE> <!-- Create a rule that changes the pronunciation and the display form of the phrase. When the user says "eh" the display text will be "I don't understand?". Note the user didn't say "huh". The pronunciation for "what" is specific to this phrase tag and is not changed for the user or application lexicon, or even other instances of "what" in the grammar --> <RULE NAME="Question_Pron" TOPLEVEL="ACTIVE"> <P DISP="I don't understand" PRON="eh">what</P> </RULE> <!-- Create a rule demonstrating repetition --> <!-- the rule will only be recognized if the user says "hey diddle diddle" --> <RULE NAME="NurseryRhyme" TOPLEVEL="ACTIVE"> <P>hey</P> <P MIN="2" MAX="2">diddle</P> </RULE> <!-- Create a list with variable phrase weights --> <!-- If the user says similar phrases, the recognizer will use the weights to pick a match --> <RULE NAME="UseWeights" TOPLEVEL="ACTIVE"> <LIST> <!-- Note the higher likelihood that the user is expected to say "recognizer speech" --> <P WEIGHT=".95">recognize speech</P> <P WEIGHT=".05">wreck a nice beach</P> </LIST> </RULE> <!-- Create a phrase with an attached semantic property --> <!-- Speaking "one two three" will return three different unique semantic properties, with different names, and different values --> <RULE NAME="UseProps" TOPLEVEL="ACTIVE"> <!-- named property, without value --> <P PROPNAME="NOVALUE">one</P> <!-- named property, with numeric value --> <P PROPNAME="NUMBER" VAL="2">two</P> <!-- named property, with string value --> <P PROPNAME="STRING" VALSTR="three">three</P> </RULE> </GRAMMAR>

    Read the article

  • Help with Boost Spirit ASTs

    - by Decmac04
    I am writing a small tool for analyzing simple B Machine substitutions as part of a college research work. The code successfully parse test inputs of the form mySubst := var1 + var2. However, I get a pop-up error message saying "This application has requested the Runtime to terminate it in an unusual way. " In the command prompt window, I get an "Assertion failed message". The main program is given below: // BMachineTree.cpp : Defines the entry point for the console application. // /*============================================================================= Copyright (c) 2010 Temitope Onunkun =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // // UUsing Boost Spririt Trees (AST) to parse B Machine Substitutions. // /////////////////////////////////////////////////////////////////////////////// #define BOOST_SPIRIT_DUMP_PARSETREE_AS_XML #include <boost/spirit/core.hpp> #include <boost/spirit/tree/ast.hpp> #include <boost/spirit/tree/tree_to_xml.hpp> #include "BMachineTreeGrammar.hpp" #include <iostream> #include <stack> #include <functional> #include <string> #include <cassert> #include <vector> #if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML) #include <map> #endif // Using AST to parse B Machine substitutions //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; typedef char const* iterator_t; typedef tree_match<iterator_t> parse_tree_match_t; typedef parse_tree_match_t::tree_iterator iter_t; //////////////////////////////////////////////////////////////////////////// string evaluate(parse_tree_match_t hit); string eval_machine(iter_t const& i); vector<string> dx; string evaluate(tree_parse_info<> info) { return eval_machine(info.trees.begin()); } string eval_machine(iter_t const& i) { cout << "In eval_machine. i->value = " << string(i->value.begin(), i->value.end()) << " i->children.size() = " << i->children.size() << endl; if (i->value.id() == substitution::leafValueID) { assert(i->children.size() == 0); // extract string tokens string leafValue(i->value.begin(), i->value.end()); dx.push_back(leafValue.c_str()); return leafValue.c_str(); } // else if (i->value.id() == substitution::termID) { if ( (*i->value.begin() == '*') || (*i->value.begin() == '/') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + " " + eval_machine(i->children.begin()+1); } // else assert(0); } else if (i->value.id() == substitution::expressionID) { if ( (*i->value.begin() == '+') || (*i->value.begin() == '-') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + " " + eval_machine(i->children.begin()+1); } else assert(0); } // else if (i->value.id() == substitution::simple_substID) { if (*i->value.begin() == (':' >> '=') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + "|->" + eval_machine(i->children.begin()+1); } else assert(0); } else { assert(0); // error } return 0; } //////////////////////////////////////////////////////////////////////////// int main() { // look in BMachineTreeGrammar for the definition of BMachine substitution BMach_subst; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "\t\tB Machine Substitution...\n\n"; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "Type an expression...or [q or Q] to quit\n\n"; string str; while (getline(cin, str)) { if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; tree_parse_info<> info = ast_parse(str.c_str(), BMach_subst, space_p); if (info.full) { #if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML) // dump parse tree as XML std::map<parser_id, std::string> rule_names; rule_names[substitution::identifierID] = "identifier"; rule_names[substitution::leafValueID] = "leafValue"; rule_names[substitution::factorID] = "factor"; rule_names[substitution::termID] = "term"; rule_names[substitution::expressionID] = "expression"; rule_names[substitution::simple_substID] = "simple_subst"; tree_to_xml(cout, info.trees, str.c_str(), rule_names); #endif // print the result cout << "Variables in Vector dx: " << endl; for(vector<string>::iterator idx = dx.begin(); idx < dx.end(); ++idx) cout << *idx << endl; cout << "parsing succeeded\n"; cout << "result = " << evaluate(info) << "\n\n"; } else { cout << "parsing failed\n"; } } cout << "Bye... :-) \n\n"; return 0; } The grammar, defined in BMachineTreeGrammar.hpp file is given below: /*============================================================================= Copyright (c) 2010 Temitope Onunkun http://www.dcs.kcl.ac.uk/pg/onun Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_BMachineTreeGrammar_HPP_ #define BOOST_SPIRIT_BMachineTreeGrammar_HPP_ using namespace boost::spirit; /////////////////////////////////////////////////////////////////////////////// // // Using Boost Spririt Trees (AST) to parse B Machine Substitutions. // /////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // // B Machine Grammar // //////////////////////////////////////////////////////////////////////////// struct substitution : public grammar<substitution> { static const int identifierID = 1; static const int leafValueID = 2; static const int factorID = 3; static const int termID = 4; static const int expressionID = 5; static const int simple_substID = 6; template <typename ScannerT> struct definition { definition(substitution const& ) { // Start grammar definition identifier = alpha_p >> (+alnum_p | ch_p('_') ) ; leafValue = leaf_node_d[ lexeme_d[ identifier | +digit_p ] ] ; factor = leafValue | inner_node_d[ ch_p( '(' ) >> expression >> ch_p(')' ) ] ; term = factor >> *( (root_node_d[ch_p('*') ] >> factor ) | (root_node_d[ch_p('/') ] >> factor ) ); expression = term >> *( (root_node_d[ch_p('+') ] >> term ) | (root_node_d[ch_p('-') ] >> term ) ); simple_subst= leaf_node_d[ lexeme_d[ identifier ] ] >> root_node_d[str_p(":=")] >> expression ; // End grammar definition // turn on the debugging info. BOOST_SPIRIT_DEBUG_RULE(identifier); BOOST_SPIRIT_DEBUG_RULE(leafValue); BOOST_SPIRIT_DEBUG_RULE(factor); BOOST_SPIRIT_DEBUG_RULE(term); BOOST_SPIRIT_DEBUG_RULE(expression); BOOST_SPIRIT_DEBUG_RULE(simple_subst); } rule<ScannerT, parser_context<>, parser_tag<simple_substID> > simple_subst; rule<ScannerT, parser_context<>, parser_tag<expressionID> > expression; rule<ScannerT, parser_context<>, parser_tag<termID> > term; rule<ScannerT, parser_context<>, parser_tag<factorID> > factor; rule<ScannerT, parser_context<>, parser_tag<leafValueID> > leafValue; rule<ScannerT, parser_context<>, parser_tag<identifierID> > identifier; rule<ScannerT, parser_context<>, parser_tag<simple_substID> > const& start() const { return simple_subst; } }; }; #endif The output I get on running the program is: ///////////////////////////////////////////////////////// B Machine Substitution... ///////////////////////////////////////////////////////// Type an expression...or [q or Q] to quit mySubst := var1 - var2 parsing succeeded In eval_machine. i->value = := i->children.size() = 2 Assertion failed: 0, file c:\redmound\bmachinetree\bmachinetree\bmachinetree.cpp , line 114 I will appreciate any help in resolving this problem.

    Read the article

  • groovy compile error

    - by Bunny Rabbit
    class x{ public static void main(String[] args){ String x="<html><head></head></html>"; String arr[]=x.split("<head>"); String script="hi"; x=arr[0]+"<head>"+script+arr[1]; System.out.println(x); } } the above code when compiled as a java file compiles fine but when used a s a groovy file spits the error : org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin\x.groovy: 4: Apparent variable 'a rr' was found in a static scope but doesn't refer to a local variable, static fi eld or class. Possible causes: You attempted to reference a variable in the binding or an instance variable fro m a static context. You misspelled a classname or statically imported field. Please check the spelli ng. You attempted to use a method 'arr' but left out brackets in a place not allowed by the grammar. @ line 4, column 10. String arr[]=x.split(""); ^ D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin\x.groovy: 6: Apparent variable 'a rr' was found in a static scope but doesn't refer to a local variable, static fi eld or class. Possible causes: You attempted to reference a variable in the binding or an instance variable fro m a static context. You misspelled a classname or statically imported field. Please check the spelli ng. You attempted to use a method 'arr' but left out brackets in a place not allowed by the grammar. @ line 6, column 5. x=arr[0]+""+script+arr[1]; ^ D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin\x.groovy: 6: Apparent variable 'a rr' was found in a static scope but doesn't refer to a local variable, static fi eld or class. Possible causes: You attempted to reference a variable in the binding or an instance variable fro m a static context. You misspelled a classname or statically imported field. Please check the spelli ng. You attempted to use a method 'arr' but left out brackets in a place not allowed by the grammar. @ line 6, column 28. x=arr[0]+""+script+arr[1]; ^ 3 errors D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin

    Read the article

  • chomsky hierarchy and programming languages

    - by dader51
    Hi, I'm trying to learn some aspects of the CH ( chomsky hierarchy ) which are related to PL ( programming languages ), and i still have to read the Dragon Book. I've read that most of the PL can be parsed as CFG ( context free grammar ). In term of computational power, it equals the one of a pushdown non deterministic automaton. Am I right ? If it's true, then how could a CFG holds a UG ( unrestricted grammar, which is turing complete ) ? I'm asking because, even if PL are CFG they are actually used to describe TM (turing machines ) and through UG. I think that's because of at least two different levels of computing, the first, which is the parsing of a CFG focuses on the syntax related to the structure ( representation ? ) of the language, while the other focuses on the semantic ( sense, interpretation of the data itself ? ) related to the capabilities of the pl which is turing complete. Again, are these assumptions rights ? thanx a lot.

    Read the article

  • ANTLR JavaScript Target

    - by kunalsawlani
    Hello, I have been using ANTLR to generate a parser + tree grammar for a mark up language with Java target which works fine. Now I am trying to get the target in JavaScript to use it in my web browser. However, I have not been able to locate any good documentation on how to go about doing this. I am using eclipse with ANTLR IDE, and when i specify the language as JavaScript, I get the following errors. Multiple markers at this line (10): internal error: group JavaScript does not satisfy interface ANTLRCore: mismatched arguments on these templates [treeParser(grammar, name, scopes, tokens, tokenNames, globalAction, rules, numRules, bitsets, labelType, ASTLabelType, superClass, members, filterMode)] (10): internal error: java.util.NoSuchElementException: no such attribute: filterMode in template context [treeParser] If anyone could help me out with this or point me to some material which I could read about the JavaScript target with ANTLR, it would be great. Thanks

    Read the article

  • How to make concept representation with the help of bag of words

    - by agazerboy
    Hi All, Thanks for stoping to read my question :) this is very sweet place full of GREAT peoples ! I have a question about "creating sentences with words". NO NO it is not about english grammar :) Let me explain, If I have bag of words like "person apple apple person person a eat person will apple eat hungry apple hungry" and it can generate some kind of following sentence "hungry person eat apple" I don't in which field this topic will relate. Where should I try to find an answer. I tried to search google but I only found english grammar stuff :) Any body there who can tell me which algo can work in this problem? or any program Thanks P.S: It is not an assignment :) if it would be i would ask for source code ! I don't even know in which field I should look for :)

    Read the article

  • How to use Speech 2 Text in Microsoft Surface

    - by Roflcoptr
    I'd like to use some speech 2 text in my microsoft surface application. I saw that it is possible, but I don't really know where to start. Is there any framework/library available, or a code snippet, or a tutorial?? I don't even know exactly what i should google for ;) ===EDIT=== I read that it is necessary to use a grammar to recognize words. So if I want to proceed free text, is there a predefined grammar for the english language? Or is it a better choice to don't use speech2text but just audio files instead?

    Read the article

  • Visualizing an AST created with ANTLR (in a .Net environment)

    - by Benjamin Podszun
    Hi there. For a pet project I started to fiddle with ANTLR. After following some tutorials I'm now trying to create the grammar for my very own language and to generate an AST. For now I'm messing around in ANTLRWorks mostly, but now that I have validated that the parse tree seems to be fine I'd like to (iteratively, because I'm still learning and still need to make some decisions regarding the final structure of the tree) create the AST. It seems that antlrworks won't visualize it (or at least not using the "Interpreter" feature, Debug's not working on any of my machines). Bottom line: Is the only way to visualize the AST the manual way, traversing/showing it or printing the tree in string representation to a console? What I'm looking for is a simple way to go from input, grammar - visual AST representation a la the "Interpreter" feature of ANTLRWorks. Any ideas?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >