Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String values don't properly handle unicode escapes #58

Open
SteveKommrusch opened this issue Oct 31, 2018 · 2 comments · May be fixed by #96
Open

String values don't properly handle unicode escapes #58

SteveKommrusch opened this issue Oct 31, 2018 · 2 comments · May be fixed by #96

Comments

@SteveKommrusch
Copy link

I am using javalang to tokenize files which include Unicode escape sequences. These are correctly tokenized as strings, but the item.value is not handled cleanly. Consider the 2 cases below:
Case 1: builder.append(text, 0, MAX_TEXT).append('\u2026');
Case 2: builder.append(text, 0, MAX_TEXT).append('…');

In both cases, item.value is identical and I get an exception if I try to write the item.value to a file. I can catch the error and successfully print using python like this:

      if (token_type == 'String'):
          try:
              outfile.write(item.value)
          except UnicodeEncodeError:
              outfile.write(item.value.encode('unicode-escape').decode('utf-8'))

but the python code above prints the same value for Case 1 and 2. I suspect the proper fix is to use raw strings for String token values internal to javalang. Below is an example of raw strings solving the problem.

>>> str1 = '…'
>>> str2 = '\u2026'
>>> print("str1: ",str1," str2:",str2)
str1:  …  str2: …
>>> str1 == str2
True
>>> str1 = r'…'
>>> str2 = r'\u2026'
>>> print("str1: ",str1," str2:",str2)
str1:  …  str2: \u2026
>>> str1 == str2
False
@chenzimin
Copy link

chenzimin commented Feb 6, 2019

Hi Steve,

If you change the code at line 534 in tokenizer.py to:

#self.pre_tokenize()
self.data = ''.join(self.decode_data())
self.length = len(self.data)

The unicode string will be stored as raw string, not converted to characters.

And one more benefit is that the position will also be correct for files containing unicode. I found this when I tried to debug the position error.

@SteveKommrusch
Copy link
Author

SteveKommrusch commented Feb 7, 2019 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants