wpilog-parser 3.1.1 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4 @@
1
1
  import { defineDiagnostics } from "nostics";
2
- import { CstParser, Lexer, createToken } from "chevrotain";
3
2
  // src/byte-offset.ts
4
3
  var ByteOffset = class {
5
4
  offset;
@@ -29,10 +28,6 @@ var ByteOffset = class {
29
28
  // src/diagnostics.ts
30
29
  /** Stable codes for errors callers can act on. */
31
30
  const diagnostics = defineDiagnostics({ codes: {
32
- WPILOG_C0001: {
33
- why: (p) => `Unknown command \`${p.command}\``,
34
- fix: "Run `wpilog --help` to see the available commands."
35
- },
36
31
  WPILOG_C0002: {
37
32
  why: "Output flags cannot be combined",
38
33
  fix: "Choose one of --json, --jsonl, --ndjson, or --csv."
@@ -603,158 +598,11 @@ function compileStruct(registry, name) {
603
598
  ${sources.join("\n")}
604
599
  return ${root};`)(new TextDecoder());
605
600
  }
606
- // src/struct/lexer.ts
607
- const Comma = createToken({
608
- name: "Comma",
609
- pattern: ","
610
- });
611
- const Semicolon = createToken({
612
- name: "Semicolon",
613
- pattern: ";"
614
- });
615
- const Colon = createToken({
616
- name: "Colon",
617
- pattern: ":"
618
- });
619
- const Equals = createToken({
620
- name: "Equals",
621
- pattern: "="
622
- });
623
- const WhiteSpace = createToken({
624
- name: "WhiteSpace",
625
- pattern: /\s+/
626
- });
627
- const Integer = createToken({
628
- name: "Integer",
629
- pattern: /0|[1-9]\d*/
630
- });
631
- const LeftSquareBrace = createToken({
632
- name: "LeftSquareBrace",
633
- pattern: "["
634
- });
635
- const RightSquareBrace = createToken({
636
- name: "RightSquareBrace",
637
- pattern: "]"
638
- });
639
- const EnumKeyword = createToken({
640
- name: "EnumKeyword",
641
- pattern: "enum"
642
- });
643
- const LeftCurlyBrace = createToken({
644
- name: "LeftCurlyBrace",
645
- pattern: "{"
646
- });
647
- const RightCurlyBrace = createToken({
648
- name: "RightCurlyBrace",
649
- pattern: "}"
650
- });
651
- const Identifier = createToken({
652
- name: "Identifier",
653
- pattern: /\w+/
654
- });
655
- const allTokens = [
656
- WhiteSpace,
657
- Semicolon,
658
- Equals,
659
- Comma,
660
- Colon,
661
- Integer,
662
- LeftSquareBrace,
663
- RightSquareBrace,
664
- EnumKeyword,
665
- LeftCurlyBrace,
666
- RightCurlyBrace,
667
- Identifier
668
- ];
669
- const lexer = new Lexer(allTokens);
670
- // src/struct/parser.ts
671
- var StructParser = class extends CstParser {
672
- structSpecification = this.RULE("structSpecification", () => {
673
- this.MANY_SEP({
674
- SEP: Semicolon,
675
- DEF: () => this.OPTION(() => this.SUBRULE(this.declaration))
676
- });
677
- });
678
- declaration = this.RULE("declaration", () => {
679
- this.OPTION(() => this.SUBRULE(this.enumSpecification));
680
- this.SUBRULE(this.optionalWhitespace);
681
- this.CONSUME(Identifier);
682
- this.SUBRULE1(this.optionalWhitespace);
683
- this.CONSUME1(Identifier);
684
- this.OPTION1(() => this.OR({ DEF: [{ ALT: () => this.SUBRULE(this.bitFieldDeclaration) }, { ALT: () => this.SUBRULE(this.standardDeclarationArray) }] }));
685
- });
686
- standardDeclarationArray = this.RULE("standardDeclarationArray", () => {
687
- this.SUBRULE(this.optionalWhitespace);
688
- this.SUBRULE(this.arraySize);
689
- });
690
- bitFieldDeclaration = this.RULE("bitFieldDeclaration", () => {
691
- this.SUBRULE(this.optionalWhitespace);
692
- this.CONSUME(Colon);
693
- this.SUBRULE1(this.optionalWhitespace);
694
- this.CONSUME(Integer);
695
- });
696
- arraySize = this.RULE("arraySize", () => {
697
- this.CONSUME(LeftSquareBrace);
698
- this.SUBRULE(this.optionalWhitespace);
699
- this.CONSUME(Integer);
700
- this.SUBRULE1(this.optionalWhitespace);
701
- this.CONSUME(RightSquareBrace);
702
- });
703
- enumSpecification = this.RULE("enumSpecification", () => {
704
- this.OPTION(() => this.CONSUME(EnumKeyword));
705
- this.SUBRULE(this.optionalWhitespace);
706
- this.CONSUME(LeftCurlyBrace);
707
- this.MANY_SEP({
708
- SEP: Comma,
709
- DEF: () => this.SUBRULE(this.enumMember)
710
- });
711
- this.SUBRULE1(this.optionalWhitespace);
712
- this.CONSUME(RightCurlyBrace);
713
- });
714
- enumMember = this.RULE("enumMember", () => {
715
- this.SUBRULE(this.optionalWhitespace);
716
- this.CONSUME(Identifier);
717
- this.SUBRULE1(this.optionalWhitespace);
718
- this.CONSUME(Equals);
719
- this.SUBRULE2(this.optionalWhitespace);
720
- this.CONSUME(Integer);
721
- this.SUBRULE3(this.optionalWhitespace);
722
- });
723
- optionalWhitespace = this.RULE("optionalWhitespace", () => {
724
- this.OPTION(() => this.CONSUME(WhiteSpace));
725
- });
726
- constructor() {
727
- super(allTokens);
728
- this.performSelfAnalysis();
729
- }
730
- };
731
- const parser = new StructParser();
732
- parser.getBaseCstVisitorConstructor();
733
- const BaseStructVisitorWithDefaults = parser.getBaseCstVisitorConstructorWithDefaults();
734
- // src/struct/struct-ast-visitor.ts
735
- var StructAstVisitor = class extends BaseStructVisitorWithDefaults {
736
- constructor() {
737
- super();
738
- this.validateVisitor();
739
- }
740
- structSpecification(children) {
741
- return children.declaration?.map((declaration) => this.declaration(declaration.children)) ?? [];
742
- }
743
- declaration(children) {
744
- const [typeName, name] = children.Identifier;
745
- const enumSpecification = children.enumSpecification ? this.enumSpecification(children.enumSpecification[0].children, typeName.image) : void 0;
746
- const arraySize = children.standardDeclarationArray ? this.standardDeclarationArray(children.standardDeclarationArray[0].children) : void 0;
747
- const bitWidth = children.bitFieldDeclaration ? this.bitFieldDeclaration(children.bitFieldDeclaration[0].children, typeName.image) : void 0;
748
- return {
749
- name: name.image,
750
- value: typeName.image,
751
- enumSpecification,
752
- arraySize,
753
- bitWidth
754
- };
755
- }
756
- enumSpecification(children, dataType) {
757
- switch (dataType) {
601
+ // src/struct/validate-declarations.ts
602
+ function validateDeclarations(declarations) {
603
+ for (const declaration of declarations) {
604
+ const { value, enumSpecification, bitWidth } = declaration;
605
+ if (enumSpecification) switch (value) {
758
606
  case KnownStructTypeName.Int8:
759
607
  case KnownStructTypeName.Uint8:
760
608
  case KnownStructTypeName.Int16:
@@ -765,82 +613,156 @@ var StructAstVisitor = class extends BaseStructVisitorWithDefaults {
765
613
  case KnownStructTypeName.Uint64: break;
766
614
  default: throw diagnostics.WPILOG_R0009();
767
615
  }
768
- const entries = children.enumMember?.map((member) => this.enumMember(member.children));
769
- return new Map(entries);
616
+ if (bitWidth !== void 0) validateBitWidth(value, bitWidth);
770
617
  }
771
- enumMember(children) {
772
- const [name] = children.Identifier;
773
- const [value] = children.Integer;
774
- return [name.image, BigInt(value.image)];
618
+ return declarations;
619
+ }
620
+ function validateBitWidth(value, parsed) {
621
+ switch (value) {
622
+ case KnownStructTypeName.Boolean:
623
+ if (parsed !== 1) throw diagnostics.WPILOG_R0010({
624
+ type: value,
625
+ width: parsed,
626
+ maxBits: 1
627
+ });
628
+ break;
629
+ case KnownStructTypeName.Int8:
630
+ case KnownStructTypeName.Uint8:
631
+ if (parsed > 8) throw diagnostics.WPILOG_R0010({
632
+ type: value,
633
+ width: parsed,
634
+ maxBits: 8
635
+ });
636
+ break;
637
+ case KnownStructTypeName.Int16:
638
+ case KnownStructTypeName.Uint16:
639
+ if (parsed > 16) throw diagnostics.WPILOG_R0010({
640
+ type: value,
641
+ width: parsed,
642
+ maxBits: 16
643
+ });
644
+ break;
645
+ case KnownStructTypeName.Int32:
646
+ case KnownStructTypeName.Uint32:
647
+ if (parsed > 32) throw diagnostics.WPILOG_R0010({
648
+ type: value,
649
+ width: parsed,
650
+ maxBits: 32
651
+ });
652
+ break;
653
+ case KnownStructTypeName.Int64:
654
+ case KnownStructTypeName.Uint64:
655
+ if (parsed > 64) throw diagnostics.WPILOG_R0010({
656
+ type: value,
657
+ width: parsed,
658
+ maxBits: 64
659
+ });
660
+ break;
661
+ default: throw diagnostics.WPILOG_R0011();
775
662
  }
776
- bitFieldDeclaration(children, dataType) {
777
- const [value] = children.Integer;
778
- const parsed = Number(value.image);
779
- switch (dataType) {
780
- case KnownStructTypeName.Boolean:
781
- if (parsed !== 1) throw diagnostics.WPILOG_R0010({
782
- type: dataType,
783
- width: parsed,
784
- maxBits: 1
785
- });
786
- break;
787
- case KnownStructTypeName.Int8:
788
- case KnownStructTypeName.Uint8:
789
- if (parsed > 8) throw diagnostics.WPILOG_R0010({
790
- type: dataType,
791
- width: parsed,
792
- maxBits: 8
793
- });
794
- break;
795
- case KnownStructTypeName.Int16:
796
- case KnownStructTypeName.Uint16:
797
- if (parsed > 16) throw diagnostics.WPILOG_R0010({
798
- type: dataType,
799
- width: parsed,
800
- maxBits: 16
801
- });
802
- break;
803
- case KnownStructTypeName.Int32:
804
- case KnownStructTypeName.Uint32:
805
- if (parsed > 32) throw diagnostics.WPILOG_R0010({
806
- type: dataType,
807
- width: parsed,
808
- maxBits: 32
809
- });
810
- break;
811
- case KnownStructTypeName.Int64:
812
- case KnownStructTypeName.Uint64:
813
- if (parsed > 64) throw diagnostics.WPILOG_R0010({
814
- type: dataType,
815
- width: parsed,
816
- maxBits: 64
817
- });
818
- break;
819
- default: throw diagnostics.WPILOG_R0011();
663
+ }
664
+ // src/struct/parser.ts
665
+ const tokenPattern = /\s*([a-zA-Z_]\w*|\d+|[;,=:[\]{}])?/y;
666
+ const identifierStartPattern = /^[a-zA-Z_]/;
667
+ const integerStartPattern = /^\d/;
668
+ /** Parse a WPILib struct schema into field declarations. */
669
+ function parseStruct(source) {
670
+ return validateDeclarations(new SchemaParser(source).parse());
671
+ }
672
+ var SchemaParser = class {
673
+ source;
674
+ offset = 0;
675
+ token = "";
676
+ tokenOffset = 0;
677
+ constructor(source) {
678
+ this.source = source;
679
+ }
680
+ parse() {
681
+ const declarations = [];
682
+ this.advance();
683
+ while (this.token) {
684
+ if (this.at(";")) {
685
+ this.advance();
686
+ continue;
687
+ }
688
+ declarations.push(this.readDeclaration());
689
+ if (this.token) this.consume(";");
690
+ }
691
+ return declarations;
692
+ }
693
+ readDeclaration() {
694
+ const enumSpecification = this.at("enum") || this.at("{") ? this.readEnum() : void 0;
695
+ const value = this.readIdentifier();
696
+ const name = this.readIdentifier();
697
+ let arraySize;
698
+ let bitWidth;
699
+ if (this.at("[")) {
700
+ this.advance();
701
+ arraySize = Number(this.readInteger());
702
+ this.consume("]");
703
+ } else if (this.at(":")) {
704
+ this.advance();
705
+ bitWidth = Number(this.readInteger());
820
706
  }
821
- return parsed;
707
+ return {
708
+ name,
709
+ value,
710
+ enumSpecification,
711
+ arraySize,
712
+ bitWidth
713
+ };
714
+ }
715
+ readEnum() {
716
+ if (this.at("enum")) this.advance();
717
+ this.consume("{");
718
+ const members = /* @__PURE__ */ new Map();
719
+ if (!this.at("}")) while (true) {
720
+ const name = this.readIdentifier();
721
+ this.consume("=");
722
+ members.set(name, BigInt(this.readInteger()));
723
+ if (!this.at(",")) break;
724
+ this.advance();
725
+ }
726
+ this.consume("}");
727
+ return members;
728
+ }
729
+ readIdentifier() {
730
+ if (!identifierStartPattern.test(this.token)) this.fail("identifier");
731
+ const value = this.token;
732
+ this.advance();
733
+ return value;
734
+ }
735
+ readInteger() {
736
+ if (!integerStartPattern.test(this.token)) this.fail("integer");
737
+ const value = this.token;
738
+ this.advance();
739
+ return value;
740
+ }
741
+ at(expected) {
742
+ return this.token === expected;
743
+ }
744
+ consume(expected) {
745
+ if (!this.at(expected)) this.fail(JSON.stringify(expected));
746
+ this.advance();
822
747
  }
823
- standardDeclarationArray(children) {
824
- return this.arraySize(children.arraySize[0].children);
748
+ advance() {
749
+ tokenPattern.lastIndex = this.offset;
750
+ this.token = tokenPattern.exec(this.source)[1] ?? "";
751
+ this.offset = tokenPattern.lastIndex;
752
+ this.tokenOffset = this.offset - this.token.length;
753
+ if (!this.token && this.offset < this.source.length) throw diagnostics.WPILOG_R0007({ cause: new AggregateError([/* @__PURE__ */ new SyntaxError(`Invalid character at offset ${this.offset}`)]) });
825
754
  }
826
- arraySize(children) {
827
- const [value] = children.Integer;
828
- return Number(value.image);
755
+ fail(expected) {
756
+ throw diagnostics.WPILOG_R0008({ cause: new AggregateError([/* @__PURE__ */ new SyntaxError(`Expected ${expected} at offset ${this.tokenOffset}`)]) });
829
757
  }
830
758
  };
831
759
  // src/struct/parse-struct.ts
832
- const structAstVisitor = new StructAstVisitor();
833
760
  const cache = /* @__PURE__ */ new Map();
834
761
  /** Parse a WPILib struct specification string into declarations. */
835
762
  function parseStructSpecification(declaration) {
836
763
  const existing = cache.get(declaration);
837
764
  if (existing) return existing;
838
- const lexingResult = lexer.tokenize(declaration);
839
- if (lexingResult.errors.length > 0) throw diagnostics.WPILOG_R0007({ cause: new AggregateError(lexingResult.errors) });
840
- parser.input = lexingResult.tokens;
841
- const cstNode = parser.structSpecification();
842
- if (parser.errors.length > 0) throw diagnostics.WPILOG_R0008({ cause: new AggregateError(parser.errors) });
843
- const created = structAstVisitor.structSpecification(cstNode.children);
765
+ const created = parseStruct(declaration);
844
766
  cache.set(declaration, created);
845
767
  return created;
846
768
  }
package/dist/cli.mjs CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { o as readRecords, t as catalogEntries, u as diagnostics } from "./catalog-BmNQKX4c.mjs";
2
+ import { o as readRecords, t as catalogEntries, u as diagnostics } from "./catalog-BRtbeKXA.mjs";
3
3
  import { Diagnostic, formatDiagnostic } from "nostics";
4
- import tab from "@bomb.sh/tab/cac";
5
- import { cac } from "cac";
4
+ import { RootCommand, script } from "@bomb.sh/tab";
5
+ import { boolean, command, commandsInfo, positional, run } from "@drizzle-team/brocli";
6
6
  import oscStatus from "osc-status";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import { encode } from "@toon-format/toon";
9
9
  // package.json
10
- var version = "3.1.1";
10
+ var version = "3.1.2";
11
+ var description = "Read WPILib wpilog data log files in TypeScript & JavaScript";
11
12
  // src/cli/catalog.ts
12
13
  async function catalogFile(filePath) {
13
14
  let bytes;
@@ -57,42 +58,60 @@ function formatCatalog(entries, format = "toon") {
57
58
  }
58
59
  }
59
60
  // src/cli.ts
60
- const cli = cac("wpilog");
61
- cli.command("catalog <file>", "List the entries available in a WPILOG file").option("--json", "Output as JSON").option("--jsonl", "Output as newline-delimited JSON").option("--ndjson", "Output as newline-delimited JSON").option("--csv", "Output as CSV").example("wpilog catalog ./example.wpilog").example("wpilog catalog ./example.wpilog --json").action(async (file, options) => {
62
- const format = selectCatalogFormat(options);
63
- oscStatus.working({
64
- app: "wpilog",
65
- message: "Cataloging log"
66
- });
67
- const entries = await catalogFile(file);
68
- console.log(formatCatalog(entries, format));
69
- oscStatus.done({
70
- app: "wpilog",
71
- message: `Cataloged ${entries.length} entries`
72
- });
73
- });
74
- cli.help();
75
- cli.version(version);
76
- try {
77
- await tab(cli);
78
- const completeCommand = cli.commands.find((command) => command.name === "complete");
79
- if (completeCommand) {
80
- completeCommand.description = "Generate shell completion scripts";
81
- completeCommand.usage("complete <zsh|bash|fish|powershell>").example("source <(wpilog complete zsh)").example("source <(wpilog complete bash)").example("wpilog complete fish > ~/.config/fish/completions/wpilog.fish").example("wpilog complete powershell | Out-String | Invoke-Expression");
61
+ const completions = new RootCommand();
62
+ const commands = [command({
63
+ name: "catalog",
64
+ desc: "List the entries available in a WPILOG file",
65
+ options: {
66
+ file: positional().desc("WPILOG file to catalog").required(),
67
+ json: boolean().desc("Output as JSON"),
68
+ jsonl: boolean().desc("Output as newline-delimited JSON"),
69
+ ndjson: boolean().desc("Output as newline-delimited JSON"),
70
+ csv: boolean().desc("Output as CSV")
71
+ },
72
+ async handler(options) {
73
+ const format = selectCatalogFormat(options);
74
+ oscStatus.working({
75
+ app: "wpilog",
76
+ message: "Cataloging log"
77
+ });
78
+ const entries = await catalogFile(options.file);
79
+ console.log(formatCatalog(entries, format));
80
+ oscStatus.done({
81
+ app: "wpilog",
82
+ message: `Cataloged ${entries.length} entries`
83
+ });
82
84
  }
83
- const parsed = cli.parse(process.argv, { run: false });
84
- if (!cli.matchedCommand && !parsed.options.help && !parsed.options.version) {
85
- if (parsed.args[0]) throw diagnostics.WPILOG_C0001({ command: parsed.args[0] });
86
- cli.outputHelp();
85
+ }), command({
86
+ name: "complete",
87
+ desc: "Generate shell completion scripts",
88
+ options: { shell: positional().enum("zsh", "bash", "fish", "powershell").desc("Shell type") },
89
+ handler({ shell }) {
90
+ if (shell) script(shell, "wpilog", "wpilog");
91
+ else completions.parse([]);
87
92
  }
88
- await cli.runMatchedCommand();
89
- } catch (error) {
90
- const message = error instanceof Diagnostic ? formatDiagnostic(error) : error instanceof Error ? error.message : String(error);
91
- console.error(error instanceof Diagnostic ? message : `wpilog: ${message}`);
92
- process.exitCode = 1;
93
- oscStatus.error({
94
- app: "wpilog",
95
- message: "Command failed"
96
- });
93
+ })];
94
+ for (const info of Object.values(commandsInfo(commands))) {
95
+ const completion = completions.command(info.name, info.desc ?? "");
96
+ for (const option of Object.values(info.options ?? {})) if (option.type === "positional") completion.argument(option.name);
97
+ else completion.option(option.name.replace(/^-+/, ""), option.description ?? "");
97
98
  }
99
+ if (process.argv[2] === "complete" && process.argv[3] === "--") completions.parse(process.argv.slice(4));
100
+ else await run(commands, {
101
+ name: "wpilog",
102
+ description,
103
+ version,
104
+ theme(event) {
105
+ if (event.type !== "error") return false;
106
+ oscStatus.error({
107
+ app: "wpilog",
108
+ message: "Command failed"
109
+ });
110
+ if (event.violation === "unknown_error" && event.error instanceof Diagnostic) {
111
+ console.error(formatDiagnostic(event.error));
112
+ return true;
113
+ }
114
+ return false;
115
+ }
116
+ });
98
117
  export {};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { s as ControlRecordType, a as KnownStructTypeName, c as RecordType, t as catalogEntries, n as decodeRecords, l as isDataRecord, r as parseDataLog, i as parseStructSpecification, o as readRecords } from "./catalog-BmNQKX4c.mjs";
1
+ export { s as ControlRecordType, a as KnownStructTypeName, c as RecordType, t as catalogEntries, n as decodeRecords, l as isDataRecord, r as parseDataLog, i as parseStructSpecification, o as readRecords } from "./catalog-BRtbeKXA.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wpilog-parser",
3
- "version": "3.1.1",
3
+ "version": "3.1.2",
4
4
  "description": "Read WPILib wpilog data log files in TypeScript & JavaScript",
5
5
  "homepage": "https://github.com/jonahsnider/wpilog-parser#readme",
6
6
  "license": "MIT",
@@ -35,7 +35,6 @@
35
35
  "build": "vp pack",
36
36
  "check": "vp check",
37
37
  "dev": "vp pack --watch",
38
- "generate": "node ./src/struct/codegen.ts",
39
38
  "preapi:check": "vp run build",
40
39
  "preapi:update": "vp run build",
41
40
  "prepare": "vp config",
@@ -45,9 +44,8 @@
45
44
  },
46
45
  "dependencies": {
47
46
  "@bomb.sh/tab": "^0.0.22",
47
+ "@drizzle-team/brocli": "^0.12.1",
48
48
  "@toon-format/toon": "^4.1.1",
49
- "cac": "^7.0.0",
50
- "chevrotain": "^13.0.0",
51
49
  "nostics": "^1.3.0",
52
50
  "osc-status": "^1.0.0"
53
51
  },