Значительные исправления ПрочитатьJSON (fix #1373 и прочее)
Глобальный ПрочитатьJSON переделан практически полностью.
Обрабатываемые ситуации см. в тестах. Предыдущая версия падала на половине из них.
Изменения существенные, прошу review и тестирования.
Снова возник вопрос, поднятый в https://github.com/EvilBeaver/OneScript/issues/1253#issuecomment-1420588316 - про чтение нестандартного литерала undefined.
Предпочтительней было бы убрать.
Тесты на пустые значения в коммите https://github.com/EvilBeaver/OneScript/pull/1374/commits/595c6bd1588d1c413ca3acce53eb7fb3eb284f78 дают примеры ошибочных json, которые будут успешно читаться. Используемая библиотека не разделяет "пустое" значение и литерал undefined перед запятой, а наоборот - преобразует первое во второе.
@Mr-Rm давай добьем может? Что тут подвисло у нас?
Сейчас остановлено на таком:
- Комментарии и undefined считать расширениями (как уже считаются одинарные кавычки: они вне стандарта).
- Обработку пустых значений - пока игнорировать, иначе надо влезать внутрь библиотеки. После 15.04.
Обзор изменений
Обновление включает в себя улучшение работы с JSON в скриптовом движке: введение нового класса для чтения JSON, улучшение обработки структур и карт, а также усиленная обработка ошибок при разборе JSON.
Изменения
| Файлы | Описание изменений |
|---|---|
| GlobalJsonFunctions.cs, JSONReader.cs | Введение JsonReaderInternal, улучшение методов чтения JSON, усиленная обработка ошибок. |
| tests/global-json.os, test-json_reader.os | Добавление тестов для проверки новой функциональности и обработки ошибок. |
| tests/json/json-mock.json | Удаление некорректной пары ключ-значение. |
Возможно связанные проблемы
- EvilBeaver/OneScript#1373: Изменения в методах чтения JSON могут помочь в исключении комментариев из возвращаемых массивов JSON, что соответствует одной из целей этой проблемы.
Recent Review Details
Configuration used: CodeRabbit UI
Commits
Files that changed from the base of the PR and between 1ddd39a5883755b2415a77d51a2c05e7c12f5c61 and 0a6db868c3f6365464521931e0dbe57cfc24da67.Files selected for processing (5)
- src/ScriptEngine.HostedScript/Library/Json/GlobalJsonFunctions.cs (4 hunks)
- src/ScriptEngine.HostedScript/Library/Json/JSONReader.cs (12 hunks)
- tests/global-json.os (1 hunks)
- tests/json/json-mock.json (2 hunks)
- tests/json/test-json_reader.os (3 hunks)
Files not reviewed due to errors (1)
- GlobalJsonFunctions.cs (no review received)
Additional comments not posted (7)
tests/json/json-mock.json (1)
1-1: Удаление пары ключ-значение"Неопределено": undefinedсоответствует целям PR по обработкеundefinedкак ошибки.tests/json/test-json_reader.os (3)
20-20: Добавление нового тестаТест_ДолженВызватьОшибку_ДляUndefinedдля проверки обработки неопределенных значений соответствует целям PR.
62-62: Обновление значения хеш-суммы в тестеТест_Должен_СверитьХешСуммуРезультатаПарсингаJSONсоответствует изменениям в данных JSON, используемых для тестирования.
136-146: ПроцедураТест_ДолженВызватьОшибку_ДляUndefinedкорректно реализована для проверки сценария с неопределенным значением, что соответствует целям PR.src/ScriptEngine.HostedScript/Library/Json/JSONReader.cs (2)
15-28: Реализация нового внутреннего классаJsonReaderInternal, производного отJsonTextReader, корректно обрабатывает неожиданные символы, что улучшает обработку JSON.
182-238: > :memo: NOTEThis review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [39-343]
Изменения в классе
JSONReader, включая использованиеJsonReaderInternalи добавление методов валидации, соответствуют целям PR по улучшению обработки JSON.tests/global-json.os (1)
1-362: Добавление новых тестов и обновление существующих в файлеglobal-json.osкорректно реализованы для проверки улучшенной функциональности чтения JSON.
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?
Tips
Chat
There are 3 ways to chat with CodeRabbit:
- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
-
I pushed a fix in commit <commit_id>. -
Generate unit testing code for this file. -
Open a follow-up GitHub issue for this discussion.
-
- Files and specific lines of code (under the "Files changed" tab): Tag
@coderabbitaiin a new review comment at the desired location with your query. Examples:-
@coderabbitai generate unit testing code for this file. -
@coderabbitai modularize this function.
-
- PR comments: Tag
@coderabbitaiin a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:-
@coderabbitai generate interesting stats about this repository and render them as a table. -
@coderabbitai show all the console.log statements in this repository. -
@coderabbitai read src/utils.ts and generate unit testing code. -
@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
-
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.
CodeRabbit Commands (invoked as PR comments)
-
@coderabbitai pauseto pause the reviews on a PR. -
@coderabbitai resumeto resume the paused reviews. -
@coderabbitai reviewto trigger a review. This is useful when automatic reviews are disabled for the repository. -
@coderabbitai resolveresolve all the CodeRabbit review comments. -
@coderabbitai helpto get help.
Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
CodeRabbit Configration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile to the root of your repository. - Please see the configuration documentation for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation:
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
Documentation and Community
- Visit our Documentation for detailed information on how to use CodeRabbit.
- Join our Discord Community to get help, request features, and share feedback.
- Follow us on X/Twitter for updates and announcements.
Итак, пустые значения - считать ошибкой.
Литерал undefined - также считать ошибкой, поскольку
- 1С так же считает это ошибкой
-
undefinedне входит в стандарт JSON - библиотека Newtonsoft.Json не позволяет отделить
undefinedот пустых значений
Неправильно работает ЧтениеJSON.Пропустить(). Но это, наверное, в отдельный PR.
@coderabbitai review
Неправильно работает
ЧтениеJSON.Пропустить(). Но это, наверное, в отдельный PR.
Давай тогда issue на это сформулируем, чтобы не забыть?