Skip to content

Instantly share code, notes, and snippets.

@aziis98
Last active August 30, 2018 15:06
Show Gist options
  • Select an option

  • Save aziis98/c2a931005e4799bad603c8d20438e461 to your computer and use it in GitHub Desktop.

Select an option

Save aziis98/c2a931005e4799bad603c8d20438e461 to your computer and use it in GitHub Desktop.
A simple PEGjs parser for a basic custom type system (Parses primitive types, generics (lowcase symbols), arrays (haskell way), functions (args are comma separated and after a right arrow there is a return type) and union types). Can be tried out here https://pegjs.org/online
// Copyright Antonio De Lucreziis 2018
/*
A simple PEGjs parser for a basic custom type system (Parses primitive types, generics (lowcase symbols), arrays (haskell way), functions (args are comma separated and after a right arrow there is a return type) and union types).
Can be tried out here https://pegjs.org/online
*/
Expression
= symbolName:( Symbol _ "::" _)? symbolType:(Lambda / Type) {
if (!symbolName) {
return symbolType;
}
else {
return {
name: symbolName,
type: symbolType,
};
}
}
Type
= UnionType / NonSetTypes
NonSetTypes
= GenericParameter / PrimitiveType / ArrayType / ParenType
ParenType
= "(" type:(Lambda / Type) ")" { return type; }
Lambda
= args:( Type ( _ "," _ Type)* )? _ "->" _ ret:Type {
return {
is: 'lambda',
'parameters': [args[0]].concat(args[1]),
'return': ret,
};
}
UnionType
= first:NonSetTypes rest:( _ "|" _ Type)+ {
return {
is: 'union',
types: [first].concat(rest.map(it => it[3]))
};
}
ArrayType
= "[" t:Type "]" { return { is: 'array', type: t }; }
GenericParameter
= [a-z]+ { return { is: 'generic', name: text() }; }
PrimitiveType
= [A-Z][a-zA-Z]* { return { is: 'primitive', name: text() }; }
Symbol
= [^ ]+ { return text() }
_ "whitespace"
= [ \t\n\r]*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment