Getting exception while parsing file using Sprache "Parsing failure: Unexpected end of input reached; expected =" - sprache

I want to parse below file,
first=The_First_Step
{
{
value=First.Value,
}
}
second=The_Second_Step
{
{
another = Second_Value,
more = Yet.More,
}
}
I have written grammar as,
public static NGSection ParseSections(string ngServerConfig)
{
return Sections.End().Parse(ngServerConfig);
}
internal static Parser<string> ValueText = Parse.LetterOrDigit.AtLeastOnce().Text().Token();
internal static Parser<string> Identifier = Parse.AnyChar.AtLeastOnce().Text().Token();
internal static Parser<Config> Config =
from id in Identifier
from equal in Parse.Char('=').Token()
from value in ValueText
from comma in Parse.Char(',').Token()
select new Config(id, value);
internal static Parser<Section> Section =
from id in Identifier
from equal in Parse.Char('=').Token()
from title in ValueText
from lbracket in Parse.Char('{').Token()
from inbracket in Parse.Char('{').Token()
from configs in Config.AtLeastOnce()
from outbracket in Parse.Char('}').Token()
from rbracket in Parse.Char('}').Token()
select new Section(id, title, configs);
internal static Parser<NGSection> Sections =
from sections in Section.AtLeastOnce()
select new NGSection(sections);
I am getting exception as
Parsing failure: Unexpected end of input reached; expected = (Line 13, Column 2); recently consumed: ore
}
}
Any clue will be helpful.

Two problems: first, values can contain _ or . in your example, so LetterOrDigit won't cover it. Should be:
internal static Parser<string> ValueText =
Parse.LetterOrDigit.Or(Parse.Chars('_', '.')).AtLeastOnce().Text().Token();
Next, the Identifier parser's AnyChar is too greedy; you need to exclude the =, or it will be considered part of the identifier:
internal static Parser<string> Identifier =
Parse.CharExcept('=').AtLeastOnce().Text().Token();

Related

picocli CLI parser: hide the Java variable name while rendering the output

I am using picocli to show the usage of my command-line application.
What I am not able to reach is to hide the name of the Java variable which appears in the printed output and from my point of view it looks so ugly.
This is the configutation of my CommandLine.Option:
#CommandLine.Option(
names = {"-a", "--abc"},
description = "Please, hide the Java variable name...")
private String xxx;
And this is how it is rendered:
-a, --abc=<xxx> Please, hide the Java variable name...
As you can see the name of the Java variable appears after the equal sign: <xxx>
I would like to hide it, like this:
-a, --abc Please, hide the Java variable name...
I checked the API but I could not see anything related to this.
Is there any way to turn it off?
The picocli annotations API does not provide for this, but it is possible to achieve this by overriding the Help API and plugging in your own option renderer. For example:
public class HideOptionParams {
#Option(names = {"-u", "--user"}, defaultValue = "${user.name}",
description = "The connecting user name.")
private String user;
#Option(names = {"-p", "--password"}, interactive = true,
description = "Password for the user.")
private String password;
#Option(names = {"-o", "--port"}, defaultValue = "12345",
description = "Listening port, default is ${DEFAULT-VALUE}.")
private int port;
public static void main(String[] args) {
CommandLine cmd = new CommandLine(new HideOptionParams());
cmd.setHelpFactory(new IHelpFactory() {
public Help create(final CommandSpec commandSpec, ColorScheme colorScheme) {
return new Help(commandSpec, colorScheme) {
#Override
public IOptionRenderer createDefaultOptionRenderer() {
return new IOptionRenderer() {
public Text[][] render(OptionSpec option,
IParamLabelRenderer ignored,
ColorScheme scheme) {
return makeOptionList(option, scheme);
}
};
}
};
}
});
cmd.usage(System.out);
}
private static Text[][] makeOptionList(OptionSpec option, ColorScheme scheme) {
String shortOption = option.shortestName(); // assumes every option has a short option
String longOption = option.longestName(); // assumes every option has a short and a long option
if (option.negatable()) { // ok to omit if you don't have negatable options
INegatableOptionTransformer transformer =
option.command().negatableOptionTransformer();
shortOption = transformer.makeSynopsis(shortOption, option.command());
longOption = transformer.makeSynopsis(longOption, option.command());
}
// assume one line of description text (may contain embedded %n line separators)
String[] description = option.description();
Text[] descriptionFirstLines = scheme.text(description[0]).splitLines();
Text EMPTY = Ansi.OFF.text("");
List<Text[]> result = new ArrayList<Text[]>();
result.add(new Text[]{
scheme.optionText(String.valueOf(
option.command().usageMessage().requiredOptionMarker())),
scheme.optionText(shortOption),
scheme.text(","), // we assume every option has a short and a long name
scheme.optionText(longOption), // just the option name without parameter
descriptionFirstLines[0]});
for (int i = 1; i < descriptionFirstLines.length; i++) {
result.add(new Text[]{EMPTY, EMPTY, EMPTY, EMPTY, descriptionFirstLines[i]});
}
// if #Command(showDefaultValues = true) was set, append line with default value
if (option.command().usageMessage().showDefaultValues()) {
Text defaultValue = scheme.text(" Default: " + option.defaultValueString(true));
result.add(new Text[]{EMPTY, EMPTY, EMPTY, EMPTY, defaultValue});
}
return result.toArray(new Text[result.size()][]);
}
}
This shows the following usage help message:
Usage: <main class> [-p] [-o=<port>] [-u=<user>]
-o, --port Listening port, default is 12345.
-p, --password Password for the user.
-u, --user The connecting user name.
Note that the parameter label is omitted in the options list, but is still shown in the synopsis. If you do not want any parameter labels shown in the synopsis, you can specify a custom synopsis in the #Command annotation, see this section in the user manual.

