@danielx/civet 0.6.82 → 0.6.83

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.
Files changed (5) hide show
  1. package/dist/browser.js +1726 -1599
  2. package/dist/civet +0 -0
  3. package/dist/main.js +1726 -1599
  4. package/dist/main.mjs +1726 -1599
  5. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -270,27 +270,25 @@ function makeLeftHandSideExpression(expression) {
270
270
  return expression;
271
271
  }
272
272
  switch (expression.type) {
273
- case "Ref":
274
273
  case "AmpersandRef":
274
+ case "CallExpression":
275
275
  case "Identifier":
276
+ case "JSXElement":
277
+ case "JSXFragment":
276
278
  case "Literal":
277
- case "IterationExpression":
278
- case "CallExpression":
279
279
  case "MemberExpression":
280
280
  case "NewExpression":
281
281
  case "ParenthesizedExpression":
282
- case "IfExpression":
283
- case "DebuggerExpression":
284
- case "SwitchExpression":
285
- case "ThrowExpression":
286
- case "TryExpression":
282
+ case "Ref":
283
+ case "StatementExpression":
287
284
  return expression;
288
285
  }
289
286
  return makeNode({
290
287
  type: "ParenthesizedExpression",
291
288
  children: ["(", expression, ")"],
292
289
  expression,
293
- implicit: true
290
+ implicit: true,
291
+ parent: void 0
294
292
  });
295
293
  }
296
294
  function updateParentPointers(node, parent, depth = 1) {
@@ -405,7 +403,9 @@ function wrapIIFE(expressions, async) {
405
403
  type: "BlockStatement",
406
404
  expressions,
407
405
  children: ["{", expressions, "}"],
408
- bare: false
406
+ bare: false,
407
+ root: false,
408
+ parent: void 0
409
409
  });
410
410
  const parameters = {
411
411
  type: "Parameters",
@@ -444,11 +444,18 @@ function wrapWithReturn(expression) {
444
444
  children
445
445
  });
446
446
  }
