Roslyn - Parse string to MethodDeclarationSyntax - roslyn

Is there any function in Roslyn, by which I can parse my string as a MethodDeclarationSyntax?
I have a file which contains the method declaration, so I am reading that file content to string and now I want to create a Method from that string. Any suggestions?

One option is to parse your string as "C# Script", an experimental version of C# that allows top-level method declarations. Doing:
var tree = SyntaxTree.ParseText("void Foo() {}", options: new ParseOptions(kind: SourceCodeKind.Script));
Gives you a valid syntax tree that contains a CompilationUnitSyntax of a single method declaration.

Related

extract specific string from a file using c++

file content:
/function name: input\n\t\tworking: inputs details\n\t\t/
/*fuction name: datawrite\n\t\tworking: write the data into the file
*/
/function name: dataread\n\tworking: read the data in the file for
display/
/*funtion name: accsummary\n\t\tworking: display the content of the
file of specific person */
I want to extract only the "function names" and the "workings" from the file and store them into the array of string. "using c++"
that is, if i have declared an array of string function[10] then this should store "input,datawrite,dataread,accsummary" similarly from "working"
This sounds like a task for regular expression. In C++ there is support for regex especially regex_match.
I guess, this should get you started. But be warned, what you are trying to accomplish will not be solved by simple regex.
Your matching string might look something like this
/\/function name: ([^\\]*).*/
This will look for string "function name: " followed by any character other than \ . and then any character up to the end of the line. The second part will be remembered and can be accessed by regex_match.
Try it in online regex tester and modify it based on your specific needs. Just note that it takes regex without leading and ending /.
Oh, I noticed that you asked also for extracting workings, while my example extracts only function names. But you will get there when you get the concept.
You need to take a look at the std::stringstream class:
http://www.cplusplus.com/reference/sstream/stringstream/
Then you need to look at the substr method in std::string:
http://www.cplusplus.com/reference/string/string/substr/

Xerces-c SaxParser issues

I am using xerces-c to parse an XML file but I am getting some strange results.
I create my own DocumentHandler (derived from HandlerBase) and override:
void characters(const XMLCh* const chars, const unsigned int length);
this way I receive notification of character data inside an element.
To parse a file I create a parser, create an inputbuffer, create my handler and call parse.
SAXParser* lp_parser = new SAXParser();
XMLCh* lp_fileName = XMLString::transcode("myfile.xml");
LocalFileInputSource l_fileBuf(lp_fileName);
XMLString::release(&lp_fileName);
MyHandler l_handler;
lp_parser->setDocumentHandler((DocumentHandler *)&l_handler);
lp_parser->parse(l_fileBuf);
delete lp_parser;
The problem is that characters([...]) is not only being called with character data, but also (sometimes several times) for each tag it is called giving me a set of spaces and a newline as character data.
i.e. <Tag>Value</Tag> yields two calls to characters([...]), one where the data is 'Value' and another (or multiple ones) where the data is something like ' \n '
The xml file itself doesn't contain these characters. I have user xerces-c to parse XML like this many times without any problems, although this is the first time I use a LocalFileInputSource (I usually use a MemBufInputSource).
Any ideas?
I had a similar problem with SAX2XMLReader. What I understood is that with SAX parsers it is up to the developer to know where he is in the XML structure while parsing.
It is possible that these subsequent call to characters() are for other tags in the file or ignorable whitespaces.
Depending on the length of the data it is also possible that callback characters be called several times for the same tag. And it is up to you to concatenate the data you receive on each call.
So what I would do is detect the start and end of tag <Tag> with callback functions startElement() and endElement(). In this way you can discard subsequent call to characters() once you have received the endElement() for your tag.

How to use javascript's regular expression by jsni?