Generate Parser for a File with JavaCC

I am a beginner with JavaCC,and i'm trying to generate a file Parser.
I have already been able to generate a successful parser interpenetrated a line that is entered on the keyboard.
Parser example when I enter the keyboard "First Name: William", I managed to display on the screen the name of the variable and the value.
Now I have a file .txt who contain a large number of names and their value, and I would like to successfully display them on the screen.
below is my .jj file that I have already written to generate a parser of a typed line
Now i want the same but for a file.
options
{
static = true;
}
PARSER_BEGIN(parser_name)
public class parser_name
{
public static void main(String args []) throws ParseException
{
System.out.println("Waiting for the Input:");
parser_name parser = new parser_name(System.in);
parser.Start();
}
}
PARSER_END(parser_name)
SKIP :
{
" "
| "\r"
| "\t"
| "\n"
}
TOKEN : { < DIGIT : (["0"-"9"])+ > }
TOKEN : { <VARIABLE: (["a"-"z", "A"-"Z"])+> }
TOKEN : { <VALUE: (~["\n",":"])+> }
TOKEN : { <ASSIGNMENT: ":"> }
void Start(): { Token t,t1,t2;}
{
t=<VARIABLE>
t1=<ASSIGNMENT>
t2=<VALUE>
{ System.out.println("The Variable is "+t.image+",and the Value is "+t2.image); }
}
I have already tried to replace the "System.in" at the parser constructor with an object of type File.And then read the file by line, but it did not work.
Pass a Reader to the parser's constructor.

Why does this fail?

Live example here.
type Activity = {
verb: string
}
type CommentActivity = {
verb: 'comment'
}
function doStuff (activity: Activity) {}
const commentActivity: CommentActivity = { verb: 'comment' }
const likeActivity: Activity = { verb: 'like' }
doStuff(likeActivity)
doStuff(commentActivity)
Fails with:
15: doStuff(commentActivity)
^ Cannot call `doStuff` with `commentActivity` bound to `activity` because string literal `comment` [1] is incompatible with string [2] in property `verb`.
References:
6: verb: 'comment' ^ [1]
2: verb: string ^ [2]
The error message is clear and I know how to work around this, but I don't understand why a string literal isn't considered a valid string?
This is an issue of property variance. If you have a function like doStuff with the type
(activity: Activity): void => {}
then it is perfectly valid for the function do to
function doStuff (activity: Activity) {
activity.verb = "some new verb";
}
and that 100% typechecks. What that means is that if
doStuff(commentActivity)
were allowed, doStuff would actually change the type of commentActivity, which is why this is throwing an error for you.
What you need to do is tell Flow that you will not be changing the value of .verb, essentially making it read-only inside of doStuff. To do this, you put a + before the name of the property.
type Activity = {
+verb: string
};
(On Flow/try)

How do I fetch CSS Coverage data using chrome dev protocol?

I am working on creating a simple java class which would give me used & unused css on any given page.
public class coverage {
static String str;
public static void main(String[] args) throws JSONException {
String url = "https://www.amazon.com";
Launcher launcher = new Launcher();
try (SessionFactory factory = launcher.launch();
Session session = factory.create()) {
Command command = session.getCommand();
DOM dom = command.getDOM();
CSS css = command.getCSS();
session.navigate(url);
dom.enable();
css.enable();
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
HashMap<String, String> hmUsedCSS = new HashMap<String, String>();
css.startRuleUsageTracking();
List<RuleUsage> list = css.stopRuleUsageTracking();
for (RuleUsage coverage : list) {
if (!hm.containsKey(coverage.getStyleSheetId())) {
hm.put(coverage.getStyleSheetId(),
css.collectClassNames(coverage.getStyleSheetId()));
}
if (!coverage.isUsed()) {
String existingContent = hmUsedCSS.get(coverage
.getStyleSheetId());
String extraContent = css.getStyleSheetText(coverage
.getStyleSheetId());
hmUsedCSS.put(coverage.getStyleSheetId(),
existingContent == null ? extraContent
: existingContent + extraContent);
}
}
for (String name : hm.keySet()) {
List<String> value = hm.get(name);
System.out.println("Total " + name + "=>" + value);
}
for (String name : hmUsedCSS.keySet()) {
List<String> value = hm.get(name);
System.out.println("Used CSS " + name + "=>" + value);
}
}
}
}
As per official documentation, 'stopRuleUsageTracking' would tell us whether a particular CSS is being used or not by setting 'used' boolean in RuleUsage , but it is returning all the CSS available on the page with 'used' set to true.I figured out that the answer lies in startoffset & endoffset values as they tell us the positioning of used CSS.But I don't know how to convert these values into meaningful result of Used & Unused CSS ? Can someone help me out here?
As I pointed out in the question , the key was to fetch coverage data as per start & end offset values.I was able to write logic to do the same & got the required list of used & Unused CSS.

Converting Map to Java Bean, some properties cannot be set rightly

// I use this simple program:
public static Object convertToBean(Class type, Map map) {
BeanInfo beanInfo;
Object obj = null;
try {
beanInfo = Introspector.getBeanInfo(type);
obj = type.newInstance();
// When I debugging to here, I found that some properties is different from the variable the Object own. PropertyDescriptor changes charactor case when the variable is not in "String" type.
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : propertyDescriptors) {
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
}
}
} catch (Exception ignored) {
}
return obj;
}
//Using BeanMap is the same question.
Finally I found the root cause.
The problem solved by changing “A01” to "a01".
The variable name must be strict camel rule. First character must be lower case, except first two characters are all in upper case, like "AD".
Because the setter and getter methods will generate in same pattern. so It'll be difficult to recognize the real name of one variable.

Resources