447
- var typeNeedsNoParens;
447
+ var assert, typeNeedsNoParens;
448
448
  var init_util = __esm({
449
449
  "source/parser/util.civet"() {
450
450
  "use strict";
451
451
  init_traversal();
452
+ assert = {
453
+ equal(a, b, msg) {
454
+ if (a !== b) {
455
+ throw new Error(`Assertion failed [${msg}]: ${a} !== ${b}`);
456
+ }
457
+ }
458
+ };
452
459
  typeNeedsNoParens = /* @__PURE__ */ new Set([
453
460
  "IdentifierType",
454
461
  "ImportType",
@@ -608,6 +615,17 @@ function makeEmptyBlock() {
608
615
  empty: true
609
616
  };
610
617
  }
618
+ function makeBlockFragment() {
619
+ const expressions = [];
620
+ return {
621
+ type: "BlockStatement",
622
+ children: expressions,
623
+ parent: void 0,
624
+ expressions,
625
+ bare: false,
626
+ root: false
627
+ };
628
+ }
611
629
  function replaceBlockExpression(node, child, replacement) {
612
630
  let found = false;
613
631
  const { expressions } = node;
@@ -739,523 +757,800 @@ var init_block = __esm({
739
757
  }
740
758
  });
741
759
 
742
- // source/parser/pipe.civet
743
- function constructInvocation(fn, arg) {
744
- const fnArr = [fn.leadingComment, fn.expr, fn.trailingComment];
745
- let expr = fn.expr;
746
- while (expr.type === "ParenthesizedExpression") {
747
- expr = expr.expression;
748
- }
749
- if (expr.ampersandBlock) {
750
- const { ref, body } = expr;
751
- ref.type = "PipedExpression";
752
- ref.children = [makeLeftHandSideExpression(arg)];
753
- updateParentPointers(ref);
754
- return makeNode({
755
- type: "UnwrappedExpression",
756
- children: [skipIfOnlyWS(fn.leadingComment), body, skipIfOnlyWS(fn.trailingComment)]
757
- });
758
- }
759
- expr = fn.expr;
760
- const lhs = makeLeftHandSideExpression(expr);
761
- let comment = skipIfOnlyWS(fn.trailingComment);
762
- if (comment)
763
- lhs.children.splice(2, 0, comment);
764
- comment = skipIfOnlyWS(fn.leadingComment);
765
- if (comment)
766
- lhs.children.splice(1, 0, comment);
767
- switch (arg.type) {
768
- case "CommaExpression":
769
- arg = makeLeftHandSideExpression(arg);
770
- break;
760
+ // source/parser/binding.civet
761
+ function adjustAtBindings(statements, asThis = false) {
762
+ gatherRecursiveAll(statements, (n) => n.type === "AtBindingProperty").forEach((binding) => {
763
+ const { ref } = binding;
764
+ if (asThis) {
765
+ const atBinding = binding.binding;
766
+ atBinding.children.pop();
767
+ atBinding.type = void 0;
768
+ binding.children.unshift(ref.id, ": this.", ref.base);
769
+ binding.type = "Property";
770
+ binding.ref = void 0;
771
+ return;
772
+ }
773
+ if (ref.names[0] !== ref.base) {
774
+ return binding.children.unshift(ref.base, ": ");
775
+ }
776
+ ;
777
+ return;
778
+ });
779
+ }
780
+ function adjustBindingElements(elements) {
781
+ const names = elements.flatMap((p) => p.names || []), { length } = elements;
782
+ let blockPrefix, restIndex = -1, restCount = 0;
783
+ elements.forEach(({ type }, i) => {
784
+ if (type === "BindingRestElement") {
785
+ if (restIndex < 0)
786
+ restIndex = i;
787
+ return restCount++;
788
+ }
789
+ ;
790
+ return;
791
+ });
792
+ if (restCount === 0) {
793
+ return {
794
+ children: elements,
795
+ names,
796
+ blockPrefix,
797
+ length
798
+ };
799
+ } else if (restCount === 1) {
800
+ const rest = elements[restIndex];
801
+ const after = elements.slice(restIndex + 1);
802
+ const restIdentifier = rest.binding.ref || rest.binding;
803
+ names.push(...rest.names || []);
804
+ let l = after.length;
805
+ if (l) {
806
+ if (arrayElementHasTrailingComma(after[l - 1]))
807
+ l++;
808
+ blockPrefix = {
809
+ type: "PostRestBindingElements",
810
+ children: ["[", insertTrimmingSpace(after, ""), "] = ", restIdentifier, ".splice(-", l.toString(), ")"],
811
+ names: after.flatMap((p) => p.names)
812
+ };
813
+ }
814
+ return {
815
+ names,
816
+ children: [...elements.slice(0, restIndex), {
817
+ ...rest,
818
+ children: rest.children.slice(0, -1)
819
+ // remove trailing comma
820
+ }],
821
+ blockPrefix,
822
+ length
823
+ };
771
824
  }
825
+ const err = {
826
+ type: "Error",
827
+ children: ["Multiple rest elements in array pattern"]
828
+ };
772
829
  return {
773
- type: "CallExpression",
774
- children: [lhs, "(", arg, ")"]
830
+ names,
831
+ children: [...elements, err],
832
+ blockPrefix,
833
+ length
775
834
  };
776
835
  }
777
- function constructPipeStep(fn, arg, returning) {
778
- const children = [[fn.leadingComment, fn.expr, fn.trailingComment].map(skipIfOnlyWS), " ", arg];
779
- switch (fn.expr.token) {
780
- case "yield":
781
- case "await":
782
- if (returning) {
783
- return [
784
- children,
785
- returning
786
- ];
836
+ function gatherBindingCode(statements, opts) {
837
+ const thisAssignments = [];
838
+ const splices = [];
839
+ function insertRestSplices(s, p, thisAssignments2) {
840
+ gatherRecursiveAll(s, (n) => n.blockPrefix || opts?.injectParamProps && n.accessModifier || n.type === "AtBinding").forEach((n) => {
841
+ if (n.type === "AtBinding") {
842
+ const { ref } = n;
843
+ const { id } = ref;
844
+ thisAssignments2.push([`this.${id} = `, ref]);
845
+ return;
787
846
  }
788
- return [
789
- children,
790
- null
791
- ];
792
- case "return":
793
- return [{
794
- type: "ReturnStatement",
795
- children
796
- }, null];
847
+ if (opts?.injectParamProps && n.type === "Parameter" && n.accessModifier) {
848
+ n.names.forEach((id) => ({
849
+ push: thisAssignments2.push({
850
+ type: "AssignmentExpression",
851
+ children: [`this.${id} = `, id],
852
+ js: true
853
+ })
854
+ }));
855
+ return;
856
+ }
857
+ const { blockPrefix } = n;
858
+ p.push(blockPrefix);
859
+ return insertRestSplices(blockPrefix, p, thisAssignments2);
860
+ });
797
861
  }
798
- if (returning) {
799
- return [
800
- constructInvocation(fn, arg),
801
- returning
802
- ];
862
+ insertRestSplices(statements, splices, thisAssignments);
863
+ return [splices, thisAssignments];
864
+ }
865
+ function arrayElementHasTrailingComma(elementNode) {
866
+ const lastChild = elementNode.children.at(-1);
867
+ return lastChild && lastChild[lastChild.length - 1]?.token === ",";
868
+ }
869
+ var init_binding = __esm({
870
+ "source/parser/binding.civet"() {
871
+ "use strict";
872
+ init_traversal();
873
+ init_util();
874
+ }
875
+ });
876
+
877
+ // source/parser/op.civet
878
+ function getPrecedence(op) {
879
+ if (typeof op === "string") {
880
+ return precedenceMap.get(op) ?? (() => {
881
+ throw new Error(`Unknown operator: ${op}`);
882
+ })();
883
+ } else if (typeof op.prec === "number") {
884
+ return op.prec;
885
+ } else {
886
+ return precedenceMap.get(op.prec ?? op.token) ?? (op.relational ? precedenceRelational : precedenceCustomDefault);
803
887
  }
804
- return [constructInvocation(fn, arg), null];
805
888
  }
806
- function processPipelineExpressions(statements) {
807
- gatherRecursiveAll(statements, (n) => n.type === "PipelineExpression").forEach((s) => {
808
- const [ws, , body] = s.children;
809
- let [, arg] = s.children;
810
- let i = 0, l = body.length;
811
- const children = [ws];
812
- let usingRef = null;
813
- for (i = 0; i < l; i++) {
814
- const step = body[i];
815
- const [leadingComment, pipe, trailingComment, expr] = step;
816
- const returns = pipe.token === "||>";
817
- let ref, result, returning = returns ? arg : null;
818
- if (pipe.token === "|>=") {
819
- let initRef;
820
- if (i === 0) {
821
- outer:
822
- switch (arg.type) {
823
- case "MemberExpression":
824
- if (arg.children.length <= 2)
825
- break;
826
- case "CallExpression":
827
- const access = arg.children.pop();
828
- switch (access.type) {
829
- case "PropertyAccess":
830
- case "SliceExpression":
831
- break;
832
- default:
833
- children.unshift({
834
- type: "Error",
835
- $loc: pipe.token.$loc,
836
- message: `Can't assign to ${access.type}`
837
- });
838
- arg.children.push(access);
839
- break outer;
840
- }
841
- usingRef = makeRef();
842
- initRef = {
843
- type: "AssignmentExpression",
844
- children: [usingRef, " = ", arg, ","]
845
- };
846
- arg = {
847
- type: "MemberExpression",
848
- children: [usingRef, access]
849
- };
850
- break;
889
+ function processBinaryOpExpression($0) {
890
+ return recurse(expandChainedComparisons($0));
891
+ function recurse(expandedOps) {
892
+ let i = 2;
893
+ while (i < expandedOps.length) {
894
+ let op = expandedOps[i];
895
+ if (op.special) {
896
+ let advanceLeft2 = function(allowEqual) {
897
+ while (start >= 4) {
898
+ const prevPrec = getPrecedence(expandedOps[start - 2]);
899
+ if (!(prevPrec > prec || allowEqual && prevPrec === prec)) {
900
+ return prevPrec === prec;
851
901
  }
852
- const lhs = [[
853
- [initRef],
854
- arg,
855
- [],
856
- { token: "=", children: [" = "] }
857
- ]];
858
- Object.assign(s, {
859
- type: "AssignmentExpression",
860
- children: [lhs, children],
861
- names: null,
862
- lhs,
863
- assigned: arg,
864
- exp: children
865
- });
866
- arg = clone(arg);
867
- if (arg.children[0].type === "Ref") {
868
- arg.children[0] = usingRef;
902
+ start -= 4;
903
+ }
904
+ return false;
905
+ }, advanceRight2 = function(allowEqual) {
906
+ while (end + 4 < expandedOps.length) {
907
+ const nextPrec = getPrecedence(expandedOps[end + 2]);
908
+ if (!(nextPrec > prec || allowEqual && nextPrec === prec)) {
909
+ return nextPrec === prec;
910
+ }
911
+ end += 4;
912
+ }
913
+ return false;
914
+ };
915
+ var advanceLeft = advanceLeft2, advanceRight = advanceRight2;
916
+ let start = i - 2, end = i + 2;
917
+ const prec = getPrecedence(op);
918
+ let error;
919
+ switch (op.assoc) {
920
+ case "left":
921
+ case void 0: {
922
+ advanceLeft2(true);
923
+ advanceRight2(false);
924
+ break;
925
+ }
926
+ case "right": {
927
+ advanceLeft2(false);
928
+ advanceRight2(true);
929
+ break;
930
+ }
931
+ case "non": {
932
+ if (advanceLeft2(false) || advanceRight2(false)) {
933
+ error = {
934
+ type: "Error",
935
+ message: `non-associative operator ${op.token} used at same precedence level without parenthesization`
936
+ };
937
+ }
938
+ ;
939
+ break;
940
+ }
941
+ case "arguments": {
942
+ if (advanceLeft2(false)) {
943
+ error = {
944
+ type: "Error",
945
+ message: `arguments operator ${op.token} used at same precedence level as ${expandedOps[start - 2].token} to the left`
946
+ };
947
+ }
948
+ advanceRight2(true);
949
+ break;
950
+ }
951
+ default: {
952
+ throw new Error(`Unsupported associativity: ${op.assoc}`);
953
+ }
954
+ }
955
+ let a = start === i - 2 ? expandedOps[start] : expandedOps.slice(start, i - 1);
956
+ let wsOp = expandedOps[i - 1];
957
+ let wsB = expandedOps[i + 1];
958
+ let b = end === i + 2 ? expandedOps[i + 2] : expandedOps.slice(i + 2, end + 1);
959
+ if (op.assoc === "arguments") {
960
+ let i2 = 2;
961
+ while (i2 < b.length) {
962
+ if (prec === getPrecedence(b[i2])) {
963
+ if (!(b[i2].token === op.token)) {
964
+ error ??= {
965
+ type: "Error",
966
+ message: `arguments operator ${op.token} used at same precedence level as ${b[i2].token} to the right`
967
+ };
968
+ }
969
+ b[i2] = ",";
970
+ }
971
+ i2 += 4;
869
972
  }
870
973
  } else {
871
- children.unshift({
872
- type: "Error",
873
- $loc: pipe.token.$loc,
874
- message: "Can't use |>= in the middle of a pipeline"
875
- });
974
+ b = recurse(b);
876
975
  }
877
- } else {
878
- if (i === 0)
879
- s.children = children;
880
- }
881
- if (returns && (ref = needsRef(arg))) {
882
- usingRef = usingRef || ref;
883
- arg = {
884
- type: "ParenthesizedExpression",
885
- children: ["(", {
886
- type: "AssignmentExpression",
887
- children: [usingRef, " = ", arg]
888
- }, ")"]
889
- };
890
- returning = usingRef;
891
- }
892
- ;
893
- [result, returning] = constructPipeStep(
894
- {
895
- leadingComment: skipIfOnlyWS(leadingComment),
896
- trailingComment: skipIfOnlyWS(trailingComment),
897
- expr
898
- },
899
- arg,
900
- returning
901
- );
902
- if (result.type === "ReturnStatement") {
903
- if (i < l - 1) {
904
- result.children.push({
905
- type: "Error",
906
- message: "Can't continue a pipeline after returning"
907
- });
976
+ if (op.token === "instanceof" && b.type === "Literal" && b.children?.[0]?.type === "StringLiteral") {
977
+ a = ["typeof ", makeLeftHandSideExpression(a)];
978
+ if (op.negated) {
979
+ op = { ...op, token: "!==", negated: false };
980
+ } else {
981
+ op = { ...op, token: "===" };
982
+ }
908
983
  }
909
- arg = result;
910
- if (children[children.length - 1] === ",") {
911
- children.pop();
912
- children.push(";");
984
+ if (op.asConst) {
985
+ a = makeAsConst(a);
986
+ b = makeAsConst(b);
913
987
  }
914
- break;
915
- }
916
- if (returning) {
917
- arg = returning;
918
- children.push(result, ",");
988
+ let children;
989
+ if (op.call) {
990
+ wsOp = insertTrimmingSpace(wsOp, "");
991
+ if (op.reversed) {
992
+ wsB = insertTrimmingSpace(wsB, "");
993
+ children = [wsOp, op.call, "(", wsB, b, ", ", a, ")", op.suffix];
994
+ } else {
995
+ children = [wsOp, op.call, "(", a, ",", wsB, b, ")", op.suffix];
996
+ }
997
+ } else if (op.method) {
998
+ wsOp = insertTrimmingSpace(wsOp, "");
999
+ wsB = insertTrimmingSpace(wsB, "");
1000
+ if (op.reversed) {
1001
+ if (end !== i + 2)
1002
+ b = makeLeftHandSideExpression(b);
1003
+ b = dotNumericLiteral(b);
1004
+ children = [wsB, b, wsOp, ".", op.method, "(", a, ")"];
1005
+ } else {
1006
+ if (start !== i - 2 || a.type === "NumericLiteral") {
1007
+ a = makeLeftHandSideExpression(a);
1008
+ }
1009
+ a = dotNumericLiteral(a);
1010
+ children = [a, wsOp, ".", op.method, "(", wsB, b, ")"];
1011
+ }
1012
+ } else if (op.token) {
1013
+ children = [a, wsOp, op, wsB, b];
1014
+ if (op.negated)
1015
+ children = ["(", ...children, ")"];
1016
+ } else {
1017
+ throw new Error("Unknown operator: " + JSON.stringify(op));
1018
+ }
1019
+ if (op.negated)
1020
+ children.unshift("!");
1021
+ if (error != null) {
1022
+ children.push(error);
1023
+ }
1024
+ expandedOps.splice(start, end - start + 1, {
1025
+ children
1026
+ });
1027
+ i = start + 2;
919
1028
  } else {
920
- arg = result;
1029
+ i += 4;
921
1030
  }
922
1031
  }
923
- if (usingRef) {
924
- s.hoistDec = {
925
- type: "Declaration",
926
- children: ["let ", usingRef],
927
- names: []
928
- };
929
- }
930
- children.push(arg);
931
- if (!children.some(($) => $?.type === "ReturnStatement") && children.some(($1) => $1 === ",")) {
932
- const { parent } = s;
933
- const parenthesizedExpression = makeLeftHandSideExpression({ ...s });
934
- Object.assign(s, parenthesizedExpression, {
935
- parent,
936
- hoistDec: void 0
937
- });
938
- }
939
- return addParentPointers(s, s.parent);
940
- });
1032
+ return expandedOps;
1033
+ }
1034
+ ;
1035
+ return recurse;
941
1036
  }
942
- var init_pipe = __esm({
943
- "source/parser/pipe.civet"() {
944
- "use strict";
945
- init_traversal();
946
- init_util();
1037
+ function dotNumericLiteral(literal) {
1038
+ if (literal?.type === "Literal" && /^[+-]?(?:0|[1-9](?:_[0-9]|[0-9])*)$/.test(literal.raw)) {
1039
+ literal.children.push(".");
1040
+ literal.raw += ".";
947
1041
  }
948
- });
949
-
950
- // source/parser/for.civet
951
- function forRange(open, forDeclaration, range, stepExp, close) {
952
- const { start, end, inclusive } = range;
953
- const counterRef = makeRef("i");
954
- let stepRef;
955
- if (stepExp) {
956
- stepExp = insertTrimmingSpace(stepExp, "");
957
- stepRef = maybeRef(stepExp, "step");
1042
+ return literal;
1043
+ }
1044
+ function makeAsConst(node) {
1045
+ if (Array.isArray(node) && node.length === 1) {
1046
+ node = node[0];
958
1047
  }
959
- const startRef = maybeRef(start, "start");
960
- const endRef = maybeRef(end, "end");
961
- const startRefDec = startRef !== start ? [startRef, " = ", start, ", "] : [];
962
- const endRefDec = endRef !== end ? [endRef, " = ", end, ", "] : [];
963
- let ascDec = [], ascRef, asc;
964
- if (stepRef) {
965
- if (stepRef !== stepExp) {
966
- ascDec = [", ", stepRef, " = ", stepExp];
967
- }
968
- } else if (start.type === "Literal" && end.type === "Literal") {
969
- asc = literalValue(start) <= literalValue(end);
1048
+ if (node.type === "Literal" && node.raw !== "null" || node.type === "ArrayExpression" || node.type === "ObjectExpression") {
1049
+ return { ...node, children: [...node.children, asConst] };
970
1050
  } else {
971
- ascRef = makeRef("asc");
972
- ascDec = [", ", ascRef, " = ", startRef, " <= ", endRef];
1051
+ return node;
973
1052
  }
974
- let varAssign = [], varLetAssign = varAssign, varLet = varAssign, blockPrefix;
975
- if (forDeclaration?.declare) {
976
- if (forDeclaration.declare.token === "let") {
977
- const varName = forDeclaration.children.splice(1);
978
- varAssign = [...insertTrimmingSpace(varName, ""), " = "];
979
- varLet = [",", ...varName, " = ", counterRef];
980
- } else {
981
- blockPrefix = [
982
- ["", forDeclaration, " = ", counterRef, ";"]
983
- ];
984
- }
985
- } else if (forDeclaration) {
986
- varAssign = varLetAssign = [forDeclaration, " = "];
1053
+ }
1054
+ function isExistence(exp) {
1055
+ if (exp.type === "ParenthesizedExpression" && exp.implicit) {
1056
+ exp = exp.expression;
987
1057
  }
988
- const declaration = {
989
- type: "Declaration",
990
- children: ["let ", ...startRefDec, ...endRefDec, counterRef, " = ", ...varLetAssign, startRef, ...varLet, ...ascDec],
991
- names: forDeclaration?.names
992
- };
993
- const counterPart = inclusive ? [counterRef, " <= ", endRef, " : ", counterRef, " >= ", endRef] : [counterRef, " < ", endRef, " : ", counterRef, " > ", endRef];
994
- const condition = stepRef ? [stepRef, " !== 0 && (", stepRef, " > 0 ? ", ...counterPart, ")"] : ascRef ? [ascRef, " ? ", ...counterPart] : asc ? counterPart.slice(0, 3) : counterPart.slice(4);
995
- const increment = stepRef ? [...varAssign, counterRef, " += ", stepRef] : ascRef ? [...varAssign, ascRef, " ? ++", counterRef, " : --", counterRef] : [...varAssign, asc ? "++" : "--", counterRef];
996
- return {
997
- declaration,
998
- children: [open, declaration, "; ", ...condition, "; ", ...increment, close],
999
- blockPrefix
1000
- };
1058
+ if (exp.type === "Existence") {
1059
+ return exp;
1060
+ }
1061
+ ;
1062
+ return;
1001
1063
  }
1002
- function processForInOf($0, getRef) {
1003
- let [awaits, eachOwn, open, declaration, declaration2, ws, inOf, exp, step, close] = $0;
1004
- if (exp.type === "RangeExpression" && inOf.token === "of" && !declaration2) {
1005
- return forRange(open, declaration, exp, step, close);
1006
- } else if (step) {
1007
- throw new Error("for..of/in cannot use 'by' except with range literals");
1064
+ function isRelationalOp(op) {
1065
+ return op.relational || getPrecedence(op) === precedenceRelational;
1066
+ }
1067
+ function expandChainedComparisons([first, binops]) {
1068
+ const results = [];
1069
+ let i = 0;
1070
+ const l = binops.length;
1071
+ let start = 0;
1072
+ let chains = [];
1073
+ let op;
1074
+ while (i < l) {
1075
+ [, op] = binops[i];
1076
+ if (isRelationalOp(op)) {
1077
+ chains.push(i);
1078
+ } else if (getPrecedence(op) < precedenceRelational) {
1079
+ processChains(op);
1080
+ first = void 0;
1081
+ }
1082
+ i++;
1008
1083
  }
1009
- let eachOwnError;
1010
- let hoistDec, blockPrefix = [];
1011
- if (eachOwn && eachOwn[0].token === "each") {
1012
- if (inOf.token === "of") {
1013
- const counterRef = makeRef("i");
1014
- const lenRef = makeRef("len");
1015
- const expRef2 = maybeRef(exp);
1016
- const increment = "++";
1017
- let assignmentNames = [...declaration.names];
1018
- if (declaration2) {
1019
- const [, , ws22, decl22] = declaration2;
1020
- blockPrefix.push(["", [
1021
- insertTrimmingSpace(ws22, ""),
1022
- decl22,
1023
- " = ",
1024
- counterRef
1025
- ], ";"]);
1026
- assignmentNames.push(...decl22.names);
1027
- }
1028
- const expRefDec = expRef2 !== exp ? [insertTrimmingSpace(expRef2, " "), " = ", insertTrimmingSpace(exp, ""), ", "] : [];
1029
- blockPrefix.push(["", {
1030
- type: "Declaration",
1031
- children: [declaration, " = ", insertTrimmingSpace(expRef2, ""), "[", counterRef, "]"],
1032
- names: assignmentNames
1033
- }, ";"]);
1034
- declaration = {
1035
- type: "Declaration",
1036
- children: ["let ", ...expRefDec, counterRef, " = 0, ", lenRef, " = ", insertTrimmingSpace(expRef2, ""), ".length"],
1037
- names: []
1038
- };
1039
- const condition = [counterRef, " < ", lenRef, "; "];
1040
- const children = [open, declaration, "; ", condition, counterRef, increment, close];
1041
- return { declaration, children, blockPrefix };
1084
+ if (op != null) {
1085
+ processChains(op);
1086
+ }
1087
+ return results;
1088
+ function processChains(op2) {
1089
+ if (first && isRelationalOp(op2)) {
1090
+ first = expandExistence(first);
1091
+ }
1092
+ if (chains.length > 1) {
1093
+ chains.forEach((index, k) => {
1094
+ if (k > 0) {
1095
+ results.push(" ", "&&", " ");
1096
+ }
1097
+ const binop = binops[index];
1098
+ let [, , , exp] = binop;
1099
+ exp = binop[3] = expandExistence(exp);
1100
+ let endIndex;
1101
+ if (k < chains.length - 1) {
1102
+ endIndex = chains[k + 1];
1103
+ } else {
1104
+ endIndex = i + 1;
1105
+ }
1106
+ results.push(first, ...binops.slice(start, endIndex).flat());
1107
+ first = [exp].concat(binops.slice(index + 1, endIndex));
1108
+ return start = endIndex;
1109
+ });
1042
1110
  } else {
1043
- eachOwnError = {
1044
- type: "Error",
1045
- message: "'each' is only meaningful in for..of loops"
1046
- };
1111
+ if (first) {
1112
+ results.push(first);
1113
+ }
1114
+ results.push(...binops.slice(start, i + 1).flat());
1115
+ start = i + 1;
1047
1116
  }
1117
+ chains.length = 0;
1048
1118
  }
1049
- let own = eachOwn && eachOwn[0].token === "own";
1050
- let expRef;
1051
- if (own && inOf.token !== "in") {
1052
- own = false;
1053
- eachOwnError = {
1054
- type: "Error",
1055
- message: "'own' is only meaningful in for..in loops"
1056
- };
1119
+ function expandExistence(exp) {
1120
+ const existence = isExistence(exp);
1121
+ if (existence) {
1122
+ results.push(existence, " ", "&&", " ");
1123
+ return existence.expression;
1124
+ }
1125
+ return exp;
1057
1126
  }
1058
- if (!declaration2 && !own) {
1059
- return {
1060
- declaration,
1061
- blockPrefix,
1062
- children: [awaits, eachOwnError, open, declaration, ws, inOf, expRef ?? exp, step, close]
1063
- // omit declaration2, replace eachOwn with eachOwnError, replace exp with expRef
1127
+ ;
1128
+ }
1129
+ var precedenceOrder, precedenceMap, precedenceStep, precedenceRelational, precedenceCustomDefault, asConst;
1130
+ var init_op = __esm({
1131
+ "source/parser/op.civet"() {
1132
+ "use strict";
1133
+ init_util();
1134
+ precedenceOrder = [
1135
+ ["||", "??"],
1136
+ ["^^"],
1137
+ ["&&"],
1138
+ ["|"],
1139
+ ["^"],
1140
+ ["&"],
1141
+ // NOTE: Equality and inequality merged because of relational chaining
1142
+ [
1143
+ "==",
1144
+ "!=",
1145
+ "===",
1146
+ "!==",
1147
+ "<",
1148
+ "<=",
1149
+ ">",
1150
+ ">=",
1151
+ "in",
1152
+ "instanceof"
1153
+ ],
1154
+ // NOTE: Extra in-between level for default custom operators
1155
+ ["custom"],
1156
+ ["<<", ">>", ">>>"],
1157
+ ["+", "-"],
1158
+ ["*", "/", "%"],
1159
+ ["**"]
1160
+ ];
1161
+ precedenceMap = /* @__PURE__ */ new Map();
1162
+ for (let i1 = 0, len = precedenceOrder.length; i1 < len; i1++) {
1163
+ const prec = i1;
1164
+ const ops = precedenceOrder[i1];
1165
+ for (let i2 = 0, len1 = ops.length; i2 < len1; i2++) {
1166
+ const op = ops[i2];
1167
+ precedenceMap.set(op, prec);
1168
+ }
1169
+ }
1170
+ precedenceStep = 1 / 64;
1171
+ precedenceRelational = precedenceMap.get("==");
1172
+ precedenceCustomDefault = precedenceMap.get("custom");
1173
+ asConst = {
1174
+ ts: true,
1175
+ children: [" as const"]
1064
1176
  };
1065
1177
  }
1066
- let ws2, decl2;
1067
- if (declaration2)
1068
- [, , ws2, decl2] = declaration2;
1069
- switch (inOf.token) {
1070
- case "of": {
1071
- const counterRef = makeRef("i");
1178
+ });
1179
+
1180
+ // source/parser/pattern-matching.civet
1181
+ function processPatternMatching(statements, ReservedWord) {
1182
+ gatherRecursiveAll(statements, ($) => $.type === "SwitchStatement").forEach((s) => {
1183
+ const { caseBlock } = s;
1184
+ const { clauses } = caseBlock;
1185
+ for (const c of clauses) {
1186
+ if (c.type === "WhenClause" && c.break) {
1187
+ const last = c.block?.expressions?.at(-1)?.[1];
1188
+ if (isExit(last)) {
1189
+ c.children.splice(c.children.indexOf(c.break), 1);
1190
+ c.break = void 0;
1191
+ }
1192
+ }
1193
+ }
1194
+ let errors = false;
1195
+ let isPattern = false;
1196
+ if (clauses.some(($1) => $1.type === "PatternClause")) {
1197
+ isPattern = true;
1198
+ clauses.forEach((c) => {
1199
+ if (!(c.type === "PatternClause" || c.type === "DefaultClause")) {
1200
+ errors = true;
1201
+ return c.children.push({
1202
+ type: "Error",
1203
+ message: "Can't mix pattern matching and non-pattern matching clauses"
1204
+ });
1205
+ }
1206
+ ;
1207
+ return;
1208
+ });
1209
+ }
1210
+ if (errors || !isPattern) {
1211
+ return;
1212
+ }
1213
+ let { condition } = s;
1214
+ if (condition.type === "ParenthesizedExpression") {
1215
+ condition = condition.expression;
1216
+ }
1217
+ let hoistDec, refAssignment = [], ref = maybeRef(condition, "m");
1218
+ if (ref !== condition) {
1072
1219
  hoistDec = {
1073
1220
  type: "Declaration",
1074
- children: ["let ", counterRef, " = 0"],
1221
+ children: ["let ", ref],
1075
1222
  names: []
1076
1223
  };
1077
- blockPrefix.push(["", {
1078
- type: "Declaration",
1079
- children: [insertTrimmingSpace(ws2, ""), decl2, " = ", counterRef, "++"],
1080
- names: decl2.names
1081
- }, ";"]);
1082
- break;
1224
+ refAssignment = [{
1225
+ type: "AssignmentExpression",
1226
+ children: [ref, " = ", condition]
1227
+ }, ","];
1083
1228
  }
1084
- case "in": {
1085
- const expRef2 = maybeRef(exp);
1086
- if (expRef2 !== exp) {
1087
- hoistDec = {
1088
- type: "Declaration",
1089
- children: ["let ", expRef2],
1090
- names: []
1091
- };
1092
- exp = {
1093
- type: "AssignmentExpression",
1094
- children: [" ", expRef2, " =", exp]
1095
- };
1229
+ let prev = [], root = prev;
1230
+ const l = clauses.length;
1231
+ clauses.forEach((c, i) => {
1232
+ if (c.type === "DefaultClause") {
1233
+ prev.push(c.block);
1234
+ return;
1096
1235
  }
1097
- let { binding } = declaration;
1098
- if (binding?.type !== "Identifier") {
1099
- const keyRef = makeRef("key");
1100
- blockPrefix.push(["", [
1101
- declaration,
1102
- " = ",
1103
- keyRef
1104
- ], ";"]);
1105
- declaration = {
1106
- type: "ForDeclaration",
1107
- binding: binding = keyRef,
1108
- children: ["const ", keyRef],
1109
- names: []
1110
- };
1236
+ let { patterns, block } = c;
1237
+ let pattern = patterns[0];
1238
+ const indent = block.expressions?.[0]?.[0] || "";
1239
+ const alternativeConditions = patterns.map((pattern2, i2) => {
1240
+ const conditions = [];
1241
+ getPatternConditions(pattern2, ref, conditions);
1242
+ return conditions;
1243
+ });
1244
+ const conditionExpression = alternativeConditions.map((conditions, i2) => {
1245
+ const conditionArray = conditions.map((c2, i3) => {
1246
+ if (i3 === 0)
1247
+ return c2;
1248
+ return [" && ", ...c2];
1249
+ });
1250
+ if (i2 === 0)
1251
+ return conditionArray;
1252
+ return [" || ", ...conditionArray];
1253
+ });
1254
+ const condition2 = {
1255
+ type: "ParenthesizedExpression",
1256
+ children: ["(", ...refAssignment, conditionExpression, ")"],
1257
+ expression: conditionExpression
1258
+ };
1259
+ const prefix = [];
1260
+ switch (pattern.type) {
1261
+ case "ArrayBindingPattern":
1262
+ if (pattern.length === 0)
1263
+ break;
1264
+ case "ObjectBindingPattern": {
1265
+ if (pattern.properties?.length === 0)
1266
+ break;
1267
+ let [splices, thisAssignments] = gatherBindingCode(pattern);
1268
+ const patternBindings = nonMatcherBindings(pattern);
1269
+ splices = splices.map((s2) => [", ", nonMatcherBindings(s2)]);
1270
+ thisAssignments = thisAssignments.map((a) => [indent, a, ";"]);
1271
+ const duplicateDeclarations = aggregateDuplicateBindings([patternBindings, splices], ReservedWord);
1272
+ prefix.push([indent, "const ", patternBindings, " = ", ref, splices, ";"]);
1273
+ prefix.push(...thisAssignments);
1274
+ prefix.push(...duplicateDeclarations.map((d) => [indent, d, ";"]));
1275
+ break;
1276
+ }
1111
1277
  }
1112
- if (own) {
1113
- const hasPropRef = getRef("hasProp");
1114
- blockPrefix.push(["", ["if (!", hasPropRef, "(", insertTrimmingSpace(expRef2, ""), ", ", insertTrimmingSpace(binding, ""), ")) continue"], ";"]);
1278
+ block.expressions.unshift(...prefix);
1279
+ const next = [];
1280
+ braceBlock(block);
1281
+ if (i < l - 1)
1282
+ next.push("\n", "else ");
1283
+ prev.push(["", {
1284
+ type: "IfStatement",
1285
+ children: ["if", condition2, block, next],
1286
+ then: block,
1287
+ else: next,
1288
+ hoistDec
1289
+ }]);
1290
+ hoistDec = void 0;
1291
+ refAssignment = [];
1292
+ return prev = next;
1293
+ });
1294
+ s.type = "PatternMatchingStatement";
1295
+ s.children = [root];
1296
+ return addParentPointers(s, s.parent);
1297
+ });
1298
+ }
1299
+ function getPatternConditions(pattern, ref, conditions) {
1300
+ if (pattern.rest)
1301
+ return;
1302
+ switch (pattern.type) {
1303
+ case "ArrayBindingPattern": {
1304
+ const { elements, length } = pattern, hasRest = elements.some((e) => e.rest), comparator = hasRest ? " >= " : " === ", l = [comparator, (length - hasRest).toString()];
1305
+ conditions.push(
1306
+ ["Array.isArray(", ref, ")"],
1307
+ [ref, ".length", l]
1308
+ );
1309
+ elements.forEach(({ children: [, e] }, i) => {
1310
+ const subRef = [ref, "[", i.toString(), "]"];
1311
+ return getPatternConditions(e, subRef, conditions);
1312
+ });
1313
+ const { blockPrefix } = pattern;
1314
+ if (blockPrefix) {
1315
+ const postElements = blockPrefix.children[1], { length: postLength } = postElements;
1316
+ postElements.forEach(({ children: [, e] }, i) => {
1317
+ const subRef = [ref, "[", ref, ".length - ", (postLength + i).toString(), "]"];
1318
+ return getPatternConditions(e, subRef, conditions);
1319
+ });
1115
1320
  }
1116
- if (decl2) {
1117
- blockPrefix.push(["", {
1118
- type: "Declaration",
1119
- children: [insertTrimmingSpace(ws2, ""), decl2, " = ", insertTrimmingSpace(expRef2, ""), "[", insertTrimmingSpace(binding, ""), "]"],
1120
- names: decl2.names
1121
- }, ";"]);
1321
+ break;
1322
+ }
1323
+ case "ObjectBindingPattern": {
1324
+ conditions.push(
1325
+ ["typeof ", ref, " === 'object'"],
1326
+ [ref, " != null"]
1327
+ );
1328
+ pattern.properties.forEach((p) => {
1329
+ switch (p.type) {
1330
+ case "PinProperty":
1331
+ case "BindingProperty": {
1332
+ const { name, value } = p;
1333
+ let subRef;
1334
+ switch (name.type) {
1335
+ case "ComputedPropertyName":
1336
+ conditions.push([name.expression, " in ", ref]);
1337
+ subRef = [ref, name];
1338
+ break;
1339
+ case "Literal":
1340
+ case "StringLiteral":
1341
+ case "NumericLiteral":
1342
+ conditions.push([name, " in ", ref]);
1343
+ subRef = [ref, "[", name, "]"];
1344
+ break;
1345
+ default:
1346
+ conditions.push(["'", name, "' in ", ref]);
1347
+ subRef = [ref, ".", name];
1348
+ }
1349
+ if (value) {
1350
+ getPatternConditions(value, subRef, conditions);
1351
+ }
1352
+ break;
1353
+ }
1354
+ }
1355
+ });
1356
+ break;
1357
+ }
1358
+ case "ConditionFragment": {
1359
+ let { children } = pattern;
1360
+ if (children.length) {
1361
+ let [first, ...rest] = children;
1362
+ let [ws, ...op] = first;
1363
+ ws = [" "].concat(ws);
1364
+ first = [ws, ...op];
1365
+ children = [first, ...rest];
1122
1366
  }
1367
+ conditions.push(
1368
+ processBinaryOpExpression([ref, children])
1369
+ );
1370
+ break;
1371
+ }
1372
+ case "RegularExpressionLiteral": {
1373
+ conditions.push(
1374
+ ["typeof ", ref, " === 'string'"],
1375
+ [pattern, ".test(", ref, ")"]
1376
+ );
1123
1377
  break;
1124
1378
  }
1379
+ case "PinPattern":
1380
+ conditions.push([
1381
+ ref,
1382
+ " === ",
1383
+ pattern.expression
1384
+ ]);
1385
+ break;
1386
+ case "Literal":
1387
+ conditions.push([
1388
+ ref,
1389
+ " === ",
1390
+ pattern
1391
+ ]);
1392
+ break;
1125
1393
  default:
1126
- (() => {
1127
- throw new Error(`for item, index must use 'of' or 'in' instead of '${inOf.token}'`);
1128
- })();
1394
+ break;
1129
1395
  }
1130
- return {
1131
- declaration,
1132
- children: [awaits, eachOwnError, open, declaration, ws, inOf, exp, step, close],
1133
- // omit declaration2, replace each with eachOwnError
1134
- blockPrefix,
1135
- hoistDec
1136
- };
1137
1396
  }
1138
- var init_for = __esm({
1139
- "source/parser/for.civet"() {
1140
- "use strict";
1141
- init_util();
1142
- }
1143
- });
1144
-
1145
- // source/parser/binding.civet
1146
- function adjustAtBindings(statements, asThis = false) {
1147
- gatherRecursiveAll(statements, (n) => n.type === "AtBindingProperty").forEach((binding) => {
1148
- const { ref } = binding;
1149
- if (asThis) {
1150
- const atBinding = binding.binding;
1151
- atBinding.children.pop();
1152
- atBinding.type = void 0;
1153
- binding.children.unshift(ref.id, ": this.", ref.base);
1154
- binding.type = "Property";
1155
- binding.ref = void 0;
1156
- return;
1397
+ function elideMatchersFromArrayBindings(elements) {
1398
+ return elements.map((el) => {
1399
+ if (el.type === "BindingRestElement") {
1400
+ return ["", el, void 0];
1157
1401
  }
1158
- if (ref.names[0] !== ref.base) {
1159
- return binding.children.unshift(ref.base, ": ");
1402
+ const { children: [ws, e, delim] } = el;
1403
+ switch (e.type) {
1404
+ case "Literal":
1405
+ case "RegularExpressionLiteral":
1406
+ case "StringLiteral":
1407
+ case "PinPattern":
1408
+ return delim;
1409
+ default:
1410
+ return [ws, nonMatcherBindings(e), delim];
1160
1411
  }
1161
- ;
1162
- return;
1163
1412
  });
1164
1413
  }
1165
- function adjustBindingElements(elements) {
1166
- const names = elements.flatMap((p) => p.names || []), { length } = elements;
1167
- let blockPrefix, restIndex = -1, restCount = 0;
1168
- elements.forEach(({ type }, i) => {
1169
- if (type === "BindingRestElement") {
1170
- if (restIndex < 0)
1171
- restIndex = i;
1172
- return restCount++;
1173
- }
1174
- ;
1175
- return;
1176
- });
1177
- if (restCount === 0) {
1178
- return {
1179
- children: elements,
1180
- names,
1181
- blockPrefix,
1182
- length
1183
- };
1184
- } else if (restCount === 1) {
1185
- const rest = elements[restIndex];
1186
- const after = elements.slice(restIndex + 1);
1187
- const restIdentifier = rest.binding.ref || rest.binding;
1188
- names.push(...rest.names || []);
1189
- let l = after.length;
1190
- if (l) {
1191
- if (arrayElementHasTrailingComma(after[l - 1]))
1192
- l++;
1193
- blockPrefix = {
1194
- type: "PostRestBindingElements",
1195
- children: ["[", insertTrimmingSpace(after, ""), "] = ", restIdentifier, ".splice(-", l.toString(), ")"],
1196
- names: after.flatMap((p) => p.names)
1414
+ function elideMatchersFromPropertyBindings(properties) {
1415
+ return properties.map((p) => {
1416
+ switch (p.type) {
1417
+ case "BindingProperty": {
1418
+ const { children, name, value } = p;
1419
+ const [ws] = children;
1420
+ switch (value && value.type) {
1421
+ case "ArrayBindingPattern":
1422
+ case "ObjectBindingPattern":
1423
+ return {
1424
+ ...p,
1425
+ children: [ws, name, ": ", nonMatcherBindings(value), p.delim]
1426
+ };
1427
+ case "Identifier":
1428
+ return p;
1429
+ case "Literal":
1430
+ case "RegularExpressionLiteral":
1431
+ case "StringLiteral":
1432
+ default:
1433
+ return {
1434
+ ...p,
1435
+ children: [ws, name, p.delim]
1436
+ };
1437
+ }
1438
+ }
1439
+ case "PinProperty":
1440
+ case "BindingRestProperty":
1441
+ default:
1442
+ return p;
1443
+ }
1444
+ });
1445
+ }
1446
+ function nonMatcherBindings(pattern) {
1447
+ switch (pattern.type) {
1448
+ case "ArrayBindingPattern": {
1449
+ const elements = elideMatchersFromArrayBindings(pattern.elements);
1450
+ const children = ["[", elements, "]"];
1451
+ return {
1452
+ ...pattern,
1453
+ children,
1454
+ elements
1197
1455
  };
1198
1456
  }
1199
- return {
1200
- names,
1201
- children: [...elements.slice(0, restIndex), {
1202
- ...rest,
1203
- children: rest.children.slice(0, -1)
1204
- // remove trailing comma
1205
- }],
1206
- blockPrefix,
1207
- length
1208
- };
1457
+ case "PostRestBindingElements": {
1458
+ const els = elideMatchersFromArrayBindings(pattern.children[1]);
1459
+ return {
1460
+ ...pattern,
1461
+ children: [
1462
+ pattern.children[0],
1463
+ els,
1464
+ ...pattern.children.slice(2)
1465
+ ]
1466
+ };
1467
+ }
1468
+ case "ObjectBindingPattern":
1469
+ return ["{", elideMatchersFromPropertyBindings(pattern.properties), "}"];
1470
+ default:
1471
+ return pattern;
1209
1472
  }
1210
- const err = {
1211
- type: "Error",
1212
- children: ["Multiple rest elements in array pattern"]
1213
- };
1214
- return {
1215
- names,
1216
- children: [...elements, err],
1217
- blockPrefix,
1218
- length
1219
- };
1220
1473
  }
1221
- function gatherBindingCode(statements, opts) {
1222
- const thisAssignments = [];
1223
- const splices = [];
1224
- function insertRestSplices(s, p, thisAssignments2) {
1225
- gatherRecursiveAll(s, (n) => n.blockPrefix || opts?.injectParamProps && n.accessModifier || n.type === "AtBinding").forEach((n) => {
1226
- if (n.type === "AtBinding") {
1227
- const { ref } = n;
1228
- const { id } = ref;
1229
- thisAssignments2.push([`this.${id} = `, ref]);
1230
- return;
1231
- }
1232
- if (opts?.injectParamProps && n.type === "Parameter" && n.accessModifier) {
1233
- n.names.forEach((id) => ({
1234
- push: thisAssignments2.push({
1235
- type: "AssignmentExpression",
1236
- children: [`this.${id} = `, id],
1237
- js: true
1238
- })
1239
- }));
1474
+ function aggregateDuplicateBindings(bindings, ReservedWord) {
1475
+ const props = gatherRecursiveAll(bindings, ($2) => $2.type === "BindingProperty");
1476
+ const arrayBindings = gatherRecursiveAll(bindings, ($3) => $3.type === "ArrayBindingPattern");
1477
+ arrayBindings.forEach((a) => {
1478
+ const { elements } = a;
1479
+ return elements.forEach((element) => {
1480
+ if (Array.isArray(element)) {
1481
+ const [, e] = element;
1482
+ if (e.type === "Identifier") {
1483
+ return props.push(e);
1484
+ } else if (e.type === "BindingRestElement") {
1485
+ return props.push(e);
1486
+ }
1487
+ ;
1240
1488
  return;
1241
1489
  }
1242
- const { blockPrefix } = n;
1243
- p.push(blockPrefix);
1244
- return insertRestSplices(blockPrefix, p, thisAssignments2);
1490
+ ;
1491
+ return;
1245
1492
  });
1493
+ });
1494
+ const declarations = [];
1495
+ const propsGroupedByName = /* @__PURE__ */ new Map();
1496
+ for (const p of props) {
1497
+ const { name, value } = p;
1498
+ const key = value?.name || name?.name || name;
1499
+ if (propsGroupedByName.has(key)) {
1500
+ propsGroupedByName.get(key).push(p);
1501
+ } else {
1502
+ propsGroupedByName.set(key, [p]);
1503
+ }
1246
1504
  }
1247
- insertRestSplices(statements, splices, thisAssignments);
1248
- return [splices, thisAssignments];
1505
+ propsGroupedByName.forEach((shared, key) => {
1506
+ if (!key) {
1507
+ return;
1508
+ }
1509
+ if (ReservedWord({ fail() {
1510
+ } }, {
1511
+ pos: 0,
1512
+ input: key
1513
+ })) {
1514
+ shared.forEach((p) => {
1515
+ return aliasBinding(p, makeRef(`_${key}`, key));
1516
+ });
1517
+ return;
1518
+ }
1519
+ if (shared.length === 1) {
1520
+ return;
1521
+ }
1522
+ const refs = shared.map((p) => {
1523
+ const ref = makeRef(key);
1524
+ aliasBinding(p, ref);
1525
+ return ref;
1526
+ });
1527
+ return declarations.push(["const ", key, " = [", ...refs.map((r, i) => {
1528
+ return i === 0 ? r : [", ", r];
1529
+ }), "]"]);
1530
+ });
1531
+ return declarations;
1249
1532
  }
1250
- function arrayElementHasTrailingComma(elementNode) {
1251
- const lastChild = elementNode.children.at(-1);
1252
- return lastChild && lastChild[lastChild.length - 1]?.token === ",";
1533
+ function aliasBinding(p, ref) {
1534
+ if (p.type === "Identifier") {
1535
+ p.children[0] = ref;
1536
+ } else if (p.type === "BindingRestElement") {
1537
+ aliasBinding(p.binding, ref);
1538
+ } else if (p.value?.type === "Identifier") {
1539
+ aliasBinding(p.value, ref);
1540
+ } else {
1541
+ p.value = ref;
1542
+ const index = p.children.indexOf(p.name);
1543
+ p.children.splice(index + 1, 0, ": ", ref);
1544
+ }
1253
1545
  }
1254
- var init_binding = __esm({
1255
- "source/parser/binding.civet"() {
1546
+ var init_pattern_matching = __esm({
1547
+ "source/parser/pattern-matching.civet"() {
1256
1548
  "use strict";
1257
1549
  init_traversal();
1258
1550
  init_util();
1551
+ init_block();
1552
+ init_binding();
1553
+ init_op();
1259
1554
  }
1260
1555
  });
1261
1556
 
@@ -1374,8 +1669,9 @@ function processReturnValue(func) {
1374
1669
  return r.children.splice(-1, 1, " ", ref);
1375
1670
  });
1376
1671
  if (!(block.children.at(-2)?.type === "ReturnStatement")) {
1672
+ const indent = getIndent(block.expressions.at(-1)) || ";";
1377
1673
  block.expressions.push([
1378
- [getIndent(block.expressions.at(-1))],
1674
+ [indent],
1379
1675
  {
1380
1676
  type: "ReturnStatement",
1381
1677
  expression: ref,
@@ -1418,36 +1714,36 @@ function patternAsValue(pattern) {
1418
1714
  return pattern;
1419
1715
  }
1420
1716
  }
1421
- function insertPush(node, ref) {
1717
+ function assignResults(node, collect) {
1422
1718
  if (!node)
1423
1719
  return;
1424
1720
  switch (node.type) {
1425
1721
  case "BlockStatement":
1426
1722
  if (node.expressions.length) {
1427
- insertPush(node.expressions.at(-1), ref);
1723
+ assignResults(node.expressions.at(-1), collect);
1428
1724
  } else {
1429
- node.expressions.push([ref, ".push(void 0);"]);
1725
+ node.expressions.push(["", collect("void 0"), ";"]);
1430
1726
  }
1431
1727
  return;
1432
1728
  case "CaseBlock":
1433
1729
  node.clauses.forEach((clause) => {
1434
- return insertPush(clause, ref);
1730
+ return assignResults(clause, collect);
1435
1731
  });
1436
1732
  return;
1437
1733
  case "WhenClause":
1438
- insertPush(node.block, ref);
1439
- return;
1440
1734
  case "DefaultClause":
1441
- insertPush(node.block, ref);
1735
+ case "PatternClause": {
1736
+ assignResults(node.block, collect);
1442
1737
  return;
1738
+ }
1443
1739
  }
1444
- if (!Array.isArray(node))
1740
+ if (!Array.isArray(node)) {
1445
1741
  return;
1742
+ }
1446
1743
  let [, exp] = node;
1447
1744
  if (!exp) {
1448
1745
  return;
1449
1746
  }
1450
- const indent = getIndent(node);
1451
1747
  const outer = exp;
1452
1748
  let { type } = exp;
1453
1749
  if (type === "LabelledStatement") {
@@ -1463,46 +1759,44 @@ function insertPush(node, ref) {
1463
1759
  case "ThrowStatement":
1464
1760
  return;
1465
1761
  case "Declaration":
1466
- exp.children.push(["", [
1467
- ";",
1468
- ref,
1469
- ".push(",
1470
- patternAsValue(exp.bindings.at(-1).pattern),
1471
- ")"
1472
- ]]);
1762
+ exp.children.push([
1763
+ "",
1764
+ [";", collect(patternAsValue(exp.bindings.at(-1).pattern))]
1765
+ ]);
1473
1766
  return;
1474
1767
  case "ForStatement":
1475
1768
  case "IterationStatement":
1476
1769
  case "DoStatement":
1477
- wrapIterationReturningResults(exp, outer, ref);
1770
+ wrapIterationReturningResults(exp, outer, collect);
1478
1771
  return;
1479
1772
  case "BlockStatement":
1480
- insertPush(exp.expressions[exp.expressions.length - 1], ref);
1773
+ assignResults(exp.expressions[exp.expressions.length - 1], collect);
1481
1774
  return;
1482
1775
  case "IfStatement":
1483
- insertPush(exp.then, ref);
1776
+ assignResults(exp.then, collect);
1484
1777
  if (exp.then.bare && !exp.then.semicolon) {
1485
1778
  exp.then.children.push(exp.then.semicolon = ";");
1486
1779
  }
1487
- if (exp.else)
1488
- insertPush(exp.else[2], ref);
1489
- else
1490
- exp.children.push([" else {\n", indent, ref, ".push(undefined)\n", indent, "}"]);
1780
+ if (exp.else) {
1781
+ assignResults(exp.else[2], collect);
1782
+ } else {
1783
+ exp.children.push([" else {", collect("undefined"), "}"]);
1784
+ }
1491
1785
  return;
1492
1786
  case "PatternMatchingStatement":
1493
- insertPush(exp.children[0][0], ref);
1787
+ assignResults(exp.children[0][0], collect);
1494
1788
  return;
1495
1789
  case "SwitchStatement":
1496
- insertPush(exp.children[2], ref);
1790
+ assignResults(exp.children[2], collect);
1497
1791
  return;
1498
1792
  case "TryStatement":
1499
- exp.blocks.forEach((block) => insertPush(block, ref));
1793
+ exp.blocks.forEach((block) => assignResults(block, collect));
1500
1794
  return;
1501
1795
  }
1502
- if (node[node.length - 1]?.type === "SemicolonDelimiter")
1796
+ if (node.at(-1)?.type === "SemicolonDelimiter") {
1503
1797
  return;
1504
- node.splice(1, 0, ref, ".push(");
1505
- node.push(")");
1798
+ }
1799
+ node[1] = collect(node[1]);
1506
1800
  }
1507
1801
  function insertReturn(node, outerNode = node) {
1508
1802
  if (!node)
@@ -1615,24 +1909,31 @@ function insertSwitchReturns(exp) {
1615
1909
  return insertReturn(clause);
1616
1910
  });
1617
1911
  }
1618
- function wrapIterationReturningResults(statement, outer, outerRef) {
1912
+ function wrapIterationReturningResults(statement, outer, collect) {
1619
1913
  if (statement.type === "DoStatement") {
1620
- if (outerRef) {
1621
- insertPush(statement.block, outerRef);
1914
+ if (collect) {
1915
+ assignResults(statement.block, collect);
1622
1916
  } else {
1623
1917
  insertReturn(statement.block, outer);
1624
1918
  }
1625
1919
  return;
1626
1920
  }
1627
- const resultsRef = makeRef("results");
1921
+ assert.equal(
1922
+ statement.resultsRef,
1923
+ void 0,
1924
+ "wrapIterationReturningResults should not be called twice on the same statement"
1925
+ );
1926
+ const resultsRef = statement.resultsRef = makeRef("results");
1628
1927
  const declaration = {
1629
1928
  type: "Declaration",
1630
- children: ["const ", resultsRef, "=[];"]
1929
+ children: ["const ", resultsRef, "=[]"]
1631
1930
  };
1632
- insertPush(statement.block, resultsRef);
1633
- outer.children.unshift(declaration);
1634
- if (outerRef) {
1635
- statement.children.push(";", outerRef, ".push(", resultsRef, ");");
1931
+ outer.children.unshift(["", declaration, ";"]);
1932
+ assignResults(statement.block, (node) => {
1933
+ return [resultsRef, ".push(", node, ")"];
1934
+ });
1935
+ if (collect) {
1936
+ statement.children.push(collect(resultsRef));
1636
1937
  } else {
1637
1938
  statement.children.push(";return ", resultsRef, ";");
1638
1939
  }
@@ -1715,8 +2016,11 @@ function expressionizeIteration(exp) {
1715
2016
  updateParentPointers(exp);
1716
2017
  return;
1717
2018
  }
1718
- const resultsRef = makeRef("results");
1719
- insertPush(block, resultsRef);
2019
+ exp.resultsRef ??= makeRef("results");
2020
+ const { resultsRef } = exp;
2021
+ assignResults(block, (node) => {
2022
+ return [resultsRef, ".push(", node, ")"];
2023
+ });
1720
2024
  braceBlock(block);
1721
2025
  children.splice(
1722
2026
  i,
@@ -1729,6 +2033,19 @@ function expressionizeIteration(exp) {
1729
2033
  );
1730
2034
  updateParentPointers(exp);
1731
2035
  }
2036
+ function skipImplicitArguments(args) {
2037
+ if (args.length === 1) {
2038
+ let arg0 = args[0];
2039
+ if (Array.isArray(arg0)) {
2040
+ arg0 = arg0[1];
2041
+ }
2042
+ if (arg0.type === "StatementExpression") {
2043
+ arg0 = arg0.statement;
2044
+ }
2045
+ return arg0.type === "IterationExpression" && arg0.subtype !== "DoStatement" && !arg0.async && isEmptyBareBlock(arg0.block);
2046
+ }
2047
+ return false;
2048
+ }
1732
2049
  var init_function = __esm({
1733
2050
  "source/parser/function.civet"() {
1734
2051
  "use strict";
@@ -1739,864 +2056,757 @@ var init_function = __esm({
1739
2056
  }
1740
2057
  });
1741
2058
 
1742
- // source/parser/op.civet
1743
- function getPrecedence(op) {
1744
- if (typeof op === "string") {
1745
- return precedenceMap.get(op) ?? (() => {
1746
- throw new Error(`Unknown operator: ${op}`);
1747
- })();
1748
- } else if (typeof op.prec === "number") {
1749
- return op.prec;
1750
- } else {
1751
- return precedenceMap.get(op.prec ?? op.token) ?? (op.relational ? precedenceRelational : precedenceCustomDefault);
1752
- }
2059
+ // source/parser/declaration.civet
2060
+ function processAssignmentDeclaration(decl, pattern, suffix, ws, assign, e) {
2061
+ decl = {
2062
+ ...decl,
2063
+ $loc: {
2064
+ pos: assign.$loc.pos - 1,
2065
+ length: assign.$loc.length + 1
2066
+ }
2067
+ };
2068
+ let [splices, assignments] = gatherBindingCode(pattern);
2069
+ splices = splices.map((s) => [", ", s]);
2070
+ const thisAssignments = assignments.map((a) => ["", a, ";"]);
2071
+ const initializer = [ws, assign, e];
2072
+ const binding = makeNode({
2073
+ type: "Binding",
2074
+ pattern,
2075
+ initializer,
2076
+ splices,
2077
+ suffix,
2078
+ thisAssignments,
2079
+ children: [pattern, suffix, initializer]
2080
+ });
2081
+ const children = [decl, binding];
2082
+ return makeNode({
2083
+ type: "Declaration",
2084
+ names: pattern.names,
2085
+ decl,
2086
+ bindings: [binding],
2087
+ splices,
2088
+ thisAssignments,
2089
+ children
2090
+ });
1753
2091
  }
1754
- function processBinaryOpExpression($0) {
1755
- return recurse(expandChainedComparisons($0));
1756
- function recurse(expandedOps) {
1757
- let i = 2;
1758
- while (i < expandedOps.length) {
1759
- let op = expandedOps[i];
1760
- if (op.special) {
1761
- let advanceLeft2 = function(allowEqual) {
1762
- while (start >= 4) {
1763
- const prevPrec = getPrecedence(expandedOps[start - 2]);
1764
- if (!(prevPrec > prec || allowEqual && prevPrec === prec)) {
1765
- return prevPrec === prec;
1766
- }
1767
- start -= 4;
1768
- }
1769
- return false;
1770
- }, advanceRight2 = function(allowEqual) {
1771
- while (end + 4 < expandedOps.length) {
1772
- const nextPrec = getPrecedence(expandedOps[end + 2]);
1773
- if (!(nextPrec > prec || allowEqual && nextPrec === prec)) {
1774
- return nextPrec === prec;
1775
- }
1776
- end += 4;
1777
- }
1778
- return false;
1779
- };
1780
- var advanceLeft = advanceLeft2, advanceRight = advanceRight2;
1781
- let start = i - 2, end = i + 2;
1782
- const prec = getPrecedence(op);
1783
- let error;
1784
- switch (op.assoc) {
1785
- case "left":
1786
- case void 0: {
1787
- advanceLeft2(true);
1788
- advanceRight2(false);
1789
- break;
1790
- }
1791
- case "right": {
1792
- advanceLeft2(false);
1793
- advanceRight2(true);
1794
- break;
1795
- }
1796
- case "non": {
1797
- if (advanceLeft2(false) || advanceRight2(false)) {
1798
- error = {
1799
- type: "Error",
1800
- message: `non-associative operator ${op.token} used at same precedence level without parenthesization`
1801
- };
1802
- }
1803
- ;
1804
- break;
1805
- }
1806
- case "arguments": {
1807
- if (advanceLeft2(false)) {
1808
- error = {
1809
- type: "Error",
1810
- message: `arguments operator ${op.token} used at same precedence level as ${expandedOps[start - 2].token} to the left`
1811
- };
1812
- }
1813
- advanceRight2(true);
1814
- break;
1815
- }
1816
- default: {
1817
- throw new Error(`Unsupported associativity: ${op.assoc}`);
1818
- }
1819
- }
1820
- let a = start === i - 2 ? expandedOps[start] : expandedOps.slice(start, i - 1);
1821
- let wsOp = expandedOps[i - 1];
1822
- let wsB = expandedOps[i + 1];
1823
- let b = end === i + 2 ? expandedOps[i + 2] : expandedOps.slice(i + 2, end + 1);
1824
- if (op.assoc === "arguments") {
1825
- let i2 = 2;
1826
- while (i2 < b.length) {
1827
- if (prec === getPrecedence(b[i2])) {
1828
- if (!(b[i2].token === op.token)) {
1829
- error ??= {
1830
- type: "Error",
1831
- message: `arguments operator ${op.token} used at same precedence level as ${b[i2].token} to the right`
1832
- };
1833
- }
1834
- b[i2] = ",";
1835
- }
1836
- i2 += 4;
1837
- }
1838
- } else {
1839
- b = recurse(b);
1840
- }
1841
- if (op.token === "instanceof" && b.type === "Literal" && b.children?.[0]?.type === "StringLiteral") {
1842
- a = ["typeof ", makeLeftHandSideExpression(a)];
1843
- if (op.negated) {
1844
- op = { ...op, token: "!==", negated: false };
1845
- } else {
1846
- op = { ...op, token: "===" };
1847
- }
1848
- }
1849
- if (op.asConst) {
1850
- a = makeAsConst(a);
1851
- b = makeAsConst(b);
1852
- }
1853
- let children;
1854
- if (op.call) {
1855
- wsOp = insertTrimmingSpace(wsOp, "");
1856
- if (op.reversed) {
1857
- wsB = insertTrimmingSpace(wsB, "");
1858
- children = [wsOp, op.call, "(", wsB, b, ", ", a, ")", op.suffix];
1859
- } else {
1860
- children = [wsOp, op.call, "(", a, ",", wsB, b, ")", op.suffix];
1861
- }
1862
- } else if (op.method) {
1863
- wsOp = insertTrimmingSpace(wsOp, "");
1864
- wsB = insertTrimmingSpace(wsB, "");
1865
- if (op.reversed) {
1866
- if (end !== i + 2)
1867
- b = makeLeftHandSideExpression(b);
1868
- b = dotNumericLiteral(b);
1869
- children = [wsB, b, wsOp, ".", op.method, "(", a, ")"];
1870
- } else {
1871
- if (start !== i - 2 || a.type === "NumericLiteral") {
1872
- a = makeLeftHandSideExpression(a);
1873
- }
1874
- a = dotNumericLiteral(a);
1875
- children = [a, wsOp, ".", op.method, "(", wsB, b, ")"];
1876
- }
1877
- } else if (op.token) {
1878
- children = [a, wsOp, op, wsB, b];
1879
- if (op.negated)
1880
- children = ["(", ...children, ")"];
1881
- } else {
1882
- throw new Error("Unknown operator: " + JSON.stringify(op));
1883
- }
1884
- if (op.negated)
1885
- children.unshift("!");
1886
- if (error != null) {
1887
- children.push(error);
1888
- }
1889
- expandedOps.splice(start, end - start + 1, {
1890
- children
1891
- });
1892
- i = start + 2;
1893
- } else {
1894
- i += 4;
2092
+ function processDeclarations(statements) {
2093
+ gatherRecursiveAll(statements, ($) => $.type === "Declaration").forEach((statement) => {
2094
+ const { bindings } = statement;
2095
+ return bindings?.forEach((binding) => {
2096
+ const suffix = binding.suffix;
2097
+ if (suffix && suffix.optional && suffix.t) {
2098
+ convertOptionalType(suffix);
1895
2099
  }
1896
- }
1897
- return expandedOps;
1898
- }
1899
- ;
1900
- return recurse;
2100
+ const { initializer } = binding;
2101
+ if (initializer) {
2102
+ return prependStatementExpressionBlock(initializer, statement);
2103
+ }
2104
+ ;
2105
+ return;
2106
+ });
2107
+ });
1901
2108
  }
1902
- function dotNumericLiteral(literal) {
1903
- if (literal?.type === "Literal" && /^[+-]?(?:0|[1-9](?:_[0-9]|[0-9])*)$/.test(literal.raw)) {
1904
- literal.children.push(".");
1905
- literal.raw += ".";
2109
+ function prependStatementExpressionBlock(initializer, statement) {
2110
+ let exp = initializer[2];
2111
+ let ws;
2112
+ if (Array.isArray(exp)) {
2113
+ ws = exp[0];
2114
+ exp = exp[1];
1906
2115
  }
1907
- return literal;
1908
- }
1909
- function makeAsConst(node) {
1910
- if (Array.isArray(node) && node.length === 1) {
1911
- node = node[0];
2116
+ if (!(exp.type === "StatementExpression")) {
2117
+ return;
1912
2118
  }
1913
- if (node.type === "Literal" && node.raw !== "null" || node.type === "ArrayExpression" || node.type === "ObjectExpression") {
1914
- return { ...node, children: [...node.children, asConst] };
2119
+ const pre = [];
2120
+ const statementExp = exp.statement;
2121
+ const blockStatement = ["", statementExp];
2122
+ let ref;
2123
+ if (statementExp.type === "IterationExpression") {
2124
+ if (statementExp.async) {
2125
+ return;
2126
+ }
2127
+ const statement2 = statementExp.statement;
2128
+ blockStatement[1] = statement2;
2129
+ if (statement2.type === "DoStatement") {
2130
+ ref = initializer[2] = makeRef();
2131
+ assignResults(blockStatement, (resultNode) => {
2132
+ return makeNode({
2133
+ type: "AssignmentExpression",
2134
+ children: [ref, " = ", resultNode]
2135
+ });
2136
+ });
2137
+ const refDec = {
2138
+ type: "Declaration",
2139
+ children: ["let ", ref, ";"]
2140
+ };
2141
+ pre.unshift(refDec);
2142
+ } else {
2143
+ wrapIterationReturningResults(statement2, { children: blockStatement }, function() {
2144
+ });
2145
+ ref = initializer[2] = statement2.resultsRef;
2146
+ }
1915
2147
  } else {
1916
- return node;
2148
+ ref = initializer[2] = makeRef();
2149
+ assignResults(blockStatement, (resultNode) => {
2150
+ return makeNode({
2151
+ type: "AssignmentExpression",
2152
+ children: [ref, " = ", resultNode]
2153
+ });
2154
+ });
2155
+ const refDec = {
2156
+ type: "Declaration",
2157
+ children: ["let ", ref, ";"]
2158
+ };
2159
+ pre.unshift(refDec);
2160
+ if (ws) {
2161
+ pre.push(ws);
2162
+ }
1917
2163
  }
2164
+ statement.children.unshift(pre, blockStatement, ";");
2165
+ updateParentPointers(blockStatement, statement);
2166
+ return ref;
1918
2167
  }
1919
- function isExistence(exp) {
1920
- if (exp.type === "ParenthesizedExpression" && exp.implicit) {
1921
- exp = exp.expression;
2168
+ function processDeclarationCondition(condition, rootCondition, parent) {
2169
+ if (!(condition.type === "DeclarationCondition")) {
2170
+ return;
1922
2171
  }
1923
- if (exp.type === "Existence") {
1924
- return exp;
2172
+ const { decl, bindings } = condition.declaration;
2173
+ const binding = bindings[0];
2174
+ const { pattern, suffix, initializer, splices, thisAssignments } = binding;
2175
+ let ref = prependStatementExpressionBlock(initializer, parent);
2176
+ if (ref) {
2177
+ Object.assign(condition, {
2178
+ type: "AssignmentExpression",
2179
+ children: [ref],
2180
+ pattern,
2181
+ ref,
2182
+ statementDeclaration: true
2183
+ });
2184
+ } else {
2185
+ ref = makeRef();
2186
+ const grandparent = condition.parent?.parent;
2187
+ const children = (
2188
+ // Check that the declaration is a plain assignment (no pattern-matching) and the immediate grandchild of an `if` or `while`
2189
+ // More complex conditions (triggered by pattern matching or `until`/`unless`) don't need double parens
2190
+ // @ts-ignore Just because pattern might not have a type at runtime doesn't mean it's unsafe
2191
+ pattern.type === "Identifier" && (grandparent?.type === "IfStatement" || grandparent?.type === "WhileStatement") ? ["(", ref, initializer, ")"] : [ref, initializer]
2192
+ );
2193
+ Object.assign(condition, {
2194
+ type: "AssignmentExpression",
2195
+ children,
2196
+ hoistDec: {
2197
+ type: "Declaration",
2198
+ children: ["let ", ref, suffix],
2199
+ names: []
2200
+ },
2201
+ pattern,
2202
+ ref
2203
+ });
1925
2204
  }
1926
- ;
1927
- return;
2205
+ addParentPointers(condition, parent);
2206
+ Object.assign(rootCondition, {
2207
+ blockPrefix: [
2208
+ ["", [decl, pattern, suffix, " = ", ref, ...splices], ";"],
2209
+ ...thisAssignments
2210
+ ]
2211
+ });
1928
2212
  }
1929
- function isRelationalOp(op) {
1930
- return op.relational || getPrecedence(op) === precedenceRelational;
2213
+ function processDeclarationConditions(node) {
2214
+ gatherRecursiveAll(node, (n) => {
2215
+ return n.type === "IfStatement" || n.type === "IterationStatement" || n.type === "SwitchStatement";
2216
+ }).forEach(processDeclarationConditionStatement);
1931
2217
  }
1932
- function expandChainedComparisons([first, binops]) {
1933
- const results = [];
1934
- let i = 0;
1935
- const l = binops.length;
1936
- let start = 0;
1937
- let chains = [];
1938
- let op;
1939
- while (i < l) {
1940
- [, op] = binops[i];
1941
- if (isRelationalOp(op)) {
1942
- chains.push(i);
1943
- } else if (getPrecedence(op) < precedenceRelational) {
1944
- processChains(op);
1945
- first = void 0;
1946
- }
1947
- i++;
2218
+ function processDeclarationConditionStatement(s) {
2219
+ const { condition } = s;
2220
+ if (!condition?.expression) {
2221
+ return;
1948
2222
  }
1949
- if (op != null) {
1950
- processChains(op);
2223
+ let { expression } = condition;
2224
+ if (typeof expression === "object" && expression != null && "type" in expression && expression.type === "UnaryExpression" && "children" in expression && Array.isArray(expression.children) && expression.children.length === 2 && expression.children[0] === "!" && typeof expression.children[1] === "object" && expression.children[1] != null && "type" in expression.children[1] && expression.children[1].type === "ParenthesizedExpression" && "expression" in expression.children[1]) {
2225
+ const { type: type1, children: [, { type: type2, expression: expression2 }] } = expression;
2226
+ const type = [type1, type2];
2227
+ expression = expression2;
1951
2228
  }
1952
- return results;
1953
- function processChains(op2) {
1954
- if (first && isRelationalOp(op2)) {
1955
- first = expandExistence(first);
1956
- }
1957
- if (chains.length > 1) {
1958
- chains.forEach((index, k) => {
1959
- if (k > 0) {
1960
- results.push(" ", "&&", " ");
1961
- }
1962
- const binop = binops[index];
1963
- let [, , , exp] = binop;
1964
- exp = binop[3] = expandExistence(exp);
1965
- let endIndex;
1966
- if (k < chains.length - 1) {
1967
- endIndex = chains[k + 1];
1968
- } else {
1969
- endIndex = i + 1;
1970
- }
1971
- results.push(first, ...binops.slice(start, endIndex).flat());
1972
- first = [exp].concat(binops.slice(index + 1, endIndex));
1973
- return start = endIndex;
2229
+ processDeclarationCondition(expression, condition.expression, s);
2230
+ const { ref, pattern } = expression;
2231
+ if (pattern) {
2232
+ let conditions = [];
2233
+ getPatternConditions(pattern, ref, conditions);
2234
+ conditions = conditions.filter((c) => {
2235
+ return !(c.length === 3 && c[0] === "typeof " && c[1] === ref && c[2] === " === 'object'") && !(c.length === 2 && c[0] === ref && c[1] === " != null");
2236
+ });
2237
+ if (conditions.length) {
2238
+ condition.children.unshift("(");
2239
+ conditions.forEach(function(c) {
2240
+ return condition.children.push(" && ", c);
1974
2241
  });
1975
- } else {
1976
- if (first) {
1977
- results.push(first);
1978
- }
1979
- results.push(...binops.slice(start, i + 1).flat());
1980
- start = i + 1;
1981
- }
1982
- chains.length = 0;
1983
- }
1984
- function expandExistence(exp) {
1985
- const existence = isExistence(exp);
1986
- if (existence) {
1987
- results.push(existence, " ", "&&", " ");
1988
- return existence.expression;
1989
- }
1990
- return exp;
1991
- }
1992
- ;
1993
- }
1994
- var precedenceOrder, precedenceMap, precedenceStep, precedenceRelational, precedenceCustomDefault, asConst;
1995
- var init_op = __esm({
1996
- "source/parser/op.civet"() {
1997
- "use strict";
1998
- init_util();
1999
- precedenceOrder = [
2000
- ["||", "??"],
2001
- ["^^"],
2002
- ["&&"],
2003
- ["|"],
2004
- ["^"],
2005
- ["&"],
2006
- // NOTE: Equality and inequality merged because of relational chaining
2007
- [
2008
- "==",
2009
- "!=",
2010
- "===",
2011
- "!==",
2012
- "<",
2013
- "<=",
2014
- ">",
2015
- ">=",
2016
- "in",
2017
- "instanceof"
2018
- ],
2019
- // NOTE: Extra in-between level for default custom operators
2020
- ["custom"],
2021
- ["<<", ">>", ">>>"],
2022
- ["+", "-"],
2023
- ["*", "/", "%"],
2024
- ["**"]
2025
- ];
2026
- precedenceMap = /* @__PURE__ */ new Map();
2027
- for (let i1 = 0, len = precedenceOrder.length; i1 < len; i1++) {
2028
- const prec = i1;
2029
- const ops = precedenceOrder[i1];
2030
- for (let i2 = 0, len1 = ops.length; i2 < len1; i2++) {
2031
- const op = ops[i2];
2032
- precedenceMap.set(op, prec);
2033
- }
2242
+ condition.children.push(")");
2034
2243
  }
2035
- precedenceStep = 1 / 64;
2036
- precedenceRelational = precedenceMap.get("==");
2037
- precedenceCustomDefault = precedenceMap.get("custom");
2038
- asConst = {
2039
- ts: true,
2040
- children: [" as const"]
2041
- };
2042
2244
  }
2043
- });
2044
-
2045
- // source/parser/pattern-matching.civet
2046
- function processPatternMatching(statements, ReservedWord) {
2047
- gatherRecursiveAll(statements, ($) => $.type === "SwitchStatement").forEach((s) => {
2048
- const { caseBlock } = s;
2049
- const { clauses } = caseBlock;
2050
- for (const c of clauses) {
2051
- if (c.type === "WhenClause" && c.break) {
2052
- const last = c.block?.expressions?.at(-1)?.[1];
2053
- if (isExit(last)) {
2054
- c.children.splice(c.children.indexOf(c.break), 1);
2055
- c.break = void 0;
2056
- }
2245
+ switch (s.type) {
2246
+ case "IfStatement": {
2247
+ const { else: e } = s;
2248
+ const block = blockWithPrefix(condition.expression.blockPrefix, s.then);
2249
+ if (block.bare && e && !block.semicolon) {
2250
+ block.children.push(block.semicolon = ";");
2057
2251
  }
2058
- }
2059
- let errors = false;
2060
- let isPattern = false;
2061
- if (clauses.some(($1) => $1.type === "PatternClause")) {
2062
- isPattern = true;
2063
- clauses.forEach((c) => {
2064
- if (!(c.type === "PatternClause" || c.type === "DefaultClause")) {
2065
- errors = true;
2066
- return c.children.push({
2067
- type: "Error",
2068
- message: "Can't mix pattern matching and non-pattern matching clauses"
2069
- });
2252
+ s.children = s.children.map((c) => {
2253
+ if (c === s.then) {
2254
+ return block;
2255
+ } else {
2256
+ return c;
2070
2257
  }
2071
- ;
2072
- return;
2073
2258
  });
2259
+ s.then = block;
2260
+ updateParentPointers(block, s);
2261
+ break;
2074
2262
  }
2075
- if (errors || !isPattern) {
2076
- return;
2077
- }
2078
- let { condition } = s;
2079
- if (condition.type === "ParenthesizedExpression") {
2080
- condition = condition.expression;
2081
- }
2082
- let hoistDec, refAssignment = [], ref = maybeRef(condition, "m");
2083
- if (ref !== condition) {
2084
- hoistDec = {
2085
- type: "Declaration",
2086
- children: ["let ", ref],
2087
- names: []
2088
- };
2089
- refAssignment = [{
2090
- type: "AssignmentExpression",
2091
- children: [ref, " = ", condition]
2092
- }, ","];
2263
+ case "IterationStatement": {
2264
+ const { children, block } = s;
2265
+ const newBlock = blockWithPrefix(condition.expression.blockPrefix, block);
2266
+ s.children = children.map((c) => c?.type === "BlockStatement" ? newBlock : c);
2267
+ updateParentPointers(newBlock, s);
2268
+ break;
2093
2269
  }
2094
- let prev = [], root = prev;
2095
- const l = clauses.length;
2096
- clauses.forEach((c, i) => {
2097
- if (c.type === "DefaultClause") {
2098
- prev.push(c.block);
2270
+ case "SwitchStatement": {
2271
+ const { blockPrefix, ref: ref2, statementDeclaration } = condition.expression;
2272
+ if (!blockPrefix) {
2099
2273
  return;
2100
2274
  }
2101
- let { patterns, block } = c;
2102
- let pattern = patterns[0];
2103
- const indent = block.expressions?.[0]?.[0] || "";
2104
- const alternativeConditions = patterns.map((pattern2, i2) => {
2105
- const conditions = [];
2106
- getPatternConditions(pattern2, ref, conditions);
2107
- return conditions;
2108
- });
2109
- const conditionExpression = alternativeConditions.map((conditions, i2) => {
2110
- const conditionArray = conditions.map((c2, i3) => {
2111
- if (i3 === 0)
2112
- return c2;
2113
- return [" && ", ...c2];
2114
- });
2115
- if (i2 === 0)
2116
- return conditionArray;
2117
- return [" || ", ...conditionArray];
2118
- });
2119
- const condition2 = {
2275
+ const newCondition = {
2120
2276
  type: "ParenthesizedExpression",
2121
- children: ["(", ...refAssignment, conditionExpression, ")"],
2122
- expression: conditionExpression
2277
+ children: ["(", ref2, ")"],
2278
+ expression: ref2,
2279
+ parent: s
2123
2280
  };
2124
- const prefix = [];
2125
- switch (pattern.type) {
2126
- case "ArrayBindingPattern":
2127
- if (pattern.length === 0)
2128
- break;
2129
- case "ObjectBindingPattern": {
2130
- if (pattern.properties?.length === 0)
2131
- break;
2132
- let [splices, thisAssignments] = gatherBindingCode(pattern);
2133
- const patternBindings = nonMatcherBindings(pattern);
2134
- splices = splices.map((s2) => [", ", nonMatcherBindings(s2)]);
2135
- thisAssignments = thisAssignments.map((a) => [indent, a, ";"]);
2136
- const duplicateDeclarations = aggregateDuplicateBindings([patternBindings, splices], ReservedWord);
2137
- prefix.push([indent, "const ", patternBindings, " = ", ref, splices, ";"]);
2138
- prefix.push(...thisAssignments);
2139
- prefix.push(...duplicateDeclarations.map((d) => [indent, d, ";"]));
2140
- break;
2281
+ s.children = s.children.map(function(c) {
2282
+ if (c === s.condition) {
2283
+ return newCondition;
2284
+ } else {
2285
+ return c;
2141
2286
  }
2142
- }
2143
- block.expressions.unshift(...prefix);
2144
- const next = [];
2145
- braceBlock(block);
2146
- if (i < l - 1)
2147
- next.push("\n", "else ");
2148
- prev.push(["", {
2149
- type: "IfStatement",
2150
- children: ["if", condition2, block, next],
2151
- then: block,
2152
- else: next,
2153
- hoistDec
2154
- }]);
2155
- hoistDec = void 0;
2156
- refAssignment = [];
2157
- return prev = next;
2158
- });
2159
- s.type = "PatternMatchingStatement";
2160
- s.children = [root];
2161
- return addParentPointers(s, s.parent);
2162
- });
2163
- }
2164
- function getPatternConditions(pattern, ref, conditions) {
2165
- if (pattern.rest)
2166
- return;
2167
- switch (pattern.type) {
2168
- case "ArrayBindingPattern": {
2169
- const { elements, length } = pattern, hasRest = elements.some((e) => e.rest), comparator = hasRest ? " >= " : " === ", l = [comparator, (length - hasRest).toString()];
2170
- conditions.push(
2171
- ["Array.isArray(", ref, ")"],
2172
- [ref, ".length", l]
2173
- );
2174
- elements.forEach(({ children: [, e] }, i) => {
2175
- const subRef = [ref, "[", i.toString(), "]"];
2176
- return getPatternConditions(e, subRef, conditions);
2177
2287
  });
2178
- const { blockPrefix } = pattern;
2179
- if (blockPrefix) {
2180
- const postElements = blockPrefix.children[1], { length: postLength } = postElements;
2181
- postElements.forEach(({ children: [, e] }, i) => {
2182
- const subRef = [ref, "[", ref, ".length - ", (postLength + i).toString(), "]"];
2183
- return getPatternConditions(e, subRef, conditions);
2184
- });
2288
+ s.condition = newCondition;
2289
+ updateParentPointers(s);
2290
+ if (statementDeclaration) {
2291
+ const block = makeEmptyBlock();
2292
+ replaceBlockExpression(s.parent, s, block);
2293
+ block.expressions.push(["", s]);
2294
+ s.children.splice(s.children.findIndex(($1) => $1.token === "switch"), 0, blockPrefix);
2295
+ s.parent = block;
2296
+ } else {
2297
+ const block = blockWithPrefix([["", [{
2298
+ type: "Declaration",
2299
+ children: ["let ", ...condition.expression.children]
2300
+ }], ";"], ...blockPrefix], makeEmptyBlock());
2301
+ updateParentPointers(block, s.parent);
2302
+ replaceBlockExpression(s.parent, s, block);
2303
+ block.expressions.push(["", s]);
2304
+ s.parent = block;
2185
2305
  }
2306
+ ;
2186
2307
  break;
2187
2308
  }
2188
- case "ObjectBindingPattern": {
2189
- conditions.push(
2190
- ["typeof ", ref, " === 'object'"],
2191
- [ref, " != null"]
2192
- );
2193
- pattern.properties.forEach((p) => {
2194
- switch (p.type) {
2195
- case "PinProperty":
2196
- case "BindingProperty": {
2197
- const { name, value } = p;
2198
- let subRef;
2199
- switch (name.type) {
2200
- case "ComputedPropertyName":
2201
- conditions.push([name.expression, " in ", ref]);
2202
- subRef = [ref, name];
2203
- break;
2204
- case "Literal":
2205
- case "StringLiteral":
2206
- case "NumericLiteral":
2207
- conditions.push([name, " in ", ref]);
2208
- subRef = [ref, "[", name, "]"];
2209
- break;
2210
- default:
2211
- conditions.push(["'", name, "' in ", ref]);
2212
- subRef = [ref, ".", name];
2213
- }
2214
- if (value) {
2215
- getPatternConditions(value, subRef, conditions);
2216
- }
2217
- break;
2218
- }
2219
- }
2220
- });
2221
- break;
2222
- }
2223
- case "ConditionFragment": {
2224
- let { children } = pattern;
2225
- if (children.length) {
2226
- let [first, ...rest] = children;
2227
- let [ws, ...op] = first;
2228
- ws = [" "].concat(ws);
2229
- first = [ws, ...op];
2230
- children = [first, ...rest];
2231
- }
2232
- conditions.push(
2233
- processBinaryOpExpression([ref, children])
2234
- );
2235
- break;
2236
- }
2237
- case "RegularExpressionLiteral": {
2238
- conditions.push(
2239
- ["typeof ", ref, " === 'string'"],
2240
- [pattern, ".test(", ref, ")"]
2241
- );
2242
- break;
2243
- }
2244
- case "PinPattern":
2245
- conditions.push([
2246
- ref,
2247
- " === ",
2248
- pattern.expression
2249
- ]);
2250
- break;
2251
- case "Literal":
2252
- conditions.push([
2253
- ref,
2254
- " === ",
2255
- pattern
2256
- ]);
2257
- break;
2258
- default:
2259
- break;
2260
2309
  }
2261
2310
  }
2262
- function elideMatchersFromArrayBindings(elements) {
2263
- return elements.map((el) => {
2264
- if (el.type === "BindingRestElement") {
2265
- return ["", el, void 0];
2266
- }
2267
- const { children: [ws, e, delim] } = el;
2268
- switch (e.type) {
2269
- case "Literal":
2270
- case "RegularExpressionLiteral":
2271
- case "StringLiteral":
2272
- case "PinPattern":
2273
- return delim;
2274
- default:
2275
- return [ws, nonMatcherBindings(e), delim];
2276
- }
2277
- });
2278
- }
2279
- function elideMatchersFromPropertyBindings(properties) {
2280
- return properties.map((p) => {
2281
- switch (p.type) {
2282
- case "BindingProperty": {
2283
- const { children, name, value } = p;
2284
- const [ws] = children;
2285
- switch (value && value.type) {
2286
- case "ArrayBindingPattern":
2287
- case "ObjectBindingPattern":
2288
- return {
2289
- ...p,
2290
- children: [ws, name, ": ", nonMatcherBindings(value), p.delim]
2291
- };
2292
- case "Identifier":
2293
- return p;
2294
- case "Literal":
2295
- case "RegularExpressionLiteral":
2296
- case "StringLiteral":
2297
- default:
2298
- return {
2299
- ...p,
2300
- children: [ws, name, p.delim]
2301
- };
2302
- }
2311
+ var init_declaration = __esm({
2312
+ "source/parser/declaration.civet"() {
2313
+ "use strict";
2314
+ init_block();
2315
+ init_traversal();
2316
+ init_pattern_matching();
2317
+ init_util();
2318
+ init_function();
2319
+ init_binding();
2320
+ }
2321
+ });
2322
+
2323
+ // source/parser/unary.civet
2324
+ function processUnaryExpression(pre, exp, post) {
2325
+ if (!(pre.length || post))
2326
+ return exp;
2327
+ if (post?.token === "?") {
2328
+ post = {
2329
+ $loc: post.$loc,
2330
+ token: " != null"
2331
+ };
2332
+ if (pre.length) {
2333
+ const lastPre = pre[pre.length - 1];
2334
+ if (lastPre.token === "!") {
2335
+ post.token = " == null";
2336
+ pre = pre.slice(0, -1);
2337
+ } else if (lastPre.length === 2 && lastPre[0].token === "!") {
2338
+ post.token = " == null";
2339
+ pre = pre.slice(0, -1);
2303
2340
  }
2304
- case "PinProperty":
2305
- case "BindingRestProperty":
2306
- default:
2307
- return p;
2308
2341
  }
2309
- });
2310
- }
2311
- function nonMatcherBindings(pattern) {
2312
- switch (pattern.type) {
2313
- case "ArrayBindingPattern": {
2314
- const elements = elideMatchersFromArrayBindings(pattern.elements);
2315
- const children = ["[", elements, "]"];
2342
+ const existence = {
2343
+ type: "Existence",
2344
+ expression: exp,
2345
+ children: [exp, post]
2346
+ };
2347
+ exp = makeLeftHandSideExpression(existence);
2348
+ if (pre.length) {
2316
2349
  return {
2317
- ...pattern,
2318
- children,
2319
- elements
2350
+ type: "UnaryExpression",
2351
+ children: [...pre, exp]
2320
2352
  };
2321
2353
  }
2322
- case "PostRestBindingElements": {
2323
- const els = elideMatchersFromArrayBindings(pattern.children[1]);
2324
- return {
2325
- ...pattern,
2326
- children: [
2327
- pattern.children[0],
2328
- els,
2329
- ...pattern.children.slice(2)
2330
- ]
2331
- };
2354
+ return exp;
2355
+ }
2356
+ if (exp.type === "Literal") {
2357
+ if (pre.length === 1) {
2358
+ const { token } = pre[0];
2359
+ if (token === "-" || token === "+") {
2360
+ const children = [pre[0], ...exp.children];
2361
+ if (post)
2362
+ exp.children.push(post);
2363
+ return {
2364
+ type: "Literal",
2365
+ children,
2366
+ raw: `${token}${exp.raw}`
2367
+ };
2368
+ }
2332
2369
  }
2333
- case "ObjectBindingPattern":
2334
- return ["{", elideMatchersFromPropertyBindings(pattern.properties), "}"];
2335
- default:
2336
- return pattern;
2337
2370
  }
2338
- }
2339
- function aggregateDuplicateBindings(bindings, ReservedWord) {
2340
- const props = gatherRecursiveAll(bindings, ($2) => $2.type === "BindingProperty");
2341
- const arrayBindings = gatherRecursiveAll(bindings, ($3) => $3.type === "ArrayBindingPattern");
2342
- arrayBindings.forEach((a) => {
2343
- const { elements } = a;
2344
- return elements.forEach((element) => {
2345
- if (Array.isArray(element)) {
2346
- const [, e] = element;
2347
- if (e.type === "Identifier") {
2348
- return props.push(e);
2349
- } else if (e.type === "BindingRestElement") {
2350
- return props.push(e);
2371
+ let ref;
2372
+ while (ref = pre.length) {
2373
+ const l = ref;
2374
+ const last = pre[l - 1];
2375
+ if (last.type === "Await") {
2376
+ if (last.op) {
2377
+ if (exp.type !== "ParenthesizedExpression") {
2378
+ exp = ["(", exp, ")"];
2351
2379
  }
2352
- ;
2353
- return;
2380
+ exp = {
2381
+ type: "CallExpression",
2382
+ children: [...last.children, "Promise", last.op, exp]
2383
+ };
2384
+ pre = pre.slice(0, -1);
2385
+ } else {
2386
+ exp = {
2387
+ type: "AwaitExpression",
2388
+ children: [...last.children, exp]
2389
+ };
2390
+ pre = pre.slice(0, -1);
2354
2391
  }
2355
- ;
2356
- return;
2357
- });
2358
- });
2359
- const declarations = [];
2360
- const propsGroupedByName = /* @__PURE__ */ new Map();
2361
- for (const p of props) {
2362
- const { name, value } = p;
2363
- const key = value?.name || name?.name || name;
2364
- if (propsGroupedByName.has(key)) {
2365
- propsGroupedByName.get(key).push(p);
2366
2392
  } else {
2367
- propsGroupedByName.set(key, [p]);
2393
+ break;
2368
2394
  }
2369
2395
  }
2370
- propsGroupedByName.forEach((shared, key) => {
2371
- if (!key) {
2372
- return;
2373
- }
2374
- if (ReservedWord({ fail() {
2375
- } }, {
2376
- pos: 0,
2377
- input: key
2378
- })) {
2379
- shared.forEach((p) => {
2380
- return aliasBinding(p, makeRef(`_${key}`, key));
2381
- });
2382
- return;
2383
- }
2384
- if (shared.length === 1) {
2385
- return;
2386
- }
2387
- const refs = shared.map((p) => {
2388
- const ref = makeRef(key);
2389
- aliasBinding(p, ref);
2390
- return ref;
2391
- });
2392
- return declarations.push(["const ", key, " = [", ...refs.map((r, i) => {
2393
- return i === 0 ? r : [", ", r];
2394
- }), "]"]);
2395
- });
2396
- return declarations;
2397
- }
2398
- function processDeclarationCondition(condition, rootCondition, parent) {
2399
- if (!(condition.type === "DeclarationCondition")) {
2400
- return;
2401
- }
2402
- const ref = makeRef();
2403
- const { decl, bindings } = condition.declaration;
2404
- const binding = bindings[0];
2405
- const { pattern, suffix, initializer, splices, thisAssignments } = binding;
2406
- const grandparent = condition.parent?.parent;
2407
- const children = (
2408
- // Check that the declaration is a plain assignment (no pattern-matching) and the immediate grandchild of an `if` or `while`
2409
- // More complex conditions (triggered by pattern matching or `until`/`unless`) don't need double parens
2410
- // @ts-ignore Just because pattern might not have a type at runtime doesn't mean it's unsafe
2411
- pattern.type === "Identifier" && (grandparent?.type === "IfStatement" || grandparent?.type === "WhileStatement") ? ["(", ref, initializer, ")"] : [ref, initializer]
2412
- );
2413
- Object.assign(condition, {
2414
- type: "AssignmentExpression",
2415
- children,
2416
- hoistDec: {
2417
- type: "Declaration",
2418
- children: ["let ", ref, suffix],
2419
- names: []
2420
- },
2421
- pattern,
2422
- ref
2423
- });
2424
- addParentPointers(condition, parent);
2425
- Object.assign(rootCondition, {
2426
- blockPrefix: [
2427
- ["", [decl, pattern, suffix, " = ", ref, ...splices], ";"],
2428
- ...thisAssignments
2429
- ]
2430
- });
2431
- }
2432
- function processDeclarationConditions(node) {
2433
- gatherRecursiveAll(node, (n) => {
2434
- return n.type === "IfStatement" || n.type === "IterationStatement" || n.type === "SwitchStatement";
2435
- }).forEach(processDeclarationConditionStatement);
2396
+ return {
2397
+ type: "UnaryExpression",
2398
+ children: [...pre, exp, post]
2399
+ };
2436
2400
  }
2437
- function processDeclarationConditionStatement(s) {
2438
- const { condition } = s;
2439
- if (!condition?.expression) {
2440
- return;
2401
+ var init_unary = __esm({
2402
+ "source/parser/unary.civet"() {
2403
+ "use strict";
2404
+ init_util();
2441
2405
  }
2442
- let { expression } = condition;
2443
- if (typeof expression === "object" && expression != null && "type" in expression && expression.type === "UnaryExpression" && "children" in expression && Array.isArray(expression.children) && expression.children.length === 2 && expression.children[0] === "!" && typeof expression.children[1] === "object" && expression.children[1] != null && "type" in expression.children[1] && expression.children[1].type === "ParenthesizedExpression" && "expression" in expression.children[1]) {
2444
- const { type: type1, children: [, { type: type2, expression: expression2 }] } = expression;
2445
- const type = [type1, type2];
2446
- expression = expression2;
2406
+ });
2407
+
2408
+ // source/parser/pipe.civet
2409
+ function constructInvocation(fn, arg) {
2410
+ const fnArr = [fn.leadingComment, fn.expr, fn.trailingComment];
2411
+ let expr = fn.expr;
2412
+ while (expr.type === "ParenthesizedExpression") {
2413
+ expr = expr.expression;
2447
2414
  }
2448
- processDeclarationCondition(expression, condition.expression, s);
2449
- const { ref, pattern } = expression;
2450
- if (pattern) {
2451
- let conditions = [];
2452
- getPatternConditions(pattern, ref, conditions);
2453
- conditions = conditions.filter((c) => {
2454
- return !(c.length === 3 && c[0] === "typeof " && c[1] === ref && c[2] === " === 'object'") && !(c.length === 2 && c[0] === ref && c[1] === " != null");
2415
+ if (expr.ampersandBlock) {
2416
+ const { ref, body } = expr;
2417
+ ref.type = "PipedExpression";
2418
+ ref.children = [makeLeftHandSideExpression(arg)];
2419
+ updateParentPointers(ref);
2420
+ return makeNode({
2421
+ type: "UnwrappedExpression",
2422
+ children: [skipIfOnlyWS(fn.leadingComment), body, skipIfOnlyWS(fn.trailingComment)]
2455
2423
  });
2456
- if (conditions.length) {
2457
- condition.children.unshift("(");
2458
- conditions.forEach(function(c) {
2459
- return condition.children.push(" && ", c);
2460
- });
2461
- condition.children.push(")");
2462
- }
2463
2424
  }
2464
- switch (s.type) {
2465
- case "IfStatement": {
2466
- const { else: e } = s;
2467
- const block = blockWithPrefix(condition.expression.blockPrefix, s.then);
2468
- s.then = block;
2469
- if (block.bare && e && !block.semicolon) {
2470
- block.children.push(block.semicolon = ";");
2425
+ expr = fn.expr;
2426
+ const lhs = makeLeftHandSideExpression(expr);
2427
+ let comment = skipIfOnlyWS(fn.trailingComment);
2428
+ if (comment)
2429
+ lhs.children.splice(2, 0, comment);
2430
+ comment = skipIfOnlyWS(fn.leadingComment);
2431
+ if (comment)
2432
+ lhs.children.splice(1, 0, comment);
2433
+ switch (arg.type) {
2434
+ case "CommaExpression":
2435
+ arg = makeLeftHandSideExpression(arg);
2436
+ break;
2437
+ }
2438
+ return {
2439
+ type: "CallExpression",
2440
+ children: [lhs, "(", arg, ")"]
2441
+ };
2442
+ }
2443
+ function constructPipeStep(fn, arg, returning) {
2444
+ let children = [[fn.leadingComment, fn.expr, fn.trailingComment].map(skipIfOnlyWS), " ", arg];
2445
+ switch (fn.expr.token) {
2446
+ case "yield":
2447
+ case "await":
2448
+ if (fn.expr.op) {
2449
+ children = processUnaryExpression([fn.expr], arg, void 0);
2450
+ }
2451
+ if (returning) {
2452
+ return [
2453
+ children,
2454
+ returning
2455
+ ];
2456
+ }
2457
+ return [
2458
+ children,
2459
+ null
2460
+ ];
2461
+ case "return":
2462
+ return [{
2463
+ type: "ReturnStatement",
2464
+ children
2465
+ }, null];
2466
+ }
2467
+ if (returning) {
2468
+ return [
2469
+ constructInvocation(fn, arg),
2470
+ returning
2471
+ ];
2472
+ }
2473
+ return [constructInvocation(fn, arg), null];
2474
+ }
2475
+ function processPipelineExpressions(statements) {
2476
+ gatherRecursiveAll(statements, (n) => n.type === "PipelineExpression").forEach((s) => {
2477
+ const [ws, , body] = s.children;
2478
+ let [, arg] = s.children;
2479
+ let i = 0, l = body.length;
2480
+ const children = [ws];
2481
+ let usingRef = null;
2482
+ for (i = 0; i < l; i++) {
2483
+ const step = body[i];
2484
+ const [leadingComment, pipe, trailingComment, expr] = step;
2485
+ const returns = pipe.token === "||>";
2486
+ let ref, result, returning = returns ? arg : null;
2487
+ if (pipe.token === "|>=") {
2488
+ let initRef;
2489
+ if (i === 0) {
2490
+ outer:
2491
+ switch (arg.type) {
2492
+ case "MemberExpression":
2493
+ if (arg.children.length <= 2)
2494
+ break;
2495
+ case "CallExpression":
2496
+ const access = arg.children.pop();
2497
+ switch (access.type) {
2498
+ case "PropertyAccess":
2499
+ case "SliceExpression":
2500
+ break;
2501
+ default:
2502
+ children.unshift({
2503
+ type: "Error",
2504
+ $loc: pipe.token.$loc,
2505
+ message: `Can't assign to ${access.type}`
2506
+ });
2507
+ arg.children.push(access);
2508
+ break outer;
2509
+ }
2510
+ usingRef = makeRef();
2511
+ initRef = {
2512
+ type: "AssignmentExpression",
2513
+ children: [usingRef, " = ", arg, ","]
2514
+ };
2515
+ arg = {
2516
+ type: "MemberExpression",
2517
+ children: [usingRef, access]
2518
+ };
2519
+ break;
2520
+ }
2521
+ const lhs = [[
2522
+ [initRef],
2523
+ arg,
2524
+ [],
2525
+ { token: "=", children: [" = "] }
2526
+ ]];
2527
+ Object.assign(s, {
2528
+ type: "AssignmentExpression",
2529
+ children: [lhs, children],
2530
+ names: null,
2531
+ lhs,
2532
+ assigned: arg,
2533
+ exp: children
2534
+ });
2535
+ arg = clone(arg);
2536
+ if (arg.children[0].type === "Ref") {
2537
+ arg.children[0] = usingRef;
2538
+ }
2539
+ } else {
2540
+ children.unshift({
2541
+ type: "Error",
2542
+ $loc: pipe.token.$loc,
2543
+ message: "Can't use |>= in the middle of a pipeline"
2544
+ });
2545
+ }
2546
+ } else {
2547
+ if (i === 0)
2548
+ s.children = children;
2549
+ }
2550
+ if (returns && (ref = needsRef(arg))) {
2551
+ usingRef = usingRef || ref;
2552
+ arg = {
2553
+ type: "ParenthesizedExpression",
2554
+ children: ["(", {
2555
+ type: "AssignmentExpression",
2556
+ children: [usingRef, " = ", arg]
2557
+ }, ")"]
2558
+ };
2559
+ returning = usingRef;
2560
+ }
2561
+ ;
2562
+ [result, returning] = constructPipeStep(
2563
+ {
2564
+ leadingComment: skipIfOnlyWS(leadingComment),
2565
+ trailingComment: skipIfOnlyWS(trailingComment),
2566
+ expr
2567
+ },
2568
+ arg,
2569
+ returning
2570
+ );
2571
+ if (result.type === "ReturnStatement") {
2572
+ if (i < l - 1) {
2573
+ result.children.push({
2574
+ type: "Error",
2575
+ message: "Can't continue a pipeline after returning"
2576
+ });
2577
+ }
2578
+ arg = result;
2579
+ if (children[children.length - 1] === ",") {
2580
+ children.pop();
2581
+ children.push(";");
2582
+ }
2583
+ break;
2471
2584
  }
2472
- s.children.splice(2, 1, block);
2473
- updateParentPointers(block, s);
2474
- break;
2475
- }
2476
- case "IterationStatement": {
2477
- const { children, block } = s;
2478
- const newBlock = blockWithPrefix(condition.expression.blockPrefix, block);
2479
- s.children = children.map((c) => c?.type === "BlockStatement" ? newBlock : c);
2480
- updateParentPointers(newBlock, s);
2481
- break;
2482
- }
2483
- case "SwitchStatement": {
2484
- const { blockPrefix, ref: ref2 } = condition.expression;
2485
- if (!blockPrefix) {
2486
- return;
2585
+ if (returning) {
2586
+ arg = returning;
2587
+ children.push(result, ",");
2588
+ } else {
2589
+ arg = result;
2487
2590
  }
2488
- s.condition = {
2489
- type: "ParenthesizedExpression",
2490
- children: ["(", ref2, ")"],
2491
- expression: ref2,
2492
- parent: s
2493
- };
2494
- s.children[1] = s.condition;
2495
- updateParentPointers(s);
2496
- const block = blockWithPrefix([["", [{
2591
+ }
2592
+ if (usingRef) {
2593
+ s.hoistDec = {
2497
2594
  type: "Declaration",
2498
- children: ["let ", ...condition.expression.children]
2499
- }], ";"], ...blockPrefix], makeEmptyBlock());
2500
- updateParentPointers(block, s.parent);
2501
- replaceBlockExpression(s.parent, s, block);
2502
- block.expressions.push(["", s]);
2503
- s.parent = block;
2504
- break;
2595
+ children: ["let ", usingRef],
2596
+ names: []
2597
+ };
2505
2598
  }
2506
- }
2507
- }
2508
- function aliasBinding(p, ref) {
2509
- if (p.type === "Identifier") {
2510
- p.children[0] = ref;
2511
- } else if (p.type === "BindingRestElement") {
2512
- aliasBinding(p.binding, ref);
2513
- } else if (p.value?.type === "Identifier") {
2514
- aliasBinding(p.value, ref);
2515
- } else {
2516
- p.value = ref;
2517
- const index = p.children.indexOf(p.name);
2518
- p.children.splice(index + 1, 0, ": ", ref);
2519
- }
2599
+ children.push(arg);
2600
+ if (!children.some(($) => $?.type === "ReturnStatement") && children.some(($1) => $1 === ",")) {
2601
+ const { parent } = s;
2602
+ const parenthesizedExpression = makeLeftHandSideExpression({ ...s });
2603
+ Object.assign(s, parenthesizedExpression, {
2604
+ parent,
2605
+ hoistDec: void 0
2606
+ });
2607
+ }
2608
+ return addParentPointers(s, s.parent);
2609
+ });
2520
2610
  }
2521
- var init_pattern_matching = __esm({
2522
- "source/parser/pattern-matching.civet"() {
2611
+ var init_pipe = __esm({
2612
+ "source/parser/pipe.civet"() {
2523
2613
  "use strict";
2524
2614
  init_traversal();
2525
2615
  init_util();
2526
- init_block();
2527
- init_binding();
2528
- init_op();
2616
+ init_unary();
2529
2617
  }
2530
2618
  });
2531
2619
 
2532
- // source/parser/unary.civet
2533
- function processUnaryExpression(pre, exp, post) {
2534
- if (!(pre.length || post))
2535
- return exp;
2536
- if (post?.token === "?") {
2537
- post = {
2538
- $loc: post.$loc,
2539
- token: " != null"
2540
- };
2541
- if (pre.length) {
2542
- const lastPre = pre[pre.length - 1];
2543
- if (lastPre.token === "!") {
2544
- post.token = " == null";
2545
- pre = pre.slice(0, -1);
2546
- } else if (lastPre.length === 2 && lastPre[0].token === "!") {
2547
- post.token = " == null";
2548
- pre = pre.slice(0, -1);
2620
+ // source/parser/for.civet
2621
+ function forRange(open, forDeclaration, range, stepExp, close) {
2622
+ const { start, end, inclusive } = range;
2623
+ const counterRef = makeRef("i");
2624
+ let stepRef;
2625
+ if (stepExp) {
2626
+ stepExp = insertTrimmingSpace(stepExp, "");
2627
+ stepRef = maybeRef(stepExp, "step");
2628
+ }
2629
+ const startRef = maybeRef(start, "start");
2630
+ const endRef = maybeRef(end, "end");
2631
+ const startRefDec = startRef !== start ? [startRef, " = ", start, ", "] : [];
2632
+ const endRefDec = endRef !== end ? [endRef, " = ", end, ", "] : [];
2633
+ let ascDec = [], ascRef, asc;
2634
+ if (stepRef) {
2635
+ if (stepRef !== stepExp) {
2636
+ ascDec = [", ", stepRef, " = ", stepExp];
2637
+ }
2638
+ } else if (start.type === "Literal" && end.type === "Literal") {
2639
+ asc = literalValue(start) <= literalValue(end);
2640
+ } else {
2641
+ ascRef = makeRef("asc");
2642
+ ascDec = [", ", ascRef, " = ", startRef, " <= ", endRef];
2643
+ }
2644
+ let varAssign = [], varLetAssign = varAssign, varLet = varAssign, blockPrefix;
2645
+ if (forDeclaration?.declare) {
2646
+ if (forDeclaration.declare.token === "let") {
2647
+ const varName = forDeclaration.children.splice(1);
2648
+ varAssign = [...insertTrimmingSpace(varName, ""), " = "];
2649
+ varLet = [",", ...varName, " = ", counterRef];
2650
+ } else {
2651
+ blockPrefix = [
2652
+ ["", forDeclaration, " = ", counterRef, ";"]
2653
+ ];
2654
+ }
2655
+ } else if (forDeclaration) {
2656
+ varAssign = varLetAssign = [forDeclaration, " = "];
2657
+ }
2658
+ const declaration = {
2659
+ type: "Declaration",
2660
+ children: ["let ", ...startRefDec, ...endRefDec, counterRef, " = ", ...varLetAssign, startRef, ...varLet, ...ascDec],
2661
+ names: forDeclaration?.names
2662
+ };
2663
+ const counterPart = inclusive ? [counterRef, " <= ", endRef, " : ", counterRef, " >= ", endRef] : [counterRef, " < ", endRef, " : ", counterRef, " > ", endRef];
2664
+ const condition = stepRef ? [stepRef, " !== 0 && (", stepRef, " > 0 ? ", ...counterPart, ")"] : ascRef ? [ascRef, " ? ", ...counterPart] : asc ? counterPart.slice(0, 3) : counterPart.slice(4);
2665
+ const increment = stepRef ? [...varAssign, counterRef, " += ", stepRef] : ascRef ? [...varAssign, ascRef, " ? ++", counterRef, " : --", counterRef] : [...varAssign, asc ? "++" : "--", counterRef];
2666
+ return {
2667
+ declaration,
2668
+ children: [open, declaration, "; ", ...condition, "; ", ...increment, close],
2669
+ blockPrefix
2670
+ };
2671
+ }
2672
+ function processForInOf($0, getRef) {
2673
+ let [awaits, eachOwn, open, declaration, declaration2, ws, inOf, exp, step, close] = $0;
2674
+ if (exp.type === "RangeExpression" && inOf.token === "of" && !declaration2) {
2675
+ return forRange(open, declaration, exp, step, close);
2676
+ } else if (step) {
2677
+ throw new Error("for..of/in cannot use 'by' except with range literals");
2678
+ }
2679
+ let eachOwnError;
2680
+ let hoistDec, blockPrefix = [];
2681
+ if (eachOwn && eachOwn[0].token === "each") {
2682
+ if (inOf.token === "of") {
2683
+ const counterRef = makeRef("i");
2684
+ const lenRef = makeRef("len");
2685
+ const expRef2 = maybeRef(exp);
2686
+ const increment = "++";
2687
+ let assignmentNames = [...declaration.names];
2688
+ if (declaration2) {
2689
+ const [, , ws22, decl22] = declaration2;
2690
+ blockPrefix.push(["", [
2691
+ insertTrimmingSpace(ws22, ""),
2692
+ decl22,
2693
+ " = ",
2694
+ counterRef
2695
+ ], ";"]);
2696
+ assignmentNames.push(...decl22.names);
2549
2697
  }
2698
+ const expRefDec = expRef2 !== exp ? [insertTrimmingSpace(expRef2, " "), " = ", insertTrimmingSpace(exp, ""), ", "] : [];
2699
+ blockPrefix.push(["", {
2700
+ type: "Declaration",
2701
+ children: [declaration, " = ", insertTrimmingSpace(expRef2, ""), "[", counterRef, "]"],
2702
+ names: assignmentNames
2703
+ }, ";"]);
2704
+ declaration = {
2705
+ type: "Declaration",
2706
+ children: ["let ", ...expRefDec, counterRef, " = 0, ", lenRef, " = ", insertTrimmingSpace(expRef2, ""), ".length"],
2707
+ names: []
2708
+ };
2709
+ const condition = [counterRef, " < ", lenRef, "; "];
2710
+ const children = [open, declaration, "; ", condition, counterRef, increment, close];
2711
+ return { declaration, children, blockPrefix };
2712
+ } else {
2713
+ eachOwnError = {
2714
+ type: "Error",
2715
+ message: "'each' is only meaningful in for..of loops"
2716
+ };
2550
2717
  }
2551
- const existence = {
2552
- type: "Existence",
2553
- expression: exp,
2554
- children: [exp, post]
2718
+ }
2719
+ let own = eachOwn && eachOwn[0].token === "own";
2720
+ let expRef;
2721
+ if (own && inOf.token !== "in") {
2722
+ own = false;
2723
+ eachOwnError = {
2724
+ type: "Error",
2725
+ message: "'own' is only meaningful in for..in loops"
2555
2726
  };
2556
- exp = makeLeftHandSideExpression(existence);
2557
- if (pre.length) {
2558
- return {
2559
- type: "UnaryExpression",
2560
- children: [...pre, exp]
2727
+ }
2728
+ if (!declaration2 && !own) {
2729
+ return {
2730
+ declaration,
2731
+ blockPrefix,
2732
+ children: [awaits, eachOwnError, open, declaration, ws, inOf, expRef ?? exp, step, close]
2733
+ // omit declaration2, replace eachOwn with eachOwnError, replace exp with expRef
2734
+ };
2735
+ }
2736
+ let ws2, decl2;
2737
+ if (declaration2)
2738
+ [, , ws2, decl2] = declaration2;
2739
+ switch (inOf.token) {
2740
+ case "of": {
2741
+ const counterRef = makeRef("i");
2742
+ hoistDec = {
2743
+ type: "Declaration",
2744
+ children: ["let ", counterRef, " = 0"],
2745
+ names: []
2561
2746
  };
2747
+ blockPrefix.push(["", {
2748
+ type: "Declaration",
2749
+ children: [insertTrimmingSpace(ws2, ""), decl2, " = ", counterRef, "++"],
2750
+ names: decl2.names
2751
+ }, ";"]);
2752
+ break;
2562
2753
  }
2563
- return exp;
2564
- }
2565
- if (exp.type === "Literal") {
2566
- if (pre.length === 1) {
2567
- const { token } = pre[0];
2568
- if (token === "-" || token === "+") {
2569
- const children = [pre[0], ...exp.children];
2570
- if (post)
2571
- exp.children.push(post);
2572
- return {
2573
- type: "Literal",
2574
- children,
2575
- raw: `${token}${exp.raw}`
2754
+ case "in": {
2755
+ const expRef2 = maybeRef(exp);
2756
+ if (expRef2 !== exp) {
2757
+ hoistDec = {
2758
+ type: "Declaration",
2759
+ children: ["let ", expRef2],
2760
+ names: []
2761
+ };
2762
+ exp = {
2763
+ type: "AssignmentExpression",
2764
+ children: [" ", expRef2, " =", exp]
2765
+ };
2766
+ }
2767
+ let { binding } = declaration;
2768
+ if (binding?.type !== "Identifier") {
2769
+ const keyRef = makeRef("key");
2770
+ blockPrefix.push(["", [
2771
+ declaration,
2772
+ " = ",
2773
+ keyRef
2774
+ ], ";"]);
2775
+ declaration = {
2776
+ type: "ForDeclaration",
2777
+ binding: binding = keyRef,
2778
+ children: ["const ", keyRef],
2779
+ names: []
2576
2780
  };
2577
2781
  }
2578
- }
2579
- }
2580
- const l = pre.length;
2581
- if (l) {
2582
- const last = pre[l - 1];
2583
- if (last.type === "Await" && last.op) {
2584
- if (exp.type !== "ParenthesizedExpression") {
2585
- exp = ["(", exp, ")"];
2782
+ if (own) {
2783
+ const hasPropRef = getRef("hasProp");
2784
+ blockPrefix.push(["", ["if (!", hasPropRef, "(", insertTrimmingSpace(expRef2, ""), ", ", insertTrimmingSpace(binding, ""), ")) continue"], ";"]);
2586
2785
  }
2587
- exp = {
2588
- type: "CallExpression",
2589
- children: [" Promise", last.op, exp]
2590
- };
2786
+ if (decl2) {
2787
+ blockPrefix.push(["", {
2788
+ type: "Declaration",
2789
+ children: [insertTrimmingSpace(ws2, ""), decl2, " = ", insertTrimmingSpace(expRef2, ""), "[", insertTrimmingSpace(binding, ""), "]"],
2790
+ names: decl2.names
2791
+ }, ";"]);
2792
+ }
2793
+ break;
2591
2794
  }
2795
+ default:
2796
+ (() => {
2797
+ throw new Error(`for item, index must use 'of' or 'in' instead of '${inOf.token}'`);
2798
+ })();
2592
2799
  }
2593
2800
  return {
2594
- type: "UnaryExpression",
2595
- children: [...pre, exp, post]
2801
+ declaration,
2802
+ children: [awaits, eachOwnError, open, declaration, ws, inOf, exp, step, close],
2803
+ // omit declaration2, replace each with eachOwnError
2804
+ blockPrefix,
2805
+ hoistDec
2596
2806
  };
2597
2807
  }
2598
- var init_unary = __esm({
2599
- "source/parser/unary.civet"() {
2808
+ var init_for = __esm({
2809
+ "source/parser/for.civet"() {
2600
2810
  "use strict";
2601
2811
  init_util();
2602
2812
  }
@@ -2921,7 +3131,6 @@ __export(lib_exports, {
2921
3131
  dedentBlockString: () => dedentBlockString,
2922
3132
  dedentBlockSubstitutions: () => dedentBlockSubstitutions,
2923
3133
  deepCopy: () => deepCopy,
2924
- expressionizeIfClause: () => expressionizeIfClause,
2925
3134
  expressionizeTypeIf: () => expressionizeTypeIf,
2926
3135
  forRange: () => forRange,
2927
3136
  gatherBindingCode: () => gatherBindingCode,
@@ -2956,6 +3165,7 @@ __export(lib_exports, {
2956
3165
  quoteString: () => quoteString,
2957
3166
  reorderBindingRestProperty: () => reorderBindingRestProperty,
2958
3167
  replaceNodes: () => replaceNodes,
3168
+ skipImplicitArguments: () => skipImplicitArguments,
2959
3169
  typeOfJSX: () => typeOfJSX,
2960
3170
  wrapIIFE: () => wrapIIFE
2961
3171
  });
@@ -2994,16 +3204,71 @@ function negateCondition(condition) {
2994
3204
  };
2995
3205
  return { ...condition, expression, children };
2996
3206
  }
2997
- function expressionizeIfClause(clause, b, e) {
2998
- const { condition } = clause;
3207
+ function isExpression(node) {
3208
+ if (Array.isArray(node)) {
3209
+ return node.every(isExpression);
3210
+ }
3211
+ if (typeof node === "string") {
3212
+ return true;
3213
+ }
3214
+ switch (node?.type) {
3215
+ case "BlockStatement":
3216
+ case "DebuggerStatement":
3217
+ case "Declaration":
3218
+ case "IfStatement":
3219
+ case "IterationStatement":
3220
+ case "ReturnStatement":
3221
+ case "SwitchStatement":
3222
+ case "ThrowStatement":
3223
+ case "TryStatement":
3224
+ return false;
3225
+ }
3226
+ return true;
3227
+ }
3228
+ function expressionizeBlock(blockOrExpression) {
3229
+ let ref1;
3230
+ if ((ref1 = blockOrExpression) && "expressions" in ref1) {
3231
+ const { expressions } = ref1;
3232
+ const l = expressions.length;
3233
+ const results = [];
3234
+ let i1 = 0;
3235
+ for (const [ws, s, _delim] of expressions) {
3236
+ const i = i1++;
3237
+ if (!isExpression(s))
3238
+ return;
3239
+ const wrapped = makeLeftHandSideExpression(s);
3240
+ if (i === l - 1) {
3241
+ results.push([ws, wrapped]);
3242
+ } else {
3243
+ results.push([ws, wrapped, ","]);
3244
+ }
3245
+ }
3246
+ if (results.length > 1) {
3247
+ return makeLeftHandSideExpression(results);
3248
+ }
3249
+ return results;
3250
+ } else {
3251
+ return blockOrExpression;
3252
+ }
3253
+ }
3254
+ function expressionizeIfStatement(statement) {
3255
+ const { condition, then: b, else: e } = statement;
2999
3256
  const [...condRest] = condition.children, [closeParen] = condRest.splice(-1);
3257
+ const expressionizedBlock = expressionizeBlock(b);
3258
+ if (!expressionizedBlock) {
3259
+ return wrapIIFE([["", statement]]);
3260
+ }
3000
3261
  const children = [
3001
3262
  ...condRest,
3002
3263
  "?",
3003
- b
3264
+ expressionizedBlock
3004
3265
  ];
3005
3266
  if (e) {
3006
- children.push(e[0], ":", ...e.slice(2));
3267
+ const e2 = expressionizeBlock(e[2]);
3268
+ if (!e2) {
3269
+ return wrapIIFE([["", statement]]);
3270
+ }
3271
+ children.push(e[0], ":", e2, ...e.slice(3));
3007
3272
  } else {
3008
3273
  children.push(":void 0");
3009
3274
  }
@@ -3067,17 +3332,17 @@ function processCallMemberExpression(node) {
3067
3332
  let call = children[1];
3068
3333
  const args = [...call.args];
3069
3334
  call = { ...call, args };
3070
- let ref1;
3071
- if (ref1 = isComma(args.at(-1))) {
3072
- const comma = ref1;
3335
+ let ref2;
3336
+ if (ref2 = isComma(args.at(-1))) {
3337
+ const comma = ref2;
3073
3338
  comma.token = "";
3074
3339
  }
3075
3340
  let commaCount = 0;
3076
- for (let i1 = 0, len1 = args.length; i1 < len1; i1++) {
3077
- const arg = args[i1];
3078
- let ref2;
3079
- if (ref2 = isComma(arg)) {
3080
- const comma = ref2;
3341
+ for (let i2 = 0, len1 = args.length; i2 < len1; i2++) {
3342
+ const arg = args[i2];
3343
+ let ref3;
3344
+ if (ref3 = isComma(arg)) {
3345
+ const comma = ref3;
3081
3346
  comma.token = `)${op.token}(`;
3082
3347
  commaCount++;
3083
3348
  }
@@ -3214,9 +3479,9 @@ function replaceNode(node, newNode) {
3214
3479
  throw new Error("replaceNode failed: node has no parent");
3215
3480
  }
3216
3481
  function recurse(children) {
3217
- for (let i2 = 0, len2 = children.length; i2 < len2; i2++) {
3218
- const i = i2;
3219
- const child = children[i2];
3482
+ for (let i3 = 0, len2 = children.length; i3 < len2; i3++) {
3483
+ const i = i3;
3484
+ const child = children[i3];
3220
3485
  if (child === node) {
3221
3486
  children[i] = newNode;
3222
3487
  return true;
@@ -3383,55 +3648,6 @@ function makeGetterMethod(name, ws, value, returnType, block, kind = { token: "g
3383
3648
  parameters
3384
3649
  };
3385
3650
  }
3386
- function processAssignmentDeclaration(decl, pattern, suffix, ws, assign, e) {
3387
- decl = {
3388
- ...decl,
3389
- $loc: {
3390
- pos: assign.$loc.pos - 1,
3391
- length: assign.$loc.length + 1
3392
- }
3393
- };
3394
- let [splices, assignments] = gatherBindingCode(pattern);
3395
- splices = splices.map((s) => [", ", s]);
3396
- const thisAssignments = assignments.map((a) => ["", a, ";"]);
3397
- const initializer = [ws, assign, e];
3398
- const binding = makeNode({
3399
- type: "Binding",
3400
- pattern,
3401
- initializer,
3402
- splices,
3403
- suffix,
3404
- thisAssignments,
3405
- children: [pattern, suffix, initializer]
3406
- });
3407
- const children = [decl, binding];
3408
- return makeNode({
3409
- type: "Declaration",
3410
- names: pattern.names,
3411
- decl,
3412
- bindings: [binding],
3413
- splices,
3414
- thisAssignments,
3415
- children
3416
- });
3417
- }
3418
- function processDeclarations(statements) {
3419
- gatherRecursiveAll(statements, ($) => $.type === "Declaration").forEach(({ bindings }) => {
3420
- return bindings?.forEach((binding) => {
3421
- const suffix = binding.suffix;
3422
- if (suffix && suffix.optional && suffix.t) {
3423
- convertOptionalType(suffix);
3424
- }
3425
- const { initializer } = binding;
3426
- if (initializer) {
3427
- const exp = initializer[2];
3428
- return exp;
3429
- }
3430
- ;
3431
- return;
3432
- });
3433
- });
3434
- }
3435
3651
  function processBindingPatternLHS(lhs, tail) {
3436
3652
  adjustAtBindings(lhs, true);
3437
3653
  const [splices, thisAssignments] = gatherBindingCode(lhs);
@@ -3485,8 +3701,25 @@ function processAssignments(statements) {
3485
3701
  return exp.children.push(...post);
3486
3702
  return;
3487
3703
  });
3488
- gatherRecursiveAll(statements, (n) => n.type === "AssignmentExpression" && n.names === null).forEach((exp) => {
3704
+ replaceNodesRecursive(statements, (n) => n.type === "AssignmentExpression" && n.names === null, (exp) => {
3489
3705
  let { lhs: $1, exp: $2 } = exp, tail = [], i = 0, len = $1.length;
3706
+ let block;
3707
+ if (exp.parent.type === "BlockStatement" && !$1.at(-1)?.at(-1)?.special) {
3708
+ block = makeBlockFragment();
3709
+ let ref4;
3710
+ if (ref4 = prependStatementExpressionBlock([null, null, $2], block)) {
3711
+ const ref = ref4;
3712
+ exp.children = exp.children.map(function(c) {
3713
+ if (c === $2)
3714
+ return ref;
3715
+ else
3716
+ return c;
3717
+ });
3718
+ $2 = ref;
3719
+ } else {
3720
+ block = void 0;
3721
+ }
3722
+ }
3490
3723
  if ($1.some((left) => left[left.length - 1].special)) {
3491
3724
  if ($1.length !== 1)
3492
3725
  throw new Error("Only one assignment with id= is allowed");
@@ -3501,7 +3734,7 @@ function processAssignments(statements) {
3501
3734
  exp.exp = $2 = [call, "(", lhs, ", ", $2, ")"]
3502
3735
  );
3503
3736
  if (omitLhs) {
3504
- replaceNode(exp, $2);
3737
+ return $2;
3505
3738
  }
3506
3739
  }
3507
3740
  let wrapped = false;
@@ -3546,7 +3779,7 @@ function processAssignments(statements) {
3546
3779
  }
3547
3780
  exp.children = [$1];
3548
3781
  exp.names = [];
3549
- return;
3782
+ return exp;
3550
3783
  }
3551
3784
  } else if (lhs.type === "ObjectBindingPattern" || lhs.type === "ArrayBindingPattern") {
3552
3785
  processBindingPatternLHS(lhs, tail);
@@ -3558,11 +3791,19 @@ function processAssignments(statements) {
3558
3791
  const index = exp.children.indexOf($2);
3559
3792
  if (index < 0)
3560
3793
  throw new Error("Assertion error: exp not in AssignmentExpression");
3561
- return exp.children.splice(index + 1, 0, ...tail);
3794
+ exp.children.splice(index + 1, 0, ...tail);
3795
+ if (block) {
3796
+ block.parent = exp.parent;
3797
+ block.expressions.push(["", exp]);
3798
+ exp.parent = block;
3799
+ return block;
3800
+ }
3801
+ return exp;
3562
3802
  });
3563
3803
  }
3564
3804
  function attachPostfixStatementAsExpression(exp, post) {
3565
- switch (post[1].type) {
3805
+ const postfixStatement = post[1];
3806
+ switch (postfixStatement.type) {
3566
3807
  case "ForStatement":
3567
3808
  case "IterationStatement":
3568
3809
  case "DoStatement": {
@@ -3575,9 +3816,9 @@ function attachPostfixStatementAsExpression(exp, post) {
3575
3816
  };
3576
3817
  }
3577
3818
  case "IfStatement":
3578
- return expressionizeIfClause(post[1], exp);
3819
+ return expressionizeIfStatement({ ...postfixStatement, then: exp });
3579
3820
  default:
3580
- (() => {
3821
+ return (() => {
3581
3822
  throw new Error("Unknown postfix statement");
3582
3823
  })();
3583
3824
  }
@@ -3616,6 +3857,42 @@ function processTypes(node) {
3616
3857
  }
3617
3858
  });
3618
3859
  }
3860
+ function processStatementExpressions(statements) {
3861
+ gatherRecursiveAll(statements, ($) => $.type === "StatementExpression").forEach((_exp) => {
3862
+ const exp = _exp;
3863
+ const { statement } = exp;
3864
+ let ws;
3865
+ if (!(exp.children[0] === exp.statement)) {
3866
+ ws = exp.children[0];
3867
+ }
3868
+ let ref5;
3869
+ switch (statement.type) {
3870
+ case "IfStatement": {
3871
+ if (ref5 = expressionizeIfStatement(statement)) {
3872
+ const expression = ref5;
3873
+ exp.statement = expression;
3874
+ exp.children = [exp.statement];
3875
+ } else {
3876
+ exp.children = wrapIIFE([["", statement]]);
3877
+ }
3878
+ ;
3879
+ break;
3880
+ }
3881
+ case "IterationExpression": {
3882
+ ;
3883
+ break;
3884
+ }
3885
+ default: {
3886
+ exp.children = wrapIIFE([["", statement]]);
3887
+ }
3888
+ }
3889
+ if (ws) {
3890
+ return exp.children.unshift(ws);
3891
+ }
3892
+ ;
3893
+ return;
3894
+ });
3895
+ }
3619
3896
  function processProgram(root, config, m, ReservedWord) {
3620
3897
  assert.equal(m.forbidBracedApplication.length, 1, "forbidBracedApplication");
3621
3898
  assert.equal(m.forbidClassImplicitCall.length, 1, "forbidClassImplicitCall");
@@ -3630,6 +3907,7 @@ function processProgram(root, config, m, ReservedWord) {
3630
3907
  processPipelineExpressions(statements);
3631
3908
  processDeclarations(statements);
3632
3909
  processAssignments(statements);
3910
+ processStatementExpressions(statements);
3633
3911
  processPatternMatching(statements, ReservedWord);
3634
3912
  gatherRecursiveAll(statements, (n) => n.type === "IterationExpression").forEach((e) => expressionizeIteration(e));
3635
3913
  hoistRefDecs(statements);
@@ -3734,9 +4012,9 @@ function replaceNodes(root, predicate, replacer) {
3734
4012
  return root;
3735
4013
  }
3736
4014
  }
3737
- for (let i3 = 0, len3 = array.length; i3 < len3; i3++) {
3738
- const i = i3;
3739
- const node = array[i3];
4015
+ for (let i4 = 0, len3 = array.length; i4 < len3; i4++) {
4016
+ const i = i4;
4017
+ const node = array[i4];
3740
4018
  if (!(node != null)) {
3741
4019
  return;
3742
4020
  }
@@ -3748,6 +4026,34 @@ function replaceNodes(root, predicate, replacer) {
3748
4026
  }
3749
4027
  return root;
3750
4028
  }
4029
+ function replaceNodesRecursive(root, predicate, replacer) {
4030
+ if (!(root != null)) {
4031
+ return root;
4032
+ }
4033
+ const array = Array.isArray(root) ? root : root.children;
4034
+ if (!array) {
4035
+ if (predicate(root)) {
4036
+ return replacer(root, root);
4037
+ } else {
4038
+ return root;
4039
+ }
4040
+ }
4041
+ for (let i5 = 0, len4 = array.length; i5 < len4; i5++) {
4042
+ const i = i5;
4043
+ const node = array[i5];
4044
+ if (!(node != null)) {
4045
+ continue;
4046
+ }
4047
+ if (predicate(node)) {
4048
+ const ret = replacer(node, root);
4049
+ replaceNodesRecursive(ret, predicate, replacer);
4050
+ array[i] = ret;
4051
+ } else {
4052
+ replaceNodesRecursive(node, predicate, replacer);
4053
+ }
4054
+ }
4055
+ return root;
4056
+ }
3751
4057
  function typeOfJSX(node, config, getRef) {
3752
4058
  switch (node.type) {
3753
4059
  case "JSXElement":
@@ -3812,13 +4118,14 @@ function typeOfJSXFragment(node, config, getRef) {
3812
4118
  ;
3813
4119
  return;
3814
4120
  }
3815
- var xor, assert;
4121
+ var xor;
3816
4122
  var init_lib = __esm({
3817
4123
  "source/parser/lib.civet"() {
3818
4124
  "use strict";
3819
4125
  init_traversal();
3820
4126
  init_util();
3821
4127
  init_block();
4128
+ init_declaration();
3822
4129
  init_pipe();
3823
4130
  init_for();
3824
4131
  init_function();
@@ -3829,19 +4136,12 @@ var init_lib = __esm({
3829
4136
  init_auto_dec();
3830
4137
  init_string();
3831
4138
  xor = (a, b) => a ? !b && a : b;
3832
- assert = {
3833
- equal(a, b, msg) {
3834
- if (a !== b) {
3835
- throw new Error(`Assertion failed [${msg}]: ${a} !== ${b}`);
3836
- }
3837
- }
3838
- };
3839
4139
  }
3840
4140
  });
3841
4141
 
3842
- // node_modules/@danielx/hera/dist/machine.js
4142
+ // ../Hera/dist/machine.js
3843
4143
  var require_machine = __commonJS({
3844
- "node_modules/@danielx/hera/dist/machine.js"(exports2, module2) {
4144
+ "../Hera/dist/machine.js"(exports2, module2) {
3845
4145
  "use strict";
3846
4146
  var __defProp2 = Object.defineProperty;
3847
4147
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -4312,8 +4612,6 @@ var require_parser = __commonJS({
4312
4612
  $TV,
4313
4613
  $Y,
4314
4614
  Parser,
4315
- ParserContext,
4316
- ParserOptions,
4317
4615
  Validator
4318
4616
  } = require_machine();
4319
4617
  var grammar = {
@@ -4330,7 +4628,7 @@ var require_parser = __commonJS({
4330
4628
  NestedNonAssignmentExtendedExpression,
4331
4629
  ExpressionizedStatementWithTrailingCallExpressions,
4332
4630
  ExpressionizedStatement,
4333
- _ExpressionizedStatement,
4631
+ StatementExpression,
4334
4632
  CommaExpression,
4335
4633
  Arguments,
4336
4634
  ImplicitArguments,
@@ -4592,14 +4890,6 @@ var require_parser = __commonJS({
4592
4890
  ElseClause,
4593
4891
  IfClause,
4594
4892
  UnlessClause,
4595
- IfExpression,
4596
- UnlessExpression,
4597
- ElseExpressionClause,
4598
- ExpressionBlock,
4599
- ElseExpressionBlock,
4600
- NestedBlockExpressions,
4601
- NestedBlockExpression,
4602
- BlockExpressionPart,
4603
4893
  IterationStatement,
4604
4894
  _IterationStatement,
4605
4895
  IterationExpression,
@@ -4623,7 +4913,6 @@ var require_parser = __commonJS({
4623
4913
  ForBinding,
4624
4914
  SwitchStatement,
4625
4915
  EmptyCondition,
4626
- SwitchExpression,
4627
4916
  CaseBlock,
4628
4917
  NestedCaseClauses,
4629
4918
  NestedCaseClause,
@@ -4635,7 +4924,6 @@ var require_parser = __commonJS({
4635
4924
  ImpliedColon,
4636
4925
  IgnoreColon,
4637
4926
  TryStatement,
4638
- TryExpression,
4639
4927
  CatchClause,
4640
4928
  CatchBind,
4641
4929
  FinallyClause,
@@ -4676,8 +4964,6 @@ var require_parser = __commonJS({
4676
4964
  Break,
4677
4965
  Continue,
4678
4966
  Debugger,
4679
- DebuggerExpression,
4680
- ThrowExpression,
4681
4967
  MaybeNestedExpression,
4682
4968
  ImportDeclaration,
4683
4969
  ImpliedImport,
@@ -5507,22 +5793,26 @@ var require_parser = __commonJS({
5507
5793
  function ExpressionizedStatementWithTrailingCallExpressions(ctx, state) {
5508
5794
  return $EVENT(ctx, state, "ExpressionizedStatementWithTrailingCallExpressions", ExpressionizedStatementWithTrailingCallExpressions$0);
5509
5795
  }
5510
- var ExpressionizedStatement$0 = $T($S($EXPECT($R0, "ExpressionizedStatement /(?=async|debugger|if|unless|do|for|loop|until|while|switch|throw|try)/"), _ExpressionizedStatement), function(value) {
5511
- return value[1];
5796
+ var ExpressionizedStatement$0 = $TS($S($EXPECT($R0, "ExpressionizedStatement /(?=async|debugger|if|unless|do|for|loop|until|while|switch|throw|try)/"), StatementExpression), function($skip, $loc, $0, $1, $2) {
5797
+ var statement = $2;
5798
+ return {
5799
+ type: "StatementExpression",
5800
+ statement,
5801
+ children: [statement]
5802
+ };
5512
5803
  });
5513
5804
  function ExpressionizedStatement(ctx, state) {
5514
5805
  return $EVENT(ctx, state, "ExpressionizedStatement", ExpressionizedStatement$0);
5515
5806
  }
5516
- var _ExpressionizedStatement$0 = DebuggerExpression;
5517
- var _ExpressionizedStatement$1 = IfExpression;
5518
- var _ExpressionizedStatement$2 = UnlessExpression;
5519
- var _ExpressionizedStatement$3 = IterationExpression;
5520
- var _ExpressionizedStatement$4 = SwitchExpression;
5521
- var _ExpressionizedStatement$5 = ThrowExpression;
5522
- var _ExpressionizedStatement$6 = TryExpression;
5523
- var _ExpressionizedStatement$$ = [_ExpressionizedStatement$0, _ExpressionizedStatement$1, _ExpressionizedStatement$2, _ExpressionizedStatement$3, _ExpressionizedStatement$4, _ExpressionizedStatement$5, _ExpressionizedStatement$6];
5524
- function _ExpressionizedStatement(ctx, state) {
5525
- return $EVENT_C(ctx, state, "_ExpressionizedStatement", _ExpressionizedStatement$$);
5807
+ var StatementExpression$0 = DebuggerStatement;
5808
+ var StatementExpression$1 = IfStatement;
5809
+ var StatementExpression$2 = IterationExpression;
5810
+ var StatementExpression$3 = SwitchStatement;
5811
+ var StatementExpression$4 = ThrowStatement;
5812
+ var StatementExpression$5 = TryStatement;
5813
+ var StatementExpression$$ = [StatementExpression$0, StatementExpression$1, StatementExpression$2, StatementExpression$3, StatementExpression$4, StatementExpression$5];
5814
+ function StatementExpression(ctx, state) {
5815
+ return $EVENT_C(ctx, state, "StatementExpression", StatementExpression$$);
5526
5816
  }
5527
5817
  var CommaExpression$0 = $TS($S(AssignmentExpression, $Q($S(CommaDelimiter, AssignmentExpression))), function($skip, $loc, $0, $1, $2) {
5528
5818
  if ($2.length == 0)
@@ -5548,14 +5838,8 @@ var require_parser = __commonJS({
5548
5838
  var ws = $3;
5549
5839
  var args = $4;
5550
5840
  var close = $5;
5551
- if (args.length === 1) {
5552
- let arg0 = args[0];
5553
- if (Array.isArray(arg0))
5554
- arg0 = arg0[1];
5555
- if (arg0.type === "IterationExpression" && arg0.subtype !== "DoStatement" && !arg0.async && isEmptyBareBlock(arg0.block)) {
5556
- return $skip;
5557
- }
5558
- }
5841
+ if (skipImplicitArguments(args))
5842
+ return $skip;
5559
5843
  return {
5560
5844
  type: "Call",
5561
5845
  args,
@@ -6113,8 +6397,12 @@ var require_parser = __commonJS({
6113
6397
  function PipelineHeadItem(ctx, state) {
6114
6398
  return $EVENT_C(ctx, state, "PipelineHeadItem", PipelineHeadItem$$);
6115
6399
  }
6116
- var PipelineTailItem$0 = Await;
6117
- var PipelineTailItem$1 = Yield;
6400
+ var PipelineTailItem$0 = $T($S(AwaitOp, $N(AccessStart)), function(value) {
6401
+ return value[0];
6402
+ });
6403
+ var PipelineTailItem$1 = $T($S(Yield, $N(AccessStart)), function(value) {
6404
+ return value[0];
6405
+ });
6118
6406
  var PipelineTailItem$2 = $T($S(Return, $N(AccessStart)), function(value) {
6119
6407
  return value[0];
6120
6408
  });
@@ -6150,6 +6438,9 @@ var require_parser = __commonJS({
6150
6438
  return $skip;
6151
6439
  const [exp, ws, close] = $3;
6152
6440
  switch (exp.type) {
6441
+ case "StatementExpression":
6442
+ if (exp.statement.type !== "IterationExpression")
6443
+ break;
6153
6444
  case "IterationExpression":
6154
6445
  return exp;
6155
6446
  case "ParenthesizedExpression":
@@ -7677,7 +7968,7 @@ var require_parser = __commonJS({
7677
7968
  if (prefix.length) {
7678
7969
  body = {
7679
7970
  type: "UnaryExpression",
7680
- children: [prefix, body, void 0]
7971
+ children: [processUnaryExpression(prefix, body, void 0)]
7681
7972
  };
7682
7973
  }
7683
7974
  const parameters = {
@@ -9634,7 +9925,13 @@ var require_parser = __commonJS({
9634
9925
  return { $loc, token: $0 };
9635
9926
  });
9636
9927
  var UnaryOp$1 = AwaitOp;
9637
- var UnaryOp$2 = $S($C(Delete, Void, Typeof), $N($R$0($EXPECT($R21, "UnaryOp /[:.]/"))), $E(_));
9928
+ var UnaryOp$2 = $TS($S($C(Delete, Void, Typeof), $N($EXPECT($R21, "UnaryOp /[:.]/")), $E(_)), function($skip, $loc, $0, $1, $2, $3) {
9929
+ var op = $1;
9930
+ var ws = $3;
9931
+ if (!ws)
9932
+ return [op, [" "]];
9933
+ return [op, ws];
9934
+ });
9638
9935
  var UnaryOp$3 = $T($S(Not, $N($EXPECT($R21, "UnaryOp /[:.]/")), $E($EXPECT($L16, 'UnaryOp " "')), $E(_)), function(value) {
9639
9936
  return [value[0], value[3]];
9640
9937
  });
@@ -9642,18 +9939,15 @@ var require_parser = __commonJS({
9642
9939
  function UnaryOp(ctx, state) {
9643
9940
  return $EVENT_C(ctx, state, "UnaryOp", UnaryOp$$);
9644
9941
  }
9645
- var AwaitOp$0 = $TS($S(Await, $E($S(Dot, IdentifierName)), $C($Y(OpenParen), _, $Y(EOS))), function($skip, $loc, $0, $1, $2, $3) {
9942
+ var AwaitOp$0 = $TS($S(Await, $E($S(Dot, IdentifierName)), $E(_)), function($skip, $loc, $0, $1, $2, $3) {
9646
9943
  var a = $1;
9647
9944
  var op = $2;
9648
9945
  var ws = $3;
9649
- if (op) {
9650
- return {
9651
- ...a,
9652
- op,
9653
- children: [a, ...ws || []]
9654
- };
9655
- }
9656
- return [a, ...ws || []];
9946
+ return {
9947
+ ...a,
9948
+ op,
9949
+ children: [a, ...ws || [" "]]
9950
+ };
9657
9951
  });
9658
9952
  function AwaitOp(ctx, state) {
9659
9953
  return $EVENT(ctx, state, "AwaitOp", AwaitOp$0);
@@ -9866,120 +10160,6 @@ var require_parser = __commonJS({
9866
10160
  function UnlessClause(ctx, state) {
9867
10161
  return $EVENT(ctx, state, "UnlessClause", UnlessClause$0);
9868
10162
  }
9869
- var IfExpression$0 = $TS($S(IfClause, ExpressionBlock, $E(ElseExpressionClause)), function($skip, $loc, $0, $1, $2, $3) {
9870
- var clause = $1;
9871
- var b = $2;
9872
- var e = $3;
9873
- return expressionizeIfClause(clause, b, e);
9874
- });
9875
- function IfExpression(ctx, state) {
9876
- return $EVENT(ctx, state, "IfExpression", IfExpression$0);
9877
- }
9878
- var UnlessExpression$0 = $TS($S(UnlessClause, ExpressionBlock, $E(ElseExpressionClause)), function($skip, $loc, $0, $1, $2, $3) {
9879
- var clause = $1;
9880
- var b = $2;
9881
- var e = $3;
9882
- return expressionizeIfClause(clause, b, e);
9883
- });
9884
- function UnlessExpression(ctx, state) {
9885
- return $EVENT(ctx, state, "UnlessExpression", UnlessExpression$0);
9886
- }
9887
- var ElseExpressionClause$0 = $TS($S($C($S(Nested, Else), $S($E(_), Else)), ElseExpressionBlock), function($skip, $loc, $0, $1, $2) {
9888
- return [...$1, $2];
9889
- });
9890
- function ElseExpressionClause(ctx, state) {
9891
- return $EVENT(ctx, state, "ElseExpressionClause", ElseExpressionClause$0);
9892
- }
9893
- var ExpressionBlock$0 = $TS($S(InsertOpenParen, NestedBlockExpressions, InsertNewline, InsertIndent, InsertCloseParen), function($skip, $loc, $0, $1, $2, $3, $4, $5) {
9894
- var exps = $2;
9895
- exps = exps.flat();
9896
- if (exps.length === 1) {
9897
- let [ws, exp] = exps[0];
9898
- switch (exp.type) {
9899
- case "Identifier":
9900
- case "Literal":
9901
- return [ws, exp];
9902
- }
9903
- }
9904
- exps = exps.map((e, i) => {
9905
- if (i === exps.length - 1) {
9906
- return e.slice(0, -1);
9907
- }
9908
- return e;
9909
- });
9910
- return {
9911
- type: "BlockExpressions",
9912
- expressions: exps,
9913
- children: [$1, exps, $3, $4, $5]
9914
- };
9915
- });
9916
- var ExpressionBlock$1 = $S(Then, ExtendedExpression);
9917
- var ExpressionBlock$$ = [ExpressionBlock$0, ExpressionBlock$1];
9918
- function ExpressionBlock(ctx, state) {
9919
- return $EVENT_C(ctx, state, "ExpressionBlock", ExpressionBlock$$);
9920
- }
9921
- var ElseExpressionBlock$0 = $TS($S(InsertOpenParen, NestedBlockExpressions, InsertNewline, InsertIndent, InsertCloseParen), function($skip, $loc, $0, $1, $2, $3, $4, $5) {
9922
- var exps = $2;
9923
- exps = exps.flat();
9924
- if (exps.length === 1) {
9925
- let [ws, exp] = exps[0];
9926
- switch (exp.type) {
9927
- case "Identifier":
9928
- case "Literal":
9929
- return [ws, exp];
9930
- }
9931
- }
9932
- exps = exps.map((e, i) => {
9933
- if (i === exps.length - 1) {
9934
- return e.slice(0, -1);
9935
- }
9936
- return e;
9937
- });
9938
- return {
9939
- type: "BlockExpressions",
9940
- expressions: exps,
9941
- children: [$1, exps, $3, $4, $5]
9942
- };
9943
- });
9944
- var ElseExpressionBlock$1 = $T($S($N(EOS), ExpressionWithObjectApplicationForbidden), function(value) {
9945
- return value[1];
9946
- });
9947
- var ElseExpressionBlock$$ = [ElseExpressionBlock$0, ElseExpressionBlock$1];
9948
- function ElseExpressionBlock(ctx, state) {
9949
- return $EVENT_C(ctx, state, "ElseExpressionBlock", ElseExpressionBlock$$);
9950
- }
9951
- var NestedBlockExpressions$0 = $TS($S(PushIndent, $Q(NestedBlockExpression), PopIndent), function($skip, $loc, $0, $1, $2, $3) {
9952
- var exps = $2;
9953
- if (!exps.length)
9954
- return $skip;
9955
- return exps;
9956
- });
9957
- function NestedBlockExpressions(ctx, state) {
9958
- return $EVENT(ctx, state, "NestedBlockExpressions", NestedBlockExpressions$0);
9959
- }
9960
- var NestedBlockExpression$0 = $TS($S(Nested, $P(BlockExpressionPart)), function($skip, $loc, $0, $1, $2) {
9961
- var nested = $1;
9962
- var expressions = $2;
9963
- return [
9964
- [nested, ...expressions[0]],
9965
- ...expressions.slice(1).map((s) => ["", ...s])
9966
- ];
9967
- });
9968
- function NestedBlockExpression(ctx, state) {
9969
- return $EVENT(ctx, state, "NestedBlockExpression", NestedBlockExpression$0);
9970
- }
9971
- var BlockExpressionPart$0 = $TS($S($N(EOS), $E(_), PostfixedExpression, ExpressionDelimiter), function($skip, $loc, $0, $1, $2, $3, $4) {
9972
- var ws = $2;
9973
- var exp = $3;
9974
- var delimiter = $4;
9975
- if (ws) {
9976
- exp = { ...exp, children: [ws, ...exp.children] };
9977
- }
9978
- return [exp, delimiter];
9979
- });
9980
- function BlockExpressionPart(ctx, state) {
9981
- return $EVENT(ctx, state, "BlockExpressionPart", BlockExpressionPart$0);
9982
- }
9983
10163
  var IterationStatement$0 = $T($S($EXPECT($R23, "IterationStatement /(?=loop|do|for|until|while)/"), _IterationStatement), function(value) {
9984
10164
  return value[1];
9985
10165
  });
@@ -10396,18 +10576,6 @@ var require_parser = __commonJS({
10396
10576
  function EmptyCondition(ctx, state) {
10397
10577
  return $EVENT(ctx, state, "EmptyCondition", EmptyCondition$0);
10398
10578
  }
10399
- var SwitchExpression$0 = $TV(SwitchStatement, function($skip, $loc, $0, $1) {
10400
- var s = $0;
10401
- return {
10402
- type: "SwitchExpression",
10403
- // wrap with IIFE
10404
- children: wrapIIFE([["", s]]),
10405
- statement: s
10406
- };
10407
- });
10408
- function SwitchExpression(ctx, state) {
10409
- return $EVENT(ctx, state, "SwitchExpression", SwitchExpression$0);
10410
- }
10411
10579
  var CaseBlock$0 = $TS($S($E($C(Nested, _)), OpenBrace, NestedCaseClauses, __, CloseBrace), function($skip, $loc, $0, $1, $2, $3, $4, $5) {
10412
10580
  var clauses = $3;
10413
10581
  return {
@@ -10589,17 +10757,6 @@ var require_parser = __commonJS({
10589
10757
  function TryStatement(ctx, state) {
10590
10758
  return $EVENT(ctx, state, "TryStatement", TryStatement$0);
10591
10759
  }
10592
- var TryExpression$0 = $TV(TryStatement, function($skip, $loc, $0, $1) {
10593
- var t = $0;
10594
- return {
10595
- type: "TryExpression",
10596
- blocks: t.blocks,
10597
- children: wrapIIFE([["", t]])
10598
- };
10599
- });
10600
- function TryExpression(ctx, state) {
10601
- return $EVENT(ctx, state, "TryExpression", TryExpression$0);
10602
- }
10603
10760
  var CatchClause$0 = $TS($S($C(Nested, _), Catch, $E(CatchBind), $C(BracedThenClause, BracedOrEmptyBlock)), function($skip, $loc, $0, $1, $2, $3, $4) {
10604
10761
  var block = $4;
10605
10762
  return {
@@ -10934,26 +11091,6 @@ var require_parser = __commonJS({
10934
11091
  function Debugger(ctx, state) {
10935
11092
  return $EVENT(ctx, state, "Debugger", Debugger$0);
10936
11093
  }
10937
- var DebuggerExpression$0 = $TV(DebuggerStatement, function($skip, $loc, $0, $1) {
10938
- var s = $0;
10939
- return {
10940
- type: "DebuggerExpression",
10941
- children: wrapIIFE([["", s]])
10942
- };
10943
- });
10944
- function DebuggerExpression(ctx, state) {
10945
- return $EVENT(ctx, state, "DebuggerExpression", DebuggerExpression$0);
10946
- }
10947
- var ThrowExpression$0 = $TV(ThrowStatement, function($skip, $loc, $0, $1) {
10948
- var s = $0;
10949
- return {
10950
- type: "ThrowExpression",
10951
- children: wrapIIFE([["", s]])
10952
- };
10953
- });
10954
- function ThrowExpression(ctx, state) {
10955
- return $EVENT(ctx, state, "ThrowExpression", ThrowExpression$0);
10956
- }
10957
11094
  var MaybeNestedExpression$0 = $TS($S($N(EOS), ExtendedExpression), function($skip, $loc, $0, $1, $2) {
10958
11095
  return $2;
10959
11096
  });
@@ -14071,7 +14208,9 @@ var require_parser = __commonJS({
14071
14208
  function TripleSlashDirective(ctx, state) {
14072
14209
  return $EVENT(ctx, state, "TripleSlashDirective", TripleSlashDirective$0);
14073
14210
  }
14074
- var DirectivePrologue$0 = PrologueString;
14211
+ var DirectivePrologue$0 = $T($S(PrologueString, $N($S(__, $C(AccessStart, Pipe)))), function(value) {
14212
+ return value[0];
14213
+ });
14075
14214
  function DirectivePrologue(ctx, state) {
14076
14215
  return $EVENT(ctx, state, "DirectivePrologue", DirectivePrologue$0);
14077
14216
  }
@@ -14606,9 +14745,9 @@ var require_parser = __commonJS({
14606
14745
  }
14607
14746
  }
14608
14747
  });
14609
- if (typeof parse !== "undefined") {
14610
- Object.assign(module2.config, parse.config);
14611
- parse.config = module2.config;
14748
+ if (typeof parse2 !== "undefined") {
14749
+ Object.assign(module2.config, parse2.config);
14750
+ parse2.config = module2.config;
14612
14751
  } else {
14613
14752
  Object.assign(module2.config, exports2.parse.config);
14614
14753
  exports2.parse.config = module2.config;
@@ -14759,7 +14898,7 @@ var require_parser = __commonJS({
14759
14898
  };
14760
14899
  }();
14761
14900
  exports2.default = parser;
14762
- exports2.parse = parser.parse;
14901
+ var parse2 = exports2.parse = parser.parse;
14763
14902
  exports2.Program = Program;
14764
14903
  exports2.TopLevelStatements = TopLevelStatements;
14765
14904
  exports2.NestedTopLevelStatements = NestedTopLevelStatements;
@@ -14773,7 +14912,7 @@ var require_parser = __commonJS({
14773
14912
  exports2.NestedNonAssignmentExtendedExpression = NestedNonAssignmentExtendedExpression;
14774
14913
  exports2.ExpressionizedStatementWithTrailingCallExpressions = ExpressionizedStatementWithTrailingCallExpressions;
14775
14914
  exports2.ExpressionizedStatement = ExpressionizedStatement;
14776
- exports2._ExpressionizedStatement = _ExpressionizedStatement;
14915
+ exports2.StatementExpression = StatementExpression;
14777
14916
  exports2.CommaExpression = CommaExpression;
14778
14917
  exports2.Arguments = Arguments;
14779
14918
  exports2.ImplicitArguments = ImplicitArguments;
@@ -15035,14 +15174,6 @@ var require_parser = __commonJS({
15035
15174
  exports2.ElseClause = ElseClause;
15036
15175
  exports2.IfClause = IfClause;
15037
15176
  exports2.UnlessClause = UnlessClause;
15038
- exports2.IfExpression = IfExpression;
15039
- exports2.UnlessExpression = UnlessExpression;
15040
- exports2.ElseExpressionClause = ElseExpressionClause;
15041
- exports2.ExpressionBlock = ExpressionBlock;
15042
- exports2.ElseExpressionBlock = ElseExpressionBlock;
15043
- exports2.NestedBlockExpressions = NestedBlockExpressions;
15044
- exports2.NestedBlockExpression = NestedBlockExpression;
15045
- exports2.BlockExpressionPart = BlockExpressionPart;
15046
15177
  exports2.IterationStatement = IterationStatement;
15047
15178
  exports2._IterationStatement = _IterationStatement;
15048
15179
  exports2.IterationExpression = IterationExpression;
@@ -15066,7 +15197,6 @@ var require_parser = __commonJS({
15066
15197
  exports2.ForBinding = ForBinding;
15067
15198
  exports2.SwitchStatement = SwitchStatement;
15068
15199
  exports2.EmptyCondition = EmptyCondition;
15069
- exports2.SwitchExpression = SwitchExpression;
15070
15200
  exports2.CaseBlock = CaseBlock;
15071
15201
  exports2.NestedCaseClauses = NestedCaseClauses;
15072
15202
  exports2.NestedCaseClause = NestedCaseClause;
@@ -15078,7 +15208,6 @@ var require_parser = __commonJS({
15078
15208
  exports2.ImpliedColon = ImpliedColon;
15079
15209
  exports2.IgnoreColon = IgnoreColon;
15080
15210
  exports2.TryStatement = TryStatement;
15081
- exports2.TryExpression = TryExpression;
15082
15211
  exports2.CatchClause = CatchClause;
15083
15212
  exports2.CatchBind = CatchBind;
15084
15213
  exports2.FinallyClause = FinallyClause;
@@ -15119,8 +15248,6 @@ var require_parser = __commonJS({
15119
15248
  exports2.Break = Break;
15120
15249
  exports2.Continue = Continue;
15121
15250
  exports2.Debugger = Debugger;
15122
- exports2.DebuggerExpression = DebuggerExpression;
15123
- exports2.ThrowExpression = ThrowExpression;
15124
15251
  exports2.MaybeNestedExpression = MaybeNestedExpression;
15125
15252
  exports2.ImportDeclaration = ImportDeclaration;
15126
15253
  exports2.ImpliedImport = ImpliedImport;