Same question has been asked here:
How to pass a regular expression as a function parameter, but I can't get it work by JSNI.
This is the string of the regular expression that will be used to test email:
"^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"
and if putting it to firebug execute like this:
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"/.test("test#domain.com")
it will give what I want,but If wrapping it to a JSNI method:
private native String reEmail()/-*{
return "^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
}-*/;
then passing it to the function:
private native boolean validate(String value, String regexp)/-*{
//escape special characters
var re=regexp.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
return new RegExp(re,'g').test(value)
}-*/;
like this:
validate("test#domain.com",reEmail());
It will give me false.Please tell what mistakes I have made,thanks.
Why do you want to use JSNI for regular expressions?. Gwt already has classes to deal with them.
I would use com.google.gwt.regexp.shared.Regexp that features like Javascript's RegExp.
Using gwt com.google.gwt.regexp.shared.RegExp you have many advantages:
don't have to deal with JSNI, saving syntax errors.
make your code testable since RegExp can be used in JVM.
let the implementation escape strings or whatever.
performance would be the same
Your code could be like:
// Note that you have to double escape \
RegExp r = RegExp.compile("^(([^<>()[\\]\\\\.,;:\\s#\"]+(\\.[^<>()[\\]\\\\.,;:\\s#\"]+)*)|(\".+\"))#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$");
if (r.test("test#domain.com")) {
} else {
}
Anyway if you continue wanting to do in your way, to make your code work, you should escape your string before returning to java instead of in the place you are trying to do, also your JSNI block syntax is incorrect, note /*-{}-*/ instead of /-*{}*-/. And you don't need the 'g' flag.
validate("test#domain.com",reEmail());
private native String reEmail() /*-{
return "^(([^<>()[\\]\\\\.,;:\\s#\"]+(\\.[^<>()[\\]\\\\.,;:\\s#\"]+)*)|(\".+\"))#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
}-*/;
private native boolean validate(String value, String regexp)/*-{
return new RegExp(regexp).test(value)
}-*/;

How to break from groovy 'eachFileMatch()'

I have a working script that lists all pdf files in a directory. It's working as desired but all I need is actually the file name of the first pdf file. Then I want to break the eachFileMatch() as there could be thousands of pdf files in the directory.
I tried to use find from this Break from groovy each closure answer after eachFileMatch().find but didn't work Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.eachFileMatch() is applicable for argument types: (java.util.regex.Pattern) values: [.*.(?i)pdf]
def directory="c:\\tmp" // place 2 or more pdf files in that
// directory and run the script
def p = ~/.*.(?i)pdf/
new File( directory ).eachFileMatch(p) { pdf ->
println pdf // and break
}
Could anyone give me an idea how to do so?
you can not break out of these each{} methods (exceptions will work, but that would be really dirty). if you check the code for eachFileMatch, you see, that it already reads the whole list() and itereates over it. so one option here is to just use the regular JDK methods and use find to return the first:
// only deal with filenames as string
println new File('/tmp').list().find{it=~/.tmp$/}
// work with `File` objects
println new File('/tmp').listFiles().find{it.isFile() && it=~/.tmp$/}
use
^.*?.(?i)pdf
this will give only the first match

Get Non Indented string from Json Object

I have a json object in c++. I am using json_cpp library.
I want to get the string from the Json::Value object. I am using it like below.
Json::Value obj;
....
....
....
string str = obj.toStyledString();
This returns the string in the pretty print format. But I want the string without any indentation. How can I do that as there are no other functions provided in the class?
You could use Json::FastWriter it does not have any indentation and formatting since it outputs everything on a single line. it is normally not suitable for 'human' consumption.
std::string toUnStyledString(const Json::Value& value)
{
Json::FastWriter writer;
return writer.write( value );
}
The function toStyledString also simply uses a Json::StyledWriter if you look into the definition of Json::Value::toStyledString.
Well, if this library doesn't provide appropriate methods then you could write them yourself. The JSON format is rather simple, so I don't think that it will take a lot of work.
Here you can find a good graphical representation of JSON format:
http://json.org
P.S. I've never worked with this particular library, so I propose sort of a general solution.
UPDATE: another option is to get a string returned by toStyledString() and remove indentation. But it requires string processing and will probably be resource consuming. Note that you can't just remove tabs/spaces/new line symbols, because they can be a part of JSON object.
Why do you want unindented string again?