type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
ArrowFunction
|
(error: any) => {
console.error(error);
process.exit(0);
}
|
98abhinav/angular2-seed
|
tools/tasks/seed/build.bundles.app.rollup.aot.ts
|
TypeScript
|
FunctionDeclaration
|
export default function Modal (props: ModalProps): React.ReactElement {
const show = props.show
const title = props.title || 'Oops!...'
useEffect(() => {
if (show) {
document.body.style.overflow = 'hidden'
} else {
document.body.style.overflow = 'unset'
}
}, [show])
return (
<div className={`modal-background ${show ? 'modal-visible' : ''}`}
|
Dramakk/gra-w-smoka
|
views/helpers/Modal.tsx
|
TypeScript
|
ArrowFunction
|
() => {
if (show) {
document.body.style.overflow = 'hidden'
} else {
document.body.style.overflow = 'unset'
}
}
|
Dramakk/gra-w-smoka
|
views/helpers/Modal.tsx
|
TypeScript
|
ArrowFunction
|
(buttonDescription, index) => {
return (
<button key={index} className={`button-${buttonDescription.buttonType}`}
|
Dramakk/gra-w-smoka
|
views/helpers/Modal.tsx
|
TypeScript
|
InterfaceDeclaration
|
export interface ButtonDescription {
buttonType: 'danger' | 'primary' | 'success' | 'disabled'
buttonText: string
onClick: MouseEventHandler
}
|
Dramakk/gra-w-smoka
|
views/helpers/Modal.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface ModalProps {
buttons: ButtonDescription[]
show: boolean
title?: string
children: React.ReactNode
}
|
Dramakk/gra-w-smoka
|
views/helpers/Modal.tsx
|
TypeScript
|
ArrowFunction
|
(
fastify: FastifyInstance,
opts: ServerOptions,
next: CallableFunction,
) => {
const {
app,
redis,
maxProfiles,
twitch,
} = opts;
const { urlPrefix } = app;
fastify.register(db, {
...opts.db,
maxProfiles,
});
if (opts.cloudflare.enable) {
fastify.register(cloudflare, opts.cloudflare);
}
fastify.register(sas, opts.sas);
fastify.register(playerConfig, { maxProfiles });
fastify.register(twitchConfigValidator, twitch);
fastify.register(viewer, { ttl: redis.ttl });
fastify.register(statusRoutes);
fastify.register(configRoutes.get, { urlPrefix });
fastify.register(configRoutes.post, { urlPrefix });
fastify.register(viewerRoutes.get, { urlPrefix });
next();
}
|
sc2pte/panel-backend
|
src/index.ts
|
TypeScript
|
InterfaceDeclaration
|
interface ServerOptions {
app: {
urlPrefix: string;
};
db: {
uri: string;
};
redis: {
ttl: number;
};
twitch: TwitchPluginOptions;
sas: SasOptions;
maxProfiles: number;
cloudflare: {
enable: boolean;
token: string;
zoneId: string;
productionDomain: string;
viewerRoute: string;
};
}
|
sc2pte/panel-backend
|
src/index.ts
|
TypeScript
|
ArrowFunction
|
_type => SongCreateWithoutSongInMovieInput
|
lewisblackburn/CSNEA2021
|
packages/backend/src/generated/type-graphql/resolvers/inputs/SongCreateNestedOneWithoutSongInMovieInput.ts
|
TypeScript
|
ArrowFunction
|
_type => SongCreateOrConnectWithoutSongInMovieInput
|
lewisblackburn/CSNEA2021
|
packages/backend/src/generated/type-graphql/resolvers/inputs/SongCreateNestedOneWithoutSongInMovieInput.ts
|
TypeScript
|
ArrowFunction
|
_type => SongWhereUniqueInput
|
lewisblackburn/CSNEA2021
|
packages/backend/src/generated/type-graphql/resolvers/inputs/SongCreateNestedOneWithoutSongInMovieInput.ts
|
TypeScript
|
ClassDeclaration
|
@TypeGraphQL.InputType({
isAbstract: true
})
export class SongCreateNestedOneWithoutSongInMovieInput {
@TypeGraphQL.Field(_type => SongCreateWithoutSongInMovieInput, {
nullable: true
})
create?: SongCreateWithoutSongInMovieInput | undefined;
@TypeGraphQL.Field(_type => SongCreateOrConnectWithoutSongInMovieInput, {
nullable: true
})
connectOrCreate?: SongCreateOrConnectWithoutSongInMovieInput | undefined;
@TypeGraphQL.Field(_type => SongWhereUniqueInput, {
nullable: true
})
connect?: SongWhereUniqueInput | undefined;
}
|
lewisblackburn/CSNEA2021
|
packages/backend/src/generated/type-graphql/resolvers/inputs/SongCreateNestedOneWithoutSongInMovieInput.ts
|
TypeScript
|
ClassDeclaration
|
export default class UnlockableRowInfoProvider extends InfoProvider {
private readonly getter;
private contentHandler?;
constructor(getter: () => number);
setContent(handler?: ContentHandler | InfoProvider | Translation): this;
get(context: InfoProviderContext): ArrayOr<TranslationGenerator<import("../../../language/dictionary/UiTranslation").default, []> | InfoProvider>;
getClass(): string[];
initComponent(context: InfoProviderContext): {
component: import("../../../ui/component/Component").default<HTMLElement>;
fullInit(): void;
};
protected onRefresh(): void;
}
|
WaywardGame/types
|
definitions/game/game/inspection/infoProviders/UnlockableRowInfoProvider.d.ts
|
TypeScript
|
TypeAliasDeclaration
|
declare type ContentHandler = (context: InfoProviderContext, provider: UnlockableRowInfoProvider) => ArrayOr<TranslationGenerator | InfoProvider>;
|
WaywardGame/types
|
definitions/game/game/inspection/infoProviders/UnlockableRowInfoProvider.d.ts
|
TypeScript
|
MethodDeclaration
|
setContent(handler?: ContentHandler | InfoProvider | Translation): this;
|
WaywardGame/types
|
definitions/game/game/inspection/infoProviders/UnlockableRowInfoProvider.d.ts
|
TypeScript
|
MethodDeclaration
|
get(context: InfoProviderContext): ArrayOr<TranslationGenerator<import("../../../language/dictionary/UiTranslation").default, []> | InfoProvider>;
|
WaywardGame/types
|
definitions/game/game/inspection/infoProviders/UnlockableRowInfoProvider.d.ts
|
TypeScript
|
MethodDeclaration
|
getClass(): string[];
|
WaywardGame/types
|
definitions/game/game/inspection/infoProviders/UnlockableRowInfoProvider.d.ts
|
TypeScript
|
MethodDeclaration
|
initComponent(context: InfoProviderContext): {
component: import("../../../ui/component/Component").default<HTMLElement>;
fullInit(): void;
};
|
WaywardGame/types
|
definitions/game/game/inspection/infoProviders/UnlockableRowInfoProvider.d.ts
|
TypeScript
|
MethodDeclaration
|
protected onRefresh(): void;
|
WaywardGame/types
|
definitions/game/game/inspection/infoProviders/UnlockableRowInfoProvider.d.ts
|
TypeScript
|
ClassDeclaration
|
@Component({
selector: 'sbb-icon-sa-sn',
// tslint:disable:max-line-length
template: `
<svg
focusable="false"
[attr.class]="'sbb-svg-icon ' + svgClass"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 26 16"
>
<path
fill-rule="evenodd"
d="M3.307 14.267c-.35-.529-.64-1-.87-1.407-.232-.411-.528-1.02-.894-1.833C1.183 10.215 1 9.207 1 8.004c0-1.167.196-2.207.59-3.123.393-.913.967-1.954 1.717-3.12h1.274c-.412.72-.727 1.304-.947 1.75a25.028 25.028 0 00-.78 1.831c-.303.776-.455 1.669-.455 2.68 0 1.035.164 1.97.499 2.805.333.836.59 1.442.771 1.814.183.373.486.913.91 1.624H3.307v.002zm6.782-4.478L8.18 7.64l-.855-1.028a3.595 3.595 0 01-.693-2.162c0-1.095.404-2.127 1.21-3.1l.2-.216L8.14 1l4.84 5.462-.005-2.067 3.742-3.393.887.953-3.324 3.015.002 1.59 4.101-3.758.915.979-4.127 3.753 1.616.104L20.1 4.647l.908.937-3.725 3.393-2.2-.143 4.145 4.674L17.52 15l-4.284-4.835-.093-.343-.106.325L7.724 15l-1.527-1.652 3.892-3.56zM8.214 3.474c-.061.145-.104.286-.128.425a2.487 2.487 0 00-.035.406c0 .664.246 1.278.741 1.844l.51.576 1.834 2.095 1.086-.972-3.856-4.38-.134-.355-.018.361zM23.04 1.76c.69 1.07 1.248 2.081 1.673 3.032.423.95.636 2.02.636 3.212 0 .59-.06 1.173-.18 1.75a8.222 8.222 0 01-.52 1.632 15.05 15.05 0 01-.627 1.291c-.193.35-.522.878-.982 1.59H21.77c.425-.735.74-1.315.945-1.741.206-.426.463-1.035.772-1.823.309-.787.466-1.694.466-2.716 0-1.023-.162-1.947-.483-2.77-.321-.824-.581-1.432-.78-1.823-.202-.39-.507-.936-.92-1.634h1.272z"
/>
</svg>
`,
// tslint:enable:max-line-length
changeDetection: ChangeDetectionStrategy.OnPush
})
export class IconSaSnComponent extends IconBase {
constructor() {
super({ width: '26px', height: '16px', ratio: 1.625 });
}
}
|
davide1995/sbb-angular
|
projects/sbb-esta/angular-icons/src/lib/timetable-attributes/icon-sa-sn.module.ts
|
TypeScript
|
ClassDeclaration
|
@NgModule({
imports: [CommonModule],
declarations: [IconSaSnComponent],
exports: [IconSaSnComponent]
})
export class IconSaSnModule {}
|
davide1995/sbb-angular
|
projects/sbb-esta/angular-icons/src/lib/timetable-attributes/icon-sa-sn.module.ts
|
TypeScript
|
FunctionDeclaration
|
async function fetchMyCAPTCHA() {
const res = await fetch('/api/captcha', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ page: 'login' })
});
if (res.status === 200) {
const resp = await res.json();
setCaptcha({ svg: resp.svg, encryptedExpr: resp.encryptedExpr, hasCaptcha: resp.hasCaptcha });
} else {
const msg = await res.text();
setErrorMsg(msg);
}
}
|
FORTH-ICS-INSPIRE/artemis-web
|
apps/artemis-web/components/login/login.tsx
|
TypeScript
|
FunctionDeclaration
|
async function onClick(e, endpoint) {
e.preventDefault();
const res = await fetch(endpoint, {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ ...formData, _csrf: props._csrf, encryptedExpr: captcha.encryptedExpr }),
});
if (res.status === 200) {
localStorage.setItem('login_timestamp', new Date().toString());
const token = await res.json();
if (token.user.role === 'pending') {
router.push('/pending');
} else {
router.push('/dashboard');
}
window.location.reload();
} else {
const msg = await res.text();
setErrorMsg(msg);
fetchMyCAPTCHA();
}
}
|
FORTH-ICS-INSPIRE/artemis-web
|
apps/artemis-web/components/login/login.tsx
|
TypeScript
|
ArrowFunction
|
(props: any): any => {
const [errorMsg, setErrorMsg] = useState('');
const [formData, setFormData] = useState({
email: '',
password: '',
rememberMe: false,
captcha: ''
});
async function fetchMyCAPTCHA() {
const res = await fetch('/api/captcha', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ page: 'login' })
});
if (res.status === 200) {
const resp = await res.json();
setCaptcha({ svg: resp.svg, encryptedExpr: resp.encryptedExpr, hasCaptcha: resp.hasCaptcha });
} else {
const msg = await res.text();
setErrorMsg(msg);
}
}
const [captcha, setCaptcha] = useState({ svg: '', encryptedExpr: '', hasCaptcha: false });
const router = useRouter();
async function onClick(e, endpoint) {
e.preventDefault();
const res = await fetch(endpoint, {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ ...formData, _csrf: props._csrf, encryptedExpr: captcha.encryptedExpr }),
});
if (res.status === 200) {
localStorage.setItem('login_timestamp', new Date().toString());
const token = await res.json();
if (token.user.role === 'pending') {
router.push('/pending');
} else {
router.push('/dashboard');
}
window.location.reload();
} else {
const msg = await res.text();
setErrorMsg(msg);
fetchMyCAPTCHA();
}
}
useEffect(() => {
fetchMyCAPTCHA();
}, []);
return (
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="sm">
<div className={props.classes.paper}>
<img
width="150"
src="./login.png"
alt="avatar"
className="img-responsive"
/>
<Typography
className={props.classes.input}
component="h1"
variant="h5"
>
Sign In
</Typography>
{errorMsg && <p className="error">{errorMsg}</p>}
<form method="post" className="login-form">
<input name="stype" type="hidden" defaultValue="login" />
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
color="primary"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
onChange={(e)
|
FORTH-ICS-INSPIRE/artemis-web
|
apps/artemis-web/components/login/login.tsx
|
TypeScript
|
ArrowFunction
|
() => {
fetchMyCAPTCHA();
}
|
FORTH-ICS-INSPIRE/artemis-web
|
apps/artemis-web/components/login/login.tsx
|
TypeScript
|
ArrowFunction
|
(props) => {
const classes = useStyles();
return <Login {...props} classes={classes} />;
}
|
FORTH-ICS-INSPIRE/artemis-web
|
apps/artemis-web/components/login/login.tsx
|
TypeScript
|
ArrowFunction
|
() => ({ cart: {}, displayCart: [] } as State)
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
ArrowFunction
|
(ci : Product) => {
if (ci.id === product.id) {
isAdded = true
return { id: ci.id, qty: ci.qty + 1 }
}
return { id: ci.id, qty: ci.qty }
}
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
ArrowFunction
|
ci => ci.id !== id
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
ArrowFunction
|
ci => {
const requiredProduct = productData.filter(p => p.id === ci.id)
// if (requiredProduct[0].stock >= ci.qty)
return {
id: ci.id,
name: requiredProduct[0].name,
price: requiredProduct[0].price,
qty: ci.qty,
color: requiredProduct[0].color,
currency: requiredProduct[0].currency,
instock: requiredProduct[0].stock >= ci.qty,
}
}
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
ArrowFunction
|
p => p.id === ci.id
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
InterfaceDeclaration
|
// interface Cart {
// cid: string
// products: Array<{id: number, qty: number}>
// }
interface State{
cart: Cart | {}
displayCart: DisplayCart [] | []
}
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
MethodDeclaration
|
loadCartInstance() {
const cs = localStorage.getItem('cart')
if (!cs)
this.cart = {}
else
this.cart = JSON.parse(cs)
}
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
MethodDeclaration
|
addToCart(product: Product) {
const cs = localStorage.getItem('cart')
let isAdded = false
if (!cs) {
this.cart = {
cid: uuid4(),
products: [product],
}
}
else {
const cartLocalStorage = JSON.parse(cs)
cartLocalStorage.products = cartLocalStorage.products.map((ci : Product) => {
if (ci.id === product.id) {
isAdded = true
return { id: ci.id, qty: ci.qty + 1 }
}
return { id: ci.id, qty: ci.qty }
})
if (!isAdded)
cartLocalStorage.products.push({ id: product.id, qty: product.qty })
this.cart = cartLocalStorage
}
localStorage.setItem('cart', JSON.stringify(this.cart))
}
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
MethodDeclaration
|
removeFromCart(id: number) {
(this.cart as Cart).products = (this.cart as Cart).products.filter(ci => ci.id !== id)
this.displayCartLoad()
localStorage.setItem('cart')
}
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
MethodDeclaration
|
displayCartLoad() {
this.displayCart = (this.cart as Cart).products.map(ci => {
const requiredProduct = productData.filter(p => p.id === ci.id)
// if (requiredProduct[0].stock >= ci.qty)
return {
id: ci.id,
name: requiredProduct[0].name,
price: requiredProduct[0].price,
qty: ci.qty,
color: requiredProduct[0].color,
currency: requiredProduct[0].currency,
instock: requiredProduct[0].stock >= ci.qty,
}
})
}
|
Pepe1776/monsteria-vitesse
|
src/stores/cart.ts
|
TypeScript
|
FunctionDeclaration
|
export default function Features(): JSX.Element {
const [flow, setFlow] = React.useState([]);
return (
<div className='d-flex flex-row'>
<RMap className='example-map' initial={{center: fromLonLat([2.364, 48.82]), zoom: 11}}
|
fogracvxy/rlayers
|
examples/Features.tsx
|
TypeScript
|
ArrowFunction
|
(p) => `<li className="m-0">${p}</li>`
|
fogracvxy/rlayers
|
examples/Features.tsx
|
TypeScript
|
MethodDeclaration
|
useCallback(
|
fogracvxy/rlayers
|
examples/Features.tsx
|
TypeScript
|
ClassDeclaration
|
export class IsListOperator extends Operator implements IOperator {
/**
* Loop while the condition is true.
*/
public call(engine: Engine, args: Array<any>): Object {
if (engine.eval(args[0]) instanceof Array) {
return true;
} else {
return false;
}
}
}
|
alphaKAI/ChickenClisp_ts
|
operator/IsListOperator.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Loop while the condition is true.
*/
public call(engine: Engine, args: Array<any>): Object {
if (engine.eval(args[0]) instanceof Array) {
return true;
} else {
return false;
}
}
|
alphaKAI/ChickenClisp_ts
|
operator/IsListOperator.ts
|
TypeScript
|
FunctionDeclaration
|
function defineCustomPatternSpec(variant, customPattern) {
it(variant, () => {
let time = 1
function extraContextValidator(
text,
offset,
tokens,
groups
) {
let result = isFunction(customPattern)
? customPattern(text, offset)
: customPattern.exec(text, offset)
if (result !== null) {
if (time === 1) {
expect(tokens).to.be.empty
time++
} else if (time === 2) {
expect(tokens).to.have.lengthOf(2)
expect(
groups.whitespace
).to.have.lengthOf(2)
time++
} else {
throw Error(
"Issue with Custom Token pattern context"
)
}
}
return result
}
let A = createToken({
name: "A",
pattern: "A"
})
let B = createToken({
name: "B",
pattern: <any>extraContextValidator
})
let WS = createToken({
name: "WS",
pattern: {
exec: (text, offset) =>
/^\s+/.exec(text.substring(offset))
},
group: "whitespace",
line_breaks: true
})
let lexerDef: any = [WS, A, B]
let myLexer = new Lexer(lexerDef, lexerConfig)
let lexResult = myLexer.tokenize("B A\n B ")
expect(lexResult.tokens).to.have.length(3)
expect(tokenMatcher(lexResult.tokens[0], B)).to.be
.true
expect(tokenMatcher(lexResult.tokens[1], A)).to.be
.true
expect(tokenMatcher(lexResult.tokens[2], B)).to.be
.true
let lastToken = lexResult.tokens[2]
expect(lastToken.startOffset).to.equal(5)
if (testStart) {
expect(lastToken.startLine).to.equal(2)
expect(lastToken.startColumn).to.equal(2)
}
if (testFull) {
expect(lastToken.endLine).to.equal(2)
expect(lastToken.endColumn).to.equal(2)
expect(lastToken.endOffset).to.equal(5)
}
})
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
FunctionDeclaration
|
function extraContextValidator(
text,
offset,
tokens,
groups
) {
let result = isFunction(customPattern)
? customPattern(text, offset)
: customPattern.exec(text, offset)
if (result !== null) {
if (time === 1) {
expect(tokens).to.be.empty
time++
} else if (time === 2) {
expect(tokens).to.have.lengthOf(2)
expect(
groups.whitespace
).to.have.lengthOf(2)
time++
} else {
throw Error(
"Issue with Custom Token pattern context"
)
}
}
return result
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
FunctionDeclaration
|
function wrapWithCustom(baseExtendToken) {
return function() {
let newToken = baseExtendToken.apply(null, arguments)
let pattern = newToken.PATTERN
if (
isRegExp(pattern) &&
!/\\n|\\r|\\s/g.test(pattern.source) &&
pattern !== Lexer.NA
) {
newToken.PATTERN = function(text, offset) {
// can't use sticky here because tests on node.js version 4 won't pass.
let withStart = addStartOfInput(pattern)
let execResult = withStart.exec(text.substring(offset))
return execResult
}
}
return newToken
}
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
it("can create a token from a string with priority to the First Token Type with the longest match #1", () => {
// this can match either IdentifierTok or BambaTok but should match BambaTok has its pattern is defined before IdentifierTok
let input = "bamba"
let result = testLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], BambaTok)).to.be.true
expect(result.tokens[0].image).to.equal("bamba")
expect(result.tokens[0].startOffset).to.equal(0)
})
it("can create a token from a string with priority to the First Token Type with the longest match #2", () => {
let input = "bambaMIA"
let result = testLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], IdentifierTok)).to.be.true
expect(result.tokens[0].image).to.equal("bambaMIA")
expect(result.tokens[0].startOffset).to.equal(0)
})
it("can create a token from a string with priority to the First Token Type with the longest match - negative", () => {
const IntegerTok = createToken({
name: "IntegerTok",
pattern: /[1-9]\d*/
})
const IdentTok = createToken({
name: "IdentifierTok",
pattern: /[A-Za-z]+/
})
// a bit contrived to test all code branches, the BambaTok is not actually prefix of Identifier tok due to the "_"
const BambaTok = createToken({
name: "BambaTok",
pattern: /_bamba/
})
BambaTok.LONGER_ALT = IdentTok
const myLexer = new Lexer([BambaTok, IntegerTok, IdentTok], {
positionTracking: "onlyOffset"
})
let input = "_bamba123"
let result = myLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], BambaTok)).to.be.true
expect(result.tokens[0].image).to.equal("_bamba")
expect(tokenMatcher(result.tokens[1], IntegerTok)).to.be.true
expect(result.tokens[1].image).to.equal("123")
})
it("can create a token from a string", () => {
let input = "6666543221231"
let result = testLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], IntegerTok)).to.be.true
expect(result.tokens[0].image).to.equal("6666543221231")
expect(result.tokens[0].startOffset).to.equal(0)
})
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
// this can match either IdentifierTok or BambaTok but should match BambaTok has its pattern is defined before IdentifierTok
let input = "bamba"
let result = testLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], BambaTok)).to.be.true
expect(result.tokens[0].image).to.equal("bamba")
expect(result.tokens[0].startOffset).to.equal(0)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let input = "bambaMIA"
let result = testLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], IdentifierTok)).to.be.true
expect(result.tokens[0].image).to.equal("bambaMIA")
expect(result.tokens[0].startOffset).to.equal(0)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
const IntegerTok = createToken({
name: "IntegerTok",
pattern: /[1-9]\d*/
})
const IdentTok = createToken({
name: "IdentifierTok",
pattern: /[A-Za-z]+/
})
// a bit contrived to test all code branches, the BambaTok is not actually prefix of Identifier tok due to the "_"
const BambaTok = createToken({
name: "BambaTok",
pattern: /_bamba/
})
BambaTok.LONGER_ALT = IdentTok
const myLexer = new Lexer([BambaTok, IntegerTok, IdentTok], {
positionTracking: "onlyOffset"
})
let input = "_bamba123"
let result = myLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], BambaTok)).to.be.true
expect(result.tokens[0].image).to.equal("_bamba")
expect(tokenMatcher(result.tokens[1], IntegerTok)).to.be.true
expect(result.tokens[1].image).to.equal("123")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let input = "6666543221231"
let result = testLexer.tokenize(input)
expect(tokenMatcher(result.tokens[0], IntegerTok)).to.be.true
expect(result.tokens[0].image).to.equal("6666543221231")
expect(result.tokens[0].startOffset).to.equal(0)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let result = findMissingPatterns([
BambaTok,
IntegerTok,
IdentifierTok
])
expect(result.errors).to.be.empty
expect(result.valid).to.deep.equal([
BambaTok,
IntegerTok,
IdentifierTok
])
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [ValidNaPattern, MissingPattern]
let result = findMissingPatterns(tokenClasses)
expect(result.errors.length).to.equal(1)
expect(result.errors[0].tokenTypes).to.deep.equal([
MissingPattern
])
expect(result.errors[0].type).to.equal(
LexerDefinitionErrorType.MISSING_PATTERN
)
expect(result.errors[0].message).to.contain(
"MissingPattern"
)
expect(result.valid).to.deep.equal([ValidNaPattern])
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let result = findInvalidPatterns([
BambaTok,
IntegerTok,
IdentifierTok,
ValidNaPattern
])
expect(result.errors).to.be.empty
expect(result.valid).to.deep.equal([
BambaTok,
IntegerTok,
IdentifierTok,
ValidNaPattern
])
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [ValidNaPattern, InvalidPattern]
let result = findInvalidPatterns(tokenClasses)
expect(result.errors.length).to.equal(1)
expect(result.errors[0].tokenTypes).to.deep.equal([
InvalidPattern
])
expect(result.errors[0].type).to.equal(
LexerDefinitionErrorType.INVALID_PATTERN
)
expect(result.errors[0].message).to.contain(
"InvalidPattern"
)
expect(result.valid).to.deep.equal([ValidNaPattern])
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let errors = findUnsupportedFlags([
BambaTok,
IntegerTok,
IdentifierTok,
CaseInsensitivePattern
])
expect(errors).to.be.empty
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [ValidNaPattern, MultiLinePattern]
let errors = findUnsupportedFlags(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([
MultiLinePattern
])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND
)
expect(errors[0].message).to.contain("MultiLinePattern")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [ValidNaPattern, GlobalPattern]
let errors = findUnsupportedFlags(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([GlobalPattern])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND
)
expect(errors[0].message).to.contain("GlobalPattern")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let errors = findDuplicatePatterns([
MultiLinePattern,
IntegerValid
])
expect(errors).to.be.empty
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let errors = findDuplicatePatterns([
ValidNaPattern,
ValidNaPattern2
])
expect(errors).to.be.empty
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let InvalidToken = createToken({
name: "InvalidToken",
pattern: /BAMBA$/
})
let tokenClasses = [ValidNaPattern, InvalidToken]
let errors = findEndOfInputAnchor(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([InvalidToken])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.EOI_ANCHOR_FOUND
)
expect(errors[0].message).to.contain("InvalidToken")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let errors = findEndOfInputAnchor([
IntegerTok,
IntegerValid
])
expect(errors).to.be.empty
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let InvalidToken = createToken({
name: "InvalidToken",
pattern: /^BAMBA/
})
let tokenClasses = [ValidNaPattern, InvalidToken]
let errors = findStartOfInputAnchor(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([InvalidToken])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.SOI_ANCHOR_FOUND
)
expect(errors[0].message).to.contain("InvalidToken")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
const ClassKeyword = createToken({
name: "ClassKeyword",
pattern: /class/
})
const Identifier = createToken({
name: "Identifier",
pattern: /\w+/
})
let tokenClasses = [Identifier, ClassKeyword]
let errors = findUnreachablePatterns(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([
Identifier,
ClassKeyword
])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.UNREACHABLE_PATTERN
)
expect(errors[0].message).to.contain("can never be matched")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let negationPattern = createToken({
name: "negationPattern",
pattern: /[^\\]/
})
let errors = findStartOfInputAnchor([negationPattern])
expect(errors).to.be.empty
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let errors = findStartOfInputAnchor([
IntegerTok,
IntegerValid
])
expect(errors).to.be.empty
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [DecimalInvalid, IntegerValid]
let errors = findDuplicatePatterns(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([
DecimalInvalid,
IntegerValid
])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND
)
expect(errors[0].message).to.contain("IntegerValid")
expect(errors[0].message).to.contain("DecimalInvalid")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
// should use \d+ as * allows zero repetitions
const emptyMatch = createToken({
name: "emptyMatch",
pattern: /\d*/
})
let tokenClasses = [emptyMatch]
let errors = findEmptyMatchRegExps(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([emptyMatch])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.EMPTY_MATCH_PATTERN
)
expect(errors[0].message).to.contain("emptyMatch")
expect(errors[0].message).to.contain(
"must not match an empty string"
)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let errors = findInvalidGroupType([
IntegerTok,
Skipped,
Special
])
//noinspection BadExpressionStatementJS
expect(errors).to.be.empty
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [InvalidGroupNumber]
let errors = findInvalidGroupType(tokenClasses)
expect(errors.length).to.equal(1)
expect(errors[0].tokenTypes).to.deep.equal([
InvalidGroupNumber
])
expect(errors[0].type).to.equal(
LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND
)
expect(errors[0].message).to.contain("InvalidGroupNumber")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
it("can transform a pattern to one with startOfInput mark ('^') #1 (NO OP)", () => {
let orgSource = (<any>BambaTok.PATTERN).source
let transPattern = addStartOfInput(<any>BambaTok.PATTERN)
expect(transPattern.source).to.equal("^(?:" + orgSource + ")")
expect(/^\^/.test(transPattern.source)).to.equal(true)
})
it("can transform a pattern to one with startOfInput mark ('^') #2", () => {
let orgSource = PatternNoStart.PATTERN.source
let transPattern = addStartOfInput(PatternNoStart.PATTERN)
expect(transPattern.source).to.equal("^(?:" + orgSource + ")")
expect(/^\^/.test(transPattern.source)).to.equal(true)
})
if (!skipValidationChecks) {
it("can transform/analyze an array of Token Typees into matched/ignored/patternToClass", () => {
let tokenClasses = [
Keyword,
If,
Else,
Return,
Integer,
Punctuation,
LParen,
RParen,
Whitespace,
NewLine
]
let analyzeResult = analyzeTokenTypes(tokenClasses, {
useSticky: false
})
let allPatterns = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.pattern
)
expect(allPatterns.length).to.equal(8)
let allPatternsString = map(allPatterns, pattern => {
return isString(pattern) ? pattern : pattern.source
})
setEquality(allPatternsString, [
"^(?:(\\t| ))",
"^(?:(\\n|\\r|\\r\\n))",
"^(?:[1-9]\\d*)",
"(",
")",
"^(?:if)",
"^(?:else)",
"^(?:return)"
])
let patternIdxToClass = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.tokenType
)
expect(keys(patternIdxToClass).length).to.equal(8)
expect(patternIdxToClass[0]).to.equal(If)
expect(patternIdxToClass[1]).to.equal(Else)
expect(patternIdxToClass[2]).to.equal(Return)
expect(patternIdxToClass[3]).to.equal(Integer)
expect(patternIdxToClass[4]).to.equal(LParen)
expect(patternIdxToClass[5]).to.equal(RParen)
expect(patternIdxToClass[6]).to.equal(Whitespace)
expect(patternIdxToClass[7]).to.equal(NewLine)
})
}
if (!skipValidationChecks && ORG_SUPPORT_STICKY) {
it("can transform/analyze an array of Token Typees into matched/ignored/patternToClass - sticky", () => {
let tokenClasses = [
Keyword,
If,
Else,
Return,
Integer,
Punctuation,
LParen,
RParen,
Whitespace,
NewLine
]
// on newer node.js this will run with the 2nd argument as true.
let analyzeResult = analyzeTokenTypes(tokenClasses, {
useSticky: true
})
let allPatterns = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.pattern
)
expect(allPatterns.length).to.equal(8)
let allPatternsString = map(allPatterns, pattern => {
return isString(pattern) ? pattern : pattern.source
})
setEquality(allPatternsString, [
"(\\t| )",
"(\\n|\\r|\\r\\n)",
"(",
")",
"[1-9]\\d*",
"if",
"else",
"return"
])
forEach(allPatterns, currPattern => {
if (isRegExp(currPattern)) {
expect(currPattern.sticky).to.be.true
}
})
let patternIdxToClass = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.tokenType
)
expect(keys(patternIdxToClass).length).to.equal(8)
expect(patternIdxToClass[0]).to.equal(If)
expect(patternIdxToClass[1]).to.equal(Else)
expect(patternIdxToClass[2]).to.equal(Return)
expect(patternIdxToClass[3]).to.equal(Integer)
expect(patternIdxToClass[4]).to.equal(LParen)
expect(patternIdxToClass[5]).to.equal(RParen)
expect(patternIdxToClass[6]).to.equal(Whitespace)
expect(patternIdxToClass[7]).to.equal(NewLine)
})
}
it("can count the number of line terminators in a string", () => {
let ltCounter = new Lexer([
createToken({
name: "lt",
pattern: /\s+/,
line_breaks: true
}),
createToken({
name: "num",
pattern: /\d+/
})
])
let lastToken = last(ltCounter.tokenize("1\r\n1\r1").tokens)
expect(lastToken.startLine).to.equal(3)
let lastToken2 = last(
ltCounter.tokenize("\r\r\r1234\r\n1").tokens
)
expect(lastToken2.startLine).to.equal(5)
expect(lastToken2.startColumn).to.equal(1)
let lastToken3 = last(ltCounter.tokenize("2\r3\n\r4\n5").tokens)
expect(lastToken3.startLine).to.equal(5)
})
it("can count the number of line terminators in a string - string literal patterns", () => {
let ltCounter = new Lexer([
createToken({
name: "lt",
pattern: "\n",
line_breaks: true
}),
createToken({
name: "num",
pattern: /\d+/
})
])
let lastToken = last(ltCounter.tokenize("1\n1\n1").tokens)
expect(lastToken.startLine).to.equal(3)
})
it("Supports custom Line Terminators", () => {
let WS = createToken({
name: "WS",
pattern: /\u2028/,
line_breaks: true,
group: Lexer.SKIPPED
})
let ifElseLexer = new Lexer([WS, If, Else], {
lineTerminatorsPattern: /\u2028/g
})
let input = "if\u2028elseif"
let lexResult = ifElseLexer.tokenize(input)
let tokens: any = lexResult.tokens
expect(tokens[0].image).to.equal("if")
expect(tokens[0].startLine).to.equal(1)
expect(tokens[0].startColumn).to.equal(1)
expect(tokens[1].image).to.equal("else")
expect(tokens[1].startLine).to.equal(2)
expect(tokens[1].startColumn).to.equal(1)
expect(tokens[2].image).to.equal("if")
expect(tokens[2].startLine).to.equal(2)
expect(tokens[2].startColumn).to.equal(5)
})
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let orgSource = (<any>BambaTok.PATTERN).source
let transPattern = addStartOfInput(<any>BambaTok.PATTERN)
expect(transPattern.source).to.equal("^(?:" + orgSource + ")")
expect(/^\^/.test(transPattern.source)).to.equal(true)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let orgSource = PatternNoStart.PATTERN.source
let transPattern = addStartOfInput(PatternNoStart.PATTERN)
expect(transPattern.source).to.equal("^(?:" + orgSource + ")")
expect(/^\^/.test(transPattern.source)).to.equal(true)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [
Keyword,
If,
Else,
Return,
Integer,
Punctuation,
LParen,
RParen,
Whitespace,
NewLine
]
let analyzeResult = analyzeTokenTypes(tokenClasses, {
useSticky: false
})
let allPatterns = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.pattern
)
expect(allPatterns.length).to.equal(8)
let allPatternsString = map(allPatterns, pattern => {
return isString(pattern) ? pattern : pattern.source
})
setEquality(allPatternsString, [
"^(?:(\\t| ))",
"^(?:(\\n|\\r|\\r\\n))",
"^(?:[1-9]\\d*)",
"(",
")",
"^(?:if)",
"^(?:else)",
"^(?:return)"
])
let patternIdxToClass = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.tokenType
)
expect(keys(patternIdxToClass).length).to.equal(8)
expect(patternIdxToClass[0]).to.equal(If)
expect(patternIdxToClass[1]).to.equal(Else)
expect(patternIdxToClass[2]).to.equal(Return)
expect(patternIdxToClass[3]).to.equal(Integer)
expect(patternIdxToClass[4]).to.equal(LParen)
expect(patternIdxToClass[5]).to.equal(RParen)
expect(patternIdxToClass[6]).to.equal(Whitespace)
expect(patternIdxToClass[7]).to.equal(NewLine)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
currConfig => currConfig.pattern
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
pattern => {
return isString(pattern) ? pattern : pattern.source
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
currConfig => currConfig.tokenType
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let tokenClasses = [
Keyword,
If,
Else,
Return,
Integer,
Punctuation,
LParen,
RParen,
Whitespace,
NewLine
]
// on newer node.js this will run with the 2nd argument as true.
let analyzeResult = analyzeTokenTypes(tokenClasses, {
useSticky: true
})
let allPatterns = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.pattern
)
expect(allPatterns.length).to.equal(8)
let allPatternsString = map(allPatterns, pattern => {
return isString(pattern) ? pattern : pattern.source
})
setEquality(allPatternsString, [
"(\\t| )",
"(\\n|\\r|\\r\\n)",
"(",
")",
"[1-9]\\d*",
"if",
"else",
"return"
])
forEach(allPatterns, currPattern => {
if (isRegExp(currPattern)) {
expect(currPattern.sticky).to.be.true
}
})
let patternIdxToClass = map(
analyzeResult.patternIdxToConfig,
currConfig => currConfig.tokenType
)
expect(keys(patternIdxToClass).length).to.equal(8)
expect(patternIdxToClass[0]).to.equal(If)
expect(patternIdxToClass[1]).to.equal(Else)
expect(patternIdxToClass[2]).to.equal(Return)
expect(patternIdxToClass[3]).to.equal(Integer)
expect(patternIdxToClass[4]).to.equal(LParen)
expect(patternIdxToClass[5]).to.equal(RParen)
expect(patternIdxToClass[6]).to.equal(Whitespace)
expect(patternIdxToClass[7]).to.equal(NewLine)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
currPattern => {
if (isRegExp(currPattern)) {
expect(currPattern.sticky).to.be.true
}
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ltCounter = new Lexer([
createToken({
name: "lt",
pattern: /\s+/,
line_breaks: true
}),
createToken({
name: "num",
pattern: /\d+/
})
])
let lastToken = last(ltCounter.tokenize("1\r\n1\r1").tokens)
expect(lastToken.startLine).to.equal(3)
let lastToken2 = last(
ltCounter.tokenize("\r\r\r1234\r\n1").tokens
)
expect(lastToken2.startLine).to.equal(5)
expect(lastToken2.startColumn).to.equal(1)
let lastToken3 = last(ltCounter.tokenize("2\r3\n\r4\n5").tokens)
expect(lastToken3.startLine).to.equal(5)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ltCounter = new Lexer([
createToken({
name: "lt",
pattern: "\n",
line_breaks: true
}),
createToken({
name: "num",
pattern: /\d+/
})
])
let lastToken = last(ltCounter.tokenize("1\n1\n1").tokens)
expect(lastToken.startLine).to.equal(3)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let WS = createToken({
name: "WS",
pattern: /\u2028/,
line_breaks: true,
group: Lexer.SKIPPED
})
let ifElseLexer = new Lexer([WS, If, Else], {
lineTerminatorsPattern: /\u2028/g
})
let input = "if\u2028elseif"
let lexResult = ifElseLexer.tokenize(input)
let tokens: any = lexResult.tokens
expect(tokens[0].image).to.equal("if")
expect(tokens[0].startLine).to.equal(1)
expect(tokens[0].startColumn).to.equal(1)
expect(tokens[1].image).to.equal("else")
expect(tokens[1].startLine).to.equal(2)
expect(tokens[1].startColumn).to.equal(1)
expect(tokens[2].image).to.equal("if")
expect(tokens[2].startLine).to.equal(2)
expect(tokens[2].startColumn).to.equal(5)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
const workflow = createToken({
name: "workflow",
pattern: /WORKFLOW/i
})
const input = "worKFloW"
const lexer = new Lexer([workflow], {
positionTracking: "onlyOffset"
})
let lexResult = lexer.tokenize(input)
let tokens: any = lexResult.tokens
expect(tokens[0].image).to.equal("worKFloW")
expect(tokens[0].tokenType).to.equal(workflow)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let Tab = createToken({
name: "Tab",
pattern: /\t/,
group: "spaces"
})
let ifElseLexer = new Lexer([Tab, If, Else], {
positionTracking: "onlyOffset"
})
let input = "if\telse"
let lexResult = ifElseLexer.tokenize(input)
let tokens: any = lexResult.tokens
expect(tokens[0].image).to.equal("if")
expect(tokens[1].image).to.equal("else")
let spacesGroups: any = lexResult.groups.spaces
expect(spacesGroups[0].image).to.equal("\t")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
const IfOrElse = createToken({
name: "IfOrElse",
pattern: /if|else/,
start_chars_hint: ["i", "e".charCodeAt(0)]
})
let ifElseLexer = new Lexer([IfOrElse], {
positionTracking: "onlyOffset"
})
let input = "ifelse"
let lexResult = ifElseLexer.tokenize(input)
let tokens: any = lexResult.tokens
expect(tokens[0].image).to.equal("if")
expect(tokens[1].image).to.equal("else")
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[
Keyword,
If,
Else,
Return,
Integer,
Punctuation,
LParen,
RParen,
Whitespace,
NewLine
],
lexerConfig
)
//noinspection BadExpressionStatementJS
expect(ifElseLexer.lexerDefinitionErrors).to.be.empty
let input = "if (666) reTurn 1\n" + "\telse return 2"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.groups).to.be.empty
expect(lexResult.tokens[0].image).to.equal("if")
expect(lexResult.tokens[0].startOffset).to.equal(0)
if (testStart) {
expect(lexResult.tokens[0].startLine).to.equal(1)
expect(lexResult.tokens[0].startColumn).to.equal(1)
}
if (testFull) {
expect(lexResult.tokens[0].endOffset).to.equal(1)
}
expect(tokenMatcher(lexResult.tokens[0], If)).to.be.true
expect(lexResult.tokens[1].image).to.equal("(")
expect(lexResult.tokens[1].startOffset).to.equal(3)
if (testStart) {
expect(lexResult.tokens[1].startLine).to.equal(1)
expect(lexResult.tokens[1].startColumn).to.equal(4)
}
if (testFull) {
expect(lexResult.tokens[1].endOffset).to.equal(3)
}
expect(tokenMatcher(lexResult.tokens[1], LParen)).to.be.true
expect(lexResult.tokens[2].image).to.equal("666")
expect(lexResult.tokens[2].startOffset).to.equal(4)
if (testStart) {
expect(lexResult.tokens[2].startLine).to.equal(1)
expect(lexResult.tokens[2].startColumn).to.equal(5)
}
if (testFull) {
expect(lexResult.tokens[2].endOffset).to.equal(6)
}
expect(tokenMatcher(lexResult.tokens[2], Integer)).to.be.true
expect(lexResult.tokens[3].image).to.equal(")")
expect(lexResult.tokens[3].startOffset).to.equal(7)
if (testStart) {
if (testStart) {
expect(lexResult.tokens[3].startLine).to.equal(1)
expect(lexResult.tokens[3].startColumn).to.equal(8)
}
}
if (testFull) {
expect(lexResult.tokens[3].endOffset).to.equal(7)
}
expect(tokenMatcher(lexResult.tokens[3], RParen)).to.be.true
expect(lexResult.tokens[4].image).to.equal("reTurn")
expect(lexResult.tokens[4].startOffset).to.equal(9)
if (testStart) {
expect(lexResult.tokens[4].startLine).to.equal(1)
expect(lexResult.tokens[4].startColumn).to.equal(10)
}
if (testFull) {
expect(lexResult.tokens[4].endOffset).to.equal(14)
}
expect(tokenMatcher(lexResult.tokens[4], Return)).to.be.true
expect(lexResult.tokens[5].image).to.equal("1")
expect(lexResult.tokens[5].startOffset).to.equal(16)
if (testStart) {
expect(lexResult.tokens[5].startLine).to.equal(1)
expect(lexResult.tokens[5].startColumn).to.equal(17)
}
if (testFull) {
expect(lexResult.tokens[5].endOffset).to.equal(16)
}
expect(tokenMatcher(lexResult.tokens[5], Integer)).to.be.true
expect(lexResult.tokens[6].image).to.equal("else")
expect(lexResult.tokens[6].startOffset).to.equal(19)
if (testStart) {
expect(lexResult.tokens[6].startLine).to.equal(2)
expect(lexResult.tokens[6].startColumn).to.equal(2)
}
if (testFull) {
expect(lexResult.tokens[6].endOffset).to.equal(22)
}
expect(tokenMatcher(lexResult.tokens[6], Else)).to.be.true
expect(lexResult.tokens[7].image).to.equal("return")
expect(lexResult.tokens[7].startOffset).to.equal(24)
if (testStart) {
expect(lexResult.tokens[7].startLine).to.equal(2)
expect(lexResult.tokens[7].startColumn).to.equal(7)
}
if (testFull) {
expect(lexResult.tokens[7].endOffset).to.equal(29)
}
expect(tokenMatcher(lexResult.tokens[7], Return)).to.be.true
expect(lexResult.tokens[8].image).to.equal("2")
expect(lexResult.tokens[8].startOffset).to.equal(31)
if (testStart) {
expect(lexResult.tokens[8].startLine).to.equal(2)
expect(lexResult.tokens[8].startColumn).to.equal(14)
}
if (testFull) {
expect(lexResult.tokens[8].endOffset).to.equal(31)
}
expect(tokenMatcher(lexResult.tokens[8], Integer)).to.be.true
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
expect(
() =>
new Lexer([], {
positionTracking: <any>"oops"
})
).to.throw(
"Invalid <positionTracking> config option:" + ' "oops"'
)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() =>
new Lexer([], {
positionTracking: <any>"oops"
})
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
expect(() => new Lexer([], <any>false)).to.throw(
"The second argument to the Lexer constructor is now an ILexerConfig"
)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => new Lexer([], <any>false)
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
expect(
() => new Lexer([EndOfInputAnchor, If, Else]),
lexerConfig
).to.throw(/Errors detected in definition of Lexer/)
expect(
() => new Lexer([EndOfInputAnchor, If, Else]),
lexerConfig
).to.throw(/EndOfInputAnchor/)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => new Lexer([EndOfInputAnchor, If, Else])
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
expect(
() =>
new Lexer([EndOfInputAnchor, If, Else], {
deferDefinitionErrorsHandling: true
})
).to.not.throw(/Errors detected in definition of Lexer/)
expect(
() =>
new Lexer([EndOfInputAnchor, If, Else], {
deferDefinitionErrorsHandling: true
})
).to.not.throw(/EndOfInputAnchor/)
let lexerWithErrs = new Lexer(
[EndOfInputAnchor, If, Else],
{
deferDefinitionErrorsHandling: true
}
)
//noinspection BadExpressionStatementJS
expect(lexerWithErrs.lexerDefinitionErrors).to.not.be.empty
// even when the Error handling is deferred, actual usage of an invalid lexer is not permitted!
expect(() => lexerWithErrs.tokenize("else")).to.throw(
/Unable to Tokenize because Errors detected in definition of Lexer/
)
expect(() => lexerWithErrs.tokenize("else")).to.throw(
/EndOfInputAnchor/
)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() =>
new Lexer([EndOfInputAnchor, If, Else], {
deferDefinitionErrorsHandling: true
})
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => lexerWithErrs.tokenize("else")
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[
Keyword,
If,
Else,
Return,
Integer,
Punctuation,
LParen,
RParen,
Whitespace,
NewLine
],
lexerConfig
)
let input = "if (666) return 1@#$@#$\n" + "\telse return 2"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.errors.length).to.equal(1)
expect(lexResult.errors[0].message).to.contain("@")
expect(lexResult.errors[0].length).to.equal(6)
if (testStart) {
expect(lexResult.errors[0].line).to.equal(1)
expect(lexResult.errors[0].column).to.equal(18)
} else {
expect(lexResult.errors[0].line).to.be.undefined
expect(lexResult.errors[0].column).to.be.undefined
}
expect(lexResult.tokens[0].image).to.equal("if")
expect(lexResult.tokens[0].startOffset).to.equal(0)
if (testStart) {
expect(lexResult.tokens[0].startLine).to.equal(1)
expect(lexResult.tokens[0].startColumn).to.equal(1)
}
expect(tokenMatcher(lexResult.tokens[0], If)).to.be.true
expect(lexResult.tokens[1].image).to.equal("(")
expect(lexResult.tokens[1].startOffset).to.equal(3)
if (testStart) {
expect(lexResult.tokens[1].startLine).to.equal(1)
expect(lexResult.tokens[1].startColumn).to.equal(4)
}
expect(tokenMatcher(lexResult.tokens[1], LParen)).to.be.true
expect(lexResult.tokens[2].image).to.equal("666")
expect(lexResult.tokens[2].startOffset).to.equal(4)
if (testStart) {
expect(lexResult.tokens[2].startLine).to.equal(1)
expect(lexResult.tokens[2].startColumn).to.equal(5)
}
expect(tokenMatcher(lexResult.tokens[2], Integer)).to.be.true
expect(lexResult.tokens[3].image).to.equal(")")
expect(lexResult.tokens[3].startOffset).to.equal(7)
if (testStart) {
expect(lexResult.tokens[3].startLine).to.equal(1)
expect(lexResult.tokens[3].startColumn).to.equal(8)
}
expect(tokenMatcher(lexResult.tokens[3], RParen)).to.be.true
expect(lexResult.tokens[4].image).to.equal("return")
expect(lexResult.tokens[4].startOffset).to.equal(9)
if (testStart) {
expect(lexResult.tokens[4].startLine).to.equal(1)
expect(lexResult.tokens[4].startColumn).to.equal(10)
}
expect(tokenMatcher(lexResult.tokens[4], Return)).to.be.true
expect(lexResult.tokens[5].image).to.equal("1")
expect(lexResult.tokens[5].startOffset).to.equal(16)
if (testStart) {
expect(lexResult.tokens[5].startLine).to.equal(1)
expect(lexResult.tokens[5].startColumn).to.equal(17)
}
expect(tokenMatcher(lexResult.tokens[5], Integer)).to.be.true
expect(lexResult.tokens[6].image).to.equal("else")
expect(lexResult.tokens[6].startOffset).to.equal(25)
if (testStart) {
expect(lexResult.tokens[6].startLine).to.equal(2)
expect(lexResult.tokens[6].startColumn).to.equal(2)
}
expect(tokenMatcher(lexResult.tokens[6], Else)).to.be.true
expect(lexResult.tokens[7].image).to.equal("return")
expect(lexResult.tokens[7].startOffset).to.equal(30)
if (testStart) {
expect(lexResult.tokens[7].startLine).to.equal(2)
expect(lexResult.tokens[7].startColumn).to.equal(7)
}
expect(tokenMatcher(lexResult.tokens[7], Return)).to.be.true
expect(lexResult.tokens[8].image).to.equal("2")
expect(lexResult.tokens[8].startOffset).to.equal(37)
if (testStart) {
expect(lexResult.tokens[8].startLine).to.equal(2)
expect(lexResult.tokens[8].startColumn).to.equal(14)
}
expect(tokenMatcher(lexResult.tokens[8], Integer)).to.be.true
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[
Keyword,
If,
Else,
Return,
Integer,
Punctuation,
LParen,
RParen,
Whitespace,
NewLine
],
lexerConfig
)
let input = "if&&&&&&&&&&&&&&&&&&&&&&&&&&&&"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.errors.length).to.equal(1)
expect(lexResult.errors[0].message).to.contain("&")
if (testStart) {
expect(lexResult.errors[0].line).to.equal(1)
expect(lexResult.errors[0].column).to.equal(3)
} else {
expect(lexResult.errors[0].line).to.be.undefined
expect(lexResult.errors[0].column).to.be.undefined
}
expect(lexResult.errors[0].length).to.equal(28)
expect(lexResult.tokens[0].image).to.equal("if")
expect(lexResult.tokens[0].startOffset).to.equal(0)
if (testStart) {
expect(lexResult.tokens[0].startLine).to.equal(1)
expect(lexResult.tokens[0].startColumn).to.equal(1)
}
expect(tokenMatcher(lexResult.tokens[0], If)).to.be.true
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[If, Else, WhitespaceNotSkipped],
lexerConfig
)
let input = "if\r\r\telse\rif\n"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.tokens[0].image).to.equal("if")
expect(lexResult.tokens[0].startOffset).to.equal(0)
if (testStart) {
expect(lexResult.tokens[0].startLine).to.equal(1)
expect(lexResult.tokens[0].startColumn).to.equal(1)
}
if (testFull) {
expect(lexResult.tokens[0].endLine).to.equal(1)
expect(lexResult.tokens[0].endColumn).to.equal(2)
}
expect(tokenMatcher(lexResult.tokens[0], If)).to.be.true
expect(lexResult.tokens[1].image).to.equal("\r\r\t")
expect(lexResult.tokens[1].startOffset).to.equal(2)
if (testStart) {
expect(lexResult.tokens[1].startLine).to.equal(1)
expect(lexResult.tokens[1].startColumn).to.equal(3)
}
if (testFull) {
expect(lexResult.tokens[1].endLine).to.equal(3)
expect(lexResult.tokens[1].endColumn).to.equal(1)
}
expect(tokenMatcher(lexResult.tokens[1], WhitespaceNotSkipped))
.to.be.true
expect(lexResult.tokens[2].image).to.equal("else")
expect(lexResult.tokens[2].startOffset).to.equal(5)
if (testStart) {
expect(lexResult.tokens[2].startLine).to.equal(3)
expect(lexResult.tokens[2].startColumn).to.equal(2)
}
if (testFull) {
expect(lexResult.tokens[2].endLine).to.equal(3)
expect(lexResult.tokens[2].endColumn).to.equal(5)
}
expect(tokenMatcher(lexResult.tokens[2], Else)).to.be.true
expect(lexResult.tokens[3].image).to.equal("\r")
expect(lexResult.tokens[3].startOffset).to.equal(9)
if (testStart) {
expect(lexResult.tokens[3].startLine).to.equal(3)
expect(lexResult.tokens[3].startColumn).to.equal(6)
}
if (testFull) {
expect(lexResult.tokens[3].endLine).to.equal(3)
expect(lexResult.tokens[3].endColumn).to.equal(6)
}
expect(tokenMatcher(lexResult.tokens[3], WhitespaceNotSkipped))
.to.be.true
expect(lexResult.tokens[4].image).to.equal("if")
expect(lexResult.tokens[4].startOffset).to.equal(10)
if (testStart) {
expect(lexResult.tokens[4].startLine).to.equal(4)
expect(lexResult.tokens[4].startColumn).to.equal(1)
}
if (testFull) {
expect(lexResult.tokens[4].endLine).to.equal(4)
expect(lexResult.tokens[4].endColumn).to.equal(2)
}
expect(tokenMatcher(lexResult.tokens[4], If)).to.be.true
expect(lexResult.tokens[5].image).to.equal("\n")
expect(lexResult.tokens[5].startOffset).to.equal(12)
if (testStart) {
expect(lexResult.tokens[5].startLine).to.equal(4)
expect(lexResult.tokens[5].startColumn).to.equal(3)
}
if (testFull) {
expect(lexResult.tokens[5].endLine).to.equal(4)
expect(lexResult.tokens[5].endColumn).to.equal(3)
}
expect(tokenMatcher(lexResult.tokens[5], WhitespaceNotSkipped))
.to.be.true
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[If, Else, WhitespaceOrAmp],
lexerConfig
)
let input = "if\r\r\telse&if"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.tokens[0].image).to.equal("if")
expect(lexResult.tokens[0].startOffset).to.equal(0)
if (testStart) {
expect(lexResult.tokens[0].startLine).to.equal(1)
expect(lexResult.tokens[0].startColumn).to.equal(1)
}
if (testFull) {
expect(lexResult.tokens[0].endLine).to.equal(1)
expect(lexResult.tokens[0].endColumn).to.equal(2)
}
expect(tokenMatcher(lexResult.tokens[0], If)).to.be.true
expect(lexResult.tokens[1].image).to.equal("\r\r\t")
expect(lexResult.tokens[1].startOffset).to.equal(2)
if (testStart) {
expect(lexResult.tokens[1].startLine).to.equal(1)
expect(lexResult.tokens[1].startColumn).to.equal(3)
}
if (testFull) {
expect(lexResult.tokens[1].endLine).to.equal(3)
expect(lexResult.tokens[1].endColumn).to.equal(1)
}
expect(tokenMatcher(lexResult.tokens[1], WhitespaceOrAmp)).to.be
.true
expect(lexResult.tokens[2].image).to.equal("else")
expect(lexResult.tokens[2].startOffset).to.equal(5)
if (testStart) {
expect(lexResult.tokens[2].startLine).to.equal(3)
expect(lexResult.tokens[2].startColumn).to.equal(2)
}
if (testFull) {
expect(lexResult.tokens[2].endLine).to.equal(3)
expect(lexResult.tokens[2].endColumn).to.equal(5)
}
expect(tokenMatcher(lexResult.tokens[2], Else)).to.be.true
expect(lexResult.tokens[3].image).to.equal("&")
expect(lexResult.tokens[3].startOffset).to.equal(9)
if (testStart) {
expect(lexResult.tokens[3].startLine).to.equal(3)
expect(lexResult.tokens[3].startColumn).to.equal(6)
}
if (testFull) {
expect(lexResult.tokens[3].endLine).to.equal(3)
expect(lexResult.tokens[3].endColumn).to.equal(6)
}
expect(tokenMatcher(lexResult.tokens[3], WhitespaceOrAmp)).to.be
.true
expect(lexResult.tokens[4].image).to.equal("if")
expect(lexResult.tokens[4].startOffset).to.equal(10)
if (testStart) {
expect(lexResult.tokens[4].startLine).to.equal(3)
expect(lexResult.tokens[4].startColumn).to.equal(7)
}
if (testFull) {
expect(lexResult.tokens[4].endLine).to.equal(3)
expect(lexResult.tokens[4].endColumn).to.equal(8)
}
expect(tokenMatcher(lexResult.tokens[4], If)).to.be.true
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[If, Else, Comment, NewLine],
lexerConfig
)
let input = "if//else"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.tokens[0].image).to.equal("if")
expect(lexResult.tokens[0].startOffset).to.equal(0)
if (testStart) {
expect(lexResult.tokens[0].startLine).to.equal(1)
expect(lexResult.tokens[0].startColumn).to.equal(1)
}
if (testFull) {
expect(lexResult.tokens[0].endLine).to.equal(1)
expect(lexResult.tokens[0].endColumn).to.equal(2)
}
expect(tokenMatcher(lexResult.tokens[0], If)).to.be.true
expect(lexResult.groups).to.have.property("comments")
// tslint:disable
expect(lexResult.groups["comments"]).to.have.length(1)
let comment = lexResult.groups["comments"][0]
// tslint:enable
expect(comment.image).to.equal("//else")
expect(comment.startOffset).to.equal(2)
if (testStart) {
expect(comment.startLine).to.equal(1)
expect(comment.startColumn).to.equal(3)
}
if (testFull) {
expect(comment.endLine).to.equal(1)
expect(comment.endColumn).to.equal(8)
}
expect(tokenMatcher(comment, Comment)).to.be.true
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[If, Else, Comment, NewLine],
lexerConfig
)
let input = "if//else"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.groups).to.have.property("comments")
// tslint:disable
expect(lexResult.groups["comments"]).to.have.length(1)
// tslint:enable
// 2th time
lexResult = ifElseLexer.tokenize(input)
expect(lexResult.groups).to.have.property("comments")
// tslint:disable
expect(lexResult.groups["comments"]).to.have.length(1)
// tslint:enable
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
let ifElseLexer = new Lexer(
[If, PileOfPoo, NewLine],
lexerConfig
)
let input = "if💩"
let lexResult = ifElseLexer.tokenize(input)
expect(lexResult.tokens[0].image).to.equal("if")
expect(lexResult.tokens[0].tokenType).to.equal(If)
expect(lexResult.tokens[1].image).to.equal("💩")
expect(lexResult.tokens[1].tokenType).to.equal(PileOfPoo)
}
|
benjie/chevrotain
|
test/scan/lexer_spec.